# 运行时错误：预期一维目标张量，不支持多目标

- **ID:** `pytorch/invalid-argument-2d-index-target`
- **领域:** pytorch
- **类别:** shape_error
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

损失函数（如 CrossEntropyLoss）接收到的目标张量维度超过一维（例如独热编码标签），而非一维类别索引张量。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| pytorch>=1.13.0 | active | — | — |

## 解决方案

1. ```
   在传递给损失函数之前，使用 `torch.argmax(target, dim=1)` 将独热编码标签转换为类别索引。示例：`loss = criterion(output, target.argmax(dim=1))`
   ```
2. ```
   如果目标已经是 1D 但由于批处理有额外维度，则挤压它：`target = target.squeeze()`。
   ```
3. ```
   如果任务是多标签分类，则使用 `torch.nn.BCEWithLogitsLoss` 并具有正确的目标形状（与输出相同）。
   ```

## 无效尝试

- **** — This still produces a 2D tensor; the loss expects 1D indices. (95% 失败率)
- **** — The error is about dimensionality, not dtype; CrossEntropyLoss expects Long type indices. (90% 失败率)
- **** — BCEWithLogitsLoss expects a different shape and value range; it will not fix the dimensionality issue. (80% 失败率)
