Python 图片分类:解决"IndexError: index 1 is out of bounds for dimension 0 with size 1" 错误
这个错误是由于索引超出范围导致的。根据报错信息,问题出现在第294行的列表推导式中。
你可以尝试使用print语句来输出相关的变量,以便进一步调试。可能的原因是top5_indices或top5_probs的维度不正确,导致索引超出范围。你可以检查一下这两个变量的形状,并确保它们具有正确的维度。另外,你还可以检查一下real_labels的长度,确保它与top5_indices的第一维度大小一致。
以下是代码片段和可能的解决方法:
for file_name in os.listdir(data_dir):
# 加载图像文件
image_path = os.path.join(data_dir, file_name)
image_paths.append(image_path)
image = Image.open(image_path).convert('RGB')
# 对图像进行预处理
image_tensor = transform(image)
image_batch = image_tensor.unsqueeze(0)
# 在模型上进行预测
with torch.no_grad():
image_batch = image_batch.cuda(non_blocking=True)
output = model(image_batch)
_, predicted = torch.max(output, 1)
predictions.extend(predicted.cpu().numpy())
top5_probs, top5_indices = torch.topk(torch.softmax(output, dim=1), k=5)
top5_predictions.append(top5_probs.cpu().numpy())
with open('real_labels.txt', 'r') as real_file:
real_labels = [line.strip() for line in real_file.readlines()]
with open('predictions.txt', 'w') as file:
for i in range(len(predictions)):
file.write(f"{image_paths[i]} ")
# 打印top5_indices和top5_probs的形状,检查维度是否正确
print(f"top5_indices.shape: {top5_indices.shape}")
print(f"top5_probs.shape: {top5_probs.shape}")
file.write(f"Top 5 Predictions: {[(real_labels[top5_indices[i][j]], top5_probs[i][j]) for j in range(5)]}
")
调试步骤:
- 打印
top5_indices和top5_probs的形状,检查维度是否正确。如果top5_indices的第一维度大小为1,则意味着只预测了一个类别,而top5_indices[i][1]就会超出范围。 - 检查
real_labels的长度,确保它与top5_indices的第一维度大小一致。如果real_labels的长度小于top5_indices的第一维度大小,则会出现索引超出范围的错误。
解决方案:
- 确保
top5_indices的维度与real_labels的长度匹配。如果top5_indices的第一维度大小为1,则可以修改代码,只取第一个预测结果,或者在模型训练时确保模型输出至少5个类别。 - 确保
real_labels的长度与top5_indices的第一维度大小一致。如果real_labels的长度不够,可以添加占位符或调整模型输出的大小。
通过调试和修复代码,可以解决这个索引超出范围的错误,使程序正常运行。
原文地址: https://www.cveoy.top/t/topic/qfGM 著作权归作者所有。请勿转载和采集!