交叉熵报错 RuntimeError: 1D target tensor expected, multi-target not supported

参考链接:交叉熵报错RuntimeError: 1D target tensor expected, multi-target not supported

使用 nn.CrossEntropyLoss() 时报错:

RuntimeError: 0D or 1D target tensor expected, multi-target not supported

pytorch 中计计算交叉熵损失函数时, 输入的正确 label 不能是 one-hot 格式。函数内部会自己处理成 one hot 格式。所以不需要输入 [ 0 0 0 0 1],只需要输入 4 就行。

在经过 loss 的时候,CrossEntropyLoss 会自动为其编码为 one-hot 编码,这样就会导致其升高一维。

所以解决方案就是采用多标签问题的损失函数。比如 MultiLabelSoftMarginLoss,或者我采用的最原始的 MSELoss。

你可能感兴趣的:(python,疑难杂症,python)