Jupyter Notebook运行PyTorch代码遇AttributeError: 'numpy.int64'无'read'属性
错误原因与解决方法:AttributeError: 'numpy.int64' object has no attribute 'read'
错误原因
- 核心问题出在自定义数据集类
CustomDataSet的__getitem__方法中:self.dataframe.iloc[idx, 15]取出的是numpy.int64类型的数值,而非图片文件的路径字符串。当Image.open()接收这个数值作为参数时,PIL库会默认将其当作可读取的文件对象处理,尝试调用read()方法,但数值类型没有该属性,因此抛出报错。
解决方法
1. 确认CSV文件路径列的正确性
检查你使用的CSV文件第15列(注意pandas列索引从0开始)的内容:
- 如果该列原本应该存储图片路径,但被pandas解析成了数值类型,需要调整CSV文件内容,或者在
pd.read_csv()时指定该列为字符串类型,比如:self.dataframe = pd.read_csv(csv_file, dtype={15: str})
2. 修正路径获取逻辑
确保img_path是有效的字符串路径:
- 如果CSV中第15列的数值对应图片文件名(比如图片命名为数字),将数值转为字符串,同时拼接根目录(如果
root_dir是图片所在文件夹):def __getitem__(self, idx): if torch.is_tensor(idx): idx = idx.tolist() # 将数值转为字符串路径 img_path = str(self.dataframe.iloc[idx, 15]) # 拼接完整路径 img_full_path = os.path.join(self.root_dir, img_path) image = Image.open(img_full_path).convert("RGB") tensor_image = self.transform(image) return tensor_image - 如果CSV中第15列不是路径列,确认正确的路径列索引,替换代码中的
15为对应索引值。
3. 增加路径校验(可选但推荐)
在代码中加入校验逻辑,方便快速定位问题:
def __getitem__(self, idx): if torch.is_tensor(idx): idx = idx.tolist() img_path = self.dataframe.iloc[idx, 15] # 打印路径和类型,排查问题 print(f"当前索引{idx}的路径:{img_path},类型:{type(img_path)}") img_path = str(img_path) img_full_path = os.path.join(self.root_dir, img_path) # 检查文件是否存在 if not os.path.exists(img_full_path): raise FileNotFoundError(f"无法找到图片:{img_full_path}") image = Image.open(img_full_path).convert("RGB") tensor_image = self.transform(image) return tensor_image
4. 验证DataLoader构建
确保testloader的构建正确,数据集实例化时传入了正确的root_dir和transform参数,避免路径拼接错误。
内容的提问来源于stack exchange,提问作者Murad Ali
相关产品推荐
相关产品推荐

