torch.nn.CTCLoss 与warpctc_pytoch.CTCLoss

1.torch.nn.CTCLoss

import torch
from torch.nn import CTCLoss

torch.backends.cudnn.benchmark = True
T = 50      # Input sequence length
C = 20      # Number of classes (including blank)
N = 16      # Batch size
S = 30     # Target sequence length of longest target in batch
S_min = 10
torch.manual_seed(1234)

input = torch.randn(T, N, C).log_softmax(2).detach().requires_grad_()
target = torch.randint(low=1, high=C, 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)

critenzer = CTCLoss()
loss = critenzer(input,target,input_lengths,target_lengths)
loss.backward()
loss

output:

tensor(10.5236, grad_fn=< MeanBackward0>)

2.warpctc_pytorch CTCLoss

源码见github: warpctc-pytorch

from warpctc_pytorch import CTCLoss as ctc

probs = torch.FloatTensor([[[0.1, 0.6, 0.1, 0.1, 0.1], [0.1, 0.1, 0.6, 0.1, 0.1]]]).transpose(0, 1).contiguous()
labels = torch.IntTensor([1, 2])
label_sizes = torch.IntTensor([2])
probs_sizes = torch.IntTensor([2])
probs.requires_grad_(True)  # tells autograd to compute gradients for probs

output:

tensor([2.4629], grad_fn=<_CTCBackward>)

    probs: Tensor of (seqLength x batch x outputDim) containing output from network
    
    labels: 1 dimensional Tensor containing all the targets of the batch in one sequence
    
    probs_lens: Tensor of size (batch) containing size of each output sequence from the network
    
    label_lens: Tensor of (batch) containing label length of each example

3. 总结

  1. warp中labels的size应是N*S或 sum(target_lens)
  2. torch.nn中的labels的size应为(N,S)或sum(target_lens)
  3. 区别似乎主要在log_softmax()
  4. 尽量还是先用warpctc
torch.nn.CrossEntropyLoss是PyTorch中常用的交叉熵损失函数之一。它结合了torch.nn.LogSoftmax和torch.nn.NLLLoss两个函数,用于多分类问题的训练中。交叉熵损失函数常用于衡量模型输出与真实标签之间的差异。 在torch.nn.CrossEntropyLoss中,输入的形状为(batch_size, num_classes),其中batch_size是每个训练批次的样本数量,num_classes是分类的类别数量。在训练过程中,模型输出的结果会通过torch.nn.LogSoftmax函数进行处理,得到对应的概率分布。然后,模型预测的概率分布与真实标签之间会被计算交叉熵损失。 交叉熵损失函数的计算公式如下: loss = -sum(y_true * log(y_pred)) 其中,y_true是真实标签的概率分布,y_pred是模型预测的概率分布。 torch.nn.CrossEntropyLoss会自动将模型输出的概率分布进行归一化,并进行log运算。因此,在使用torch.nn.CrossEntropyLoss时,不需要手动应用torch.nn.LogSoftmax函数。 需要注意的是,torch.nn.CrossEntropyLoss函数的输入不包含softmax层。如果模型的最后一层是softmax层,可以直接使用torch.nn.CrossEntropyLoss来计算损失。如果模型的最后一层是logits层(未经过softmax激活),可以使用torch.nn.CrossEntropyLoss配合torch.nn.LogSoftmax来计算损失。 总结起来,torch.nn.CrossEntropyLoss是PyTorch中用于多分类问题训练的交叉熵损失函数,它结合了torch.nn.LogSoftmax和torch.nn.NLLLoss两个函数,并且可以适用于不同形式的模型输出。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值