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

在使用PyTorch的nn.CrossEntropyLoss计算损失时遇到错误:RuntimeError:0Dor1Dtargettensorexpected,multi-targetnotsupported。原因是输入的label不应为one-hot格式。解决方法是使用适合多标签问题的损失函数,如MultiLabelSoftMarginLoss或MSELoss。确保label输入为非one-hot的类别索引。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考链接:交叉熵报错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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值