RuntimeError: multi-target not supported at

1. 出错代码行
计算交叉熵是出现异常提示:RuntimeError: multi-target not supported at /opt/conda/conda-bld/pytorch_1549635019666/work/aten/src/THNN/generic/ClassNLLCriterion.c:21

loss = criterion(prediction, target)
2 原因:
CrossEntropyLoss does not expect a one-hot encoded vector as the target, but class indices
pytorch 中计计算交叉熵损失函数时, 输入的正确 label 不能是 one-hot 格式。函数内部会自己处理成 one hot 格式。所以不需要输入 [ 0 0 0 0 1],只需要输入 4 就行。

print(prediction.size())
print(target.size())
print("target = ", target)
loss = criterion(prediction, target)
# 输出给过如下
torch.Size([2, 145]) # 输入两个数据,每个数据的有145个值
torch.Size([2]) # target(ground true) 是两个值,每个数据一个值
target = tensor([4, 4]) # 两个数据具体的 target 值,都是4

3. 解决方法:
更改 dataloader 中 dataset 中 def __getitem__(self, index) 返回的 target 的内容(将 one hot 格式改成 数字格式 就行)。
如果 target 的size 不是一维的话,需要添加一行代码,如下:
target = target.squeeze() # 添加这一行,用于降维度(从 torch.Size([2, 1]) 降成torch.Size([2]) ) ,即 target 从[ [4], [4]] 降成 [ 4, 4 ]
loss = criterion(prediction, target)

4. 总结
pytorch 中使用神经网络进行多分类时,网路的输出 prediction 是 one hot 格式,但计算 交叉熵损失函数时,loss = criterion(prediction, target) 的输入 target 不能是 one hot 格式,直接用数字来表示就行(4 表示 one hot 中的 0 0 0 0 1)。
所以,自己构建数据集,返回的 target 不需要是 one hot 格式。

  

 

posted @ 2019-12-10 20:11  闪存第一菜鸡  阅读(16227)  评论(0编辑  收藏  举报