我正在学习pytorch,并将基于tensorflow (https://github.com/matthewearl/deep-anpr,http://matthewearl.github.io/2016/05/06/cnn-anpr/)的anpr项目作为练习,将其移植到pytorch平台。
有一个问题,我使用nn.CrossEntropyLoss()作为损失函数:
criterion=nn.CrossEntropyLoss()模型的output.data为:
- 1.00000e-02 *
- 2.5552 2.7582 2.5368 ... 5.6184 1.2288 -0.0076
- 0.7033 1.3167 -1.0966 ... 4.7249 1.3217 1.8367
- 0.7592 1.4777 1.8095 ... 0.8733 1.2417 1.1521
- 0.1040 -0.7054 -3.4862 ... 4.7703 2.9595 1.4263
- [torch.FloatTensor of size 4x253]targets.data是:
- 1 0 0 ... 0 0 0
- 1 0 0 ... 0 0 0
- 1 0 0 ... 0 0 0
- 1 0 0 ... 0 0 0
- [torch.DoubleTensor of size 4x253]当我调用时:
loss=criterion(output,targets)发生错误,信息为:
TypeError: FloatClassNLLCriterion_updateOutput received an invalid combination of arguments - got (int, torch.FloatTensor, **torch.DoubleTensor**, torch.FloatTensor, bool, NoneType, torch.FloatTensor), but expected (int state, torch.FloatTensor input, **torch.LongTensor** target, torch.FloatTensor output, bool sizeAverage, [torch.FloatTensor weights or None], torch.FloatTensor total_weight)
'expected torch.LongTensor'......'got torch.DoubleTensor',but if i convert the targets into LongTensor:
torch.LongTensor(numpy.array(targets.data.numpy(),numpy.long))调用loss=criterion(output,targets),错误为:
RuntimeError: multi-target not supported at /data/users/soumith/miniconda2/conda-bld/pytorch-0.1.10_1488752595704/work/torch/lib/THNN/generic/ClassNLLCriterion.c:20我的最后一个练习是mnist,来自pytorch的一个例子,我做了一点修改,batch_size是4,损失函数:
loss = F.nll_loss(outputs, labels)outputs.data:
- -2.3220 -2.1229 -2.3395 -2.3391 -2.5270 -2.3269 -2.1055 -2.2321 -2.4943 -2.2996
-2.3653 -2.2034 -2.4437 -2.2708 -2.5114 -2.3286 -2.1921 -2.1771 -2.3343 -2.2533
-2.2809 -2.2119 -2.3872 -2.2190 -2.4610 -2.2946 -2.2053 -2.3192 -2.3674 -2.3100
-2.3715 -2.1455 -2.4199 -2.4177 -2.4565 -2.2812 -2.2467 -2.1144 -2.3321 -2.3009
[torch.FloatTensor of size 4x10]labels.data:
- 8
- 6
- 0
- 1
- [torch.LongTensor of size 4]对于输入图像,标签必须是单个元素,在上面的示例中,有253个数字,而在'mnist‘中,只有一个数字,输出的形状与标签不同。
我回顾了tensorflow手册tf.nn.softmax_cross_entropy_with_logits,“Logit和labels必须具有相同的形状batch_size、num_classes和相同的数据类型( float32或float64)。”
pytorch是否支持tensorflow中的相同函数?
很多东西
发布于 2017-05-06 03:18:36
您可以将您拥有的目标转换为分类表示。在您提供的示例中,您将有1 0 0 0..如果类为0,则为0,0 10 0 ...如果类是1,0 0 1 0 0...如果类是2等,我能想到的一种快速方法是首先将目标张量转换为numpy数组,然后将其从一个hot数组转换为一个分类数组,然后再将其转换回pytorch张量。如下所示:
targetnp=targets.numpy()
idxs=np.where(targetnp>0)[1]
new_targets=torch.LongTensor(idxs)
loss=criterion(output,new_targets)发布于 2017-12-05 20:40:13
CrossEntropyLoss等同于tf.nn.softmax_cross_entropy_with_logits。CrossEntropyLoss的输入是shape batch_size的分类向量。使用.view()更改张量形状。
labels = labels.view(-1) output = output.view(labels.size(0), -1) loss = criterion(output, loss)
调用.view(x, y, -1)会导致张量使用剩余的数据点来填充-1维度,如果没有足够的数据点来生成完整的维度,则会导致错误
labels.size(0)给出了label张量的0维的大小
附加
要在张量类型之间进行转换,可以调用张量上的类型,例如'labels = labels.long()`
第二个附加
如果你像output.data这样从一个变量中解压数据,那么你将会丢失该输出的渐变,并且在时机成熟的时候无法支持
https://stackoverflow.com/questions/43406693
复制相似问题