我有一个CSV文件,第一列是文件名,第二列是文件名的标签。第三列则指定了数据的某些信息(即数据是否满足特定条件)。它看起来像这样,
+-----------------------------+| Filepath 1 Label 1 'n' || |+-----------------------------+| Filepath 2 Label 2 'n' || || |+-----------------------------+| Filepath 3 Label 3 'n'|| |+-----------------------------+| Filepath 4 Label 4 'y'|+------------------------------+
我想在属性列等于’y’时使用getitem加载自定义数据集。但是,我遇到了以下错误:
TypeError: default_collate: batch must contain tensors, numpy arrays, numbers, dicts or lists; found <class ‘NoneType’>
我的代码如下:
”’
class InterDataset(Dataset): def __init__(self, csv_file, mode, root_dir = None, transform = None, run = None): self.annotations = pd.read_csv(csv_file, header = None) self.root_dir = root_dir self.transform = transform self.mode = mode self.run = run def __len__(self): return len(self.annotations) def __getitem__(self, index): if self.mode == 'train': if (self.annotations.iloc[index, 2] == 'n'): img_path = self.annotations.iloc[index,0] image = cv2.imread(img_path,1) y_label = self.annotations.iloc[index,1] if self.transform: image = self.transform(image) if (index+1)%300 == 0: print('Loop {0} done'.format(index)) return [image, y_label]
”’
回答:
你会遇到这个错误是因为数据加载器必须返回某些东西。这里有三个解决方案:
- 有一个名为nonechucks的库,它允许你创建可以跳过样本的数据加载器。
- 通常你可以预处理/清理你的数据,并剔除不需要的样本。
- 你可以返回一个指示样本不想要的标志,例如
if "y": return data, targetelse: return -1
然后你可以在训练循环中检查”data”是否为-1,如果是则跳过该迭代。希望这对你有帮助 🙂