Есть ли разница между "torch.nn.CTCLoss", поддерживаемым PYTORCH, и "CTCLoss", поддерживаемым torch_baidu_ctc? - PullRequest
0 голосов
/ 03 мая 2019

Есть ли разница между "torch.nn.CTCLoss", поддерживаемым PYTORCH, и "CTCLoss", поддерживаемым torch_baidu_ctc?

Я думаю, я не заметил никакой разницы при сравнении учебного кода.

Кто-нибудь знает правду?

Код учебника находится ниже.

import torch
from torch_baidu_ctc import ctc_loss, CTCLoss

# Activations. Shape T x N x D.
# T -> max number of frames/timesteps
# N -> minibatch size
# D -> number of output labels (including the CTC blank)
x = torch.rand(10, 3, 6)
# Target labels
y = torch.tensor([
# 1st sample
1, 1, 2, 5, 2,
# 2nd
1, 5, 2,
# 3rd
4, 4, 2, 3,
],
dtype=torch.int,
)
# Activations lengths
xs = torch.tensor([10, 6, 9], dtype=torch.int)
# Target lengths
ys = torch.tensor([5, 3, 4], dtype=torch.int)

# By default, the costs (negative log-likelihood) of all samples are 
summed.
# This is equivalent to:
#   ctc_loss(x, y, xs, ys, average_frames=False, reduction="sum")
loss1 = ctc_loss(x, y, xs, ys)

# You can also average the cost of each sample among the number of 
frames.
# The averaged costs are then summed.
loss2 = ctc_loss(x, y, xs, ys, average_frames=True)

# Instead of summing the costs of each sample, you can perform
# other `reductions`: "none", "sum", or "mean"
#
# Return an array with the loss of each individual sample
losses = ctc_loss(x, y, xs, ys, reduction="none")
#
# Compute the mean of the individual losses
loss3 = ctc_loss(x, y, xs, ys, reduction="mean")
#
# First, normalize loss by number of frames, later average losses
loss4 = ctc_loss(x, y, xs, ys, average_frames=True, reduction="mean")


# Finally, there's also a nn.Module to use this loss.
ctc = CTCLoss(average_frames=True, reduction="mean", blank=0)
loss4_2 = ctc(x, y, xs, ys)

# Note: the `blank` option is also available for `ctc_loss`.
# By default it is 0.

torch.nn.CTCLoss

T = 50      # Input sequence length
C = 20      # Number of classes (excluding blank)
N = 16      # Batch size
S = 30      # Target sequence length of longest target in batch
S_min = 10  # Minimum target length, for demonstration purposes

# Initialize random batch of input vectors, for *size = (T,N,C)
input = torch.randn(T, N, C).log_softmax(2).detach().requires_grad_()

# Initialize random batch of targets (0 = blank, 1:C+1 = classes)
target = torch.randint(low=1, high=C+1, size=(N, S), dtype=torch.long)

input_lengths = torch.full(size=(N,), fill_value=T, dtype=torch.long)
target_lengths = torch.randint(low=S_min, high=S, size=(N,), 
dtype=torch.long)
ctc_loss = nn.CTCLoss()
loss = ctc_loss(input, target, input_lengths, target_lengths)
loss.backward()

Я кореец. Английский не мой родной язык. Так что я плохо разбираюсь в английском. Если есть что-то, что не доставлено хорошо, пожалуйста, оставьте комментарий. Я изменю предложение как можно скорее.

Ответы [ 2 ]

0 голосов
/ 22 мая 2019

Позаботьтесь о том, чтобы потери CTC Pytorch принимали логарифмические вероятности softmax в качестве входных данных, в то время как потери CTC от Baidu не упоминают об этом.

0 голосов
/ 03 мая 2019

CTC теряет только часть PyTorch начиная с версии 1.0 , и это лучший путь, потому что он изначально является частью PyTorch.Если вы используете PyTorch 1.0 или новее, используйте torch.nn.CTCLoss.

warp-ctc , похоже, не поддерживается, последние коммиты, изменяющие код ядра, относятся к 2017 году. Позже онитолько фиксированные привязки для (уже устаревшей версии) TensorFlow.

...