pytorch
shape_error
ai_generated
true
运行时错误:预期一维目标张量,不支持多目标
RuntimeError: 1D target tensor expected, multi-target not supported
ID: pytorch/invalid-argument-2d-index-target
90%修复率
88%置信度
1证据数
2023-08-20首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| pytorch>=1.13.0 | active | — | — | — |
根因分析
损失函数(如 CrossEntropyLoss)接收到的目标张量维度超过一维(例如独热编码标签),而非一维类别索引张量。
English
A loss function like CrossEntropyLoss received a target tensor with more than one dimension (e.g., one-hot encoded labels) instead of a 1D tensor of class indices.
官方文档
https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html解决方案
-
在传递给损失函数之前,使用 `torch.argmax(target, dim=1)` 将独热编码标签转换为类别索引。示例:`loss = criterion(output, target.argmax(dim=1))`
-
如果目标已经是 1D 但由于批处理有额外维度,则挤压它:`target = target.squeeze()`。
-
如果任务是多标签分类,则使用 `torch.nn.BCEWithLogitsLoss` 并具有正确的目标形状(与输出相同)。
无效尝试
常见但无效的做法:
-
95% 失败
This still produces a 2D tensor; the loss expects 1D indices.
-
90% 失败
The error is about dimensionality, not dtype; CrossEntropyLoss expects Long type indices.
-
80% 失败
BCEWithLogitsLoss expects a different shape and value range; it will not fix the dimensionality issue.