如何在pytorch中使用GRU正确使用CTC损失?

时间:2020-06-07 20:32:13

标签: pytorch ctc

我正在尝试创建ASR,但我仍在学习,因此,我只是在尝试使用简单的GRU:

MySpeechRecognition(
  (gru): GRU(128, 128, num_layers=5, batch_first=True, dropout=0.5)
  (dropout): Dropout(p=0.3, inplace=False)
  (fc1): Linear(in_features=128, out_features=512, bias=True)
  (fc2): Linear(in_features=512, out_features=28, bias=True)
)

将每个输出分类为可能的字母+空格+空白。

然后我使用CTC损失函数和Adam优化器:

lr = 5e-4
criterion = nn.CTCLoss(blank=28, zero_infinity=False)
optimizer = torch.optim.Adam(net.parameters(), lr=lr)

在我的训练循环中(我仅显示有问题的区域):

output, h = mynet(specs, h)
print(output.size())
output = F.log_softmax(output, dim=2)
output = output.transpose(0,1)
# calculate the loss and perform backprop
loss = criterion(output, labels, input_lengths, label_lengths)
loss.backward()

我收到此错误:

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-133-5e47e7b03a46> in <module>
     42         output = output.transpose(0,1)
     43         # calculate the loss and perform backprop
---> 44         loss = criterion(output, labels, input_lengths, label_lengths)
     45         loss.backward()
     46         # `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs.

/opt/conda/lib/python3.7/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
    548             result = self._slow_forward(*input, **kwargs)
    549         else:
--> 550             result = self.forward(*input, **kwargs)
    551         for hook in self._forward_hooks.values():
    552             hook_result = hook(self, input, result)

/opt/conda/lib/python3.7/site-packages/torch/nn/modules/loss.py in forward(self, log_probs, targets, input_lengths, target_lengths)
   1309     def forward(self, log_probs, targets, input_lengths, target_lengths):
   1310         return F.ctc_loss(log_probs, targets, input_lengths, target_lengths, self.blank, self.reduction,
-> 1311                           self.zero_infinity)
   1312 
   1313 # TODO: L1HingeEmbeddingCriterion

/opt/conda/lib/python3.7/site-packages/torch/nn/functional.py in ctc_loss(log_probs, targets, input_lengths, target_lengths, blank, reduction, zero_infinity)
   2050     """
   2051     return torch.ctc_loss(log_probs, targets, input_lengths, target_lengths, blank, _Reduction.get_enum(reduction),
-> 2052                           zero_infinity)
   2053 
   2054 

RuntimeError: blank must be in label range

我不确定为什么会出现此错误。我尝试更改为

labels.float()

谢谢。

1 个答案:

答案 0 :(得分:2)

您的模型预测28个类别,因此该模型的输出的大小为 [batch_size,seq_len,28] (或日志的 [seq_len,batch_size,28] CTC损失的概率)。在nn.CTCLoss中设置blank=28,这意味着空白标签是索引为28的类。要获取空白标签的日志概率,可以将其索引为output[:, :, 28],但是不起作用,因为该索引超出范围,因为有效索引为0到27。

输出中的最后一个类在索引27处,因此应为blank=27

criterion = nn.CTCLoss(blank=27, zero_infinity=False)