用python加载数据集的时候一直报错
最后两句
img1, label = ants_dataset[0]
train_dataset = ants_dataset + bees_dataset
这两句不写就可以正常运行,但是只要写一句上去就报错,这是为什么啊
from torch.utils.data import Dataset
from PIL import Image
import os
class MyData(Dataset):
def __init__(self, root_dir, label_dir):
self.root_dir = root_dir
self.label_dir = label_dir
self.path = os.path.join(self.root_dir, self.label_dir)
self.image_path = os.listdir(self.path)
def __getitem__(self,idx):
image_name = self.img_path[idx]
img_item_path = os.path.join(self.root_dir, self.label_dir, image_name)
img = Image.open(img_item_path)
label = self.label_dir
return img, label
def __len__(self):
return len(self.img_path)
root_dir = "dataset/train"
ants_label_dir = "ants"
bees_label_dir = "bees"
ants_dataset = MyData(root_dir, ants_label_dir)
bees_dataset = MyData(root_dir, bees_label_dir)
img1, label = ants_dataset[0]
#train_dataset = ants_dataset + bees_dataset
D:\learn\Programming\Python\envs\pytorch\python.exe C:/Users/Alan/Desktop/pytorch/demo1.py
Traceback (most recent call last):
File "C:\Users\Alan\Desktop\pytorch\demo1.py", line 30, in
img1, label = ants_dataset[0]
File "C:\Users\Alan\Desktop\pytorch\demo1.py", line 14, in getitem
image_name = self.img_path[idx]
File "D:\learn\Programming\Python\envs\pytorch\lib\site-packages\torch\utils\data\dataset.py", line 83, in getattr
raise AttributeError
AttributeError
进程已结束,退出代码1
可能是你的 label 并不是按照 label[idx] 的方式进行迭代,导致无法取值