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 (target)不能是 one-hot 格式。所以只需要输入数字 4 就行,不需要输入 one hot 格式的 [ 0 0 0 0 1]。函数内部会自己处理成 one hot 格式。
loss = criterion(prediction, target)
print(prediction.size()) # 模型计算(预测)出的结果
print(target.size()) # ground true/标签/label
print("target = ", target)
输出结果如下
torch.Size([2, 145]) # 输入两个数据,每个数据的有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 格式。
5. 参考链接:
https://discuss.pytorch.org/t/runtimeerror-multi-target-not-supported-newbie/10216/3
完