PyTorch模型训练报错:IndexError: Target 25越界求助
解决IndexError: Target 25 is out of bounds的问题
问题根源
- 输出层维度不匹配:数据集包含6个类别,但模型输出层
nn.Linear(in_features=32, out_features=5)仅设置了5个输出神经元,CrossEntropyLoss会默认类别索引范围是0-4,无法匹配实际类别数量。 - 标签格式不符合要求:你的标签是
[9,12,15,18,21,25]这类原始离散值,但PyTorch的CrossEntropyLoss要求目标标签必须是从0开始的连续整数索引(0到类别数-1),25远超出当前模型支持的索引范围,因此触发越界错误。
解决方案
步骤1:修正模型输出层神经元数量
将输出层的out_features改为6,对应6个类别:
class HourPredictor(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(in_features=14, out_features=64) self.fc2 = nn.Linear(in_features=64, out_features=32) self.output = nn.Linear(in_features=32, out_features=6) # 从5改为6 def forward(self, x): x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.output(x) return x
步骤2:将原始标签转换为类别索引
需要把原始标签映射为0-5的连续整数,推荐两种方法:
方法一:用LabelEncoder预处理(适合批量数据)
from sklearn.preprocessing import LabelEncoder # 假设原始标签存储在labels变量中 label_encoder = LabelEncoder() encoded_labels = label_encoder.fit_transform(labels) # 转换后encoded_labels对应原始标签的索引为[0,1,2,3,4,5]
方法二:手动字典映射(无需额外依赖)
label_mapping = {9:0, 12:1, 15:2, 18:3, 21:4, 25:5} # 转换标签并转为PyTorch张量 encoded_labels = torch.tensor([label_mapping[label] for label in labels], dtype=torch.long)
验证说明
修改后,模型输出维度为(batch_size,6),标签范围是0-5的整数,CrossEntropyLoss可正常计算,不会再触发索引越界错误。
内容的提问来源于stack exchange,提问作者Ammar Ahmed Siddiqui
相关产品推荐
相关产品推荐

