NotImplementedError:当我尝试在Pytorch中创建DataLoader对象时

时间:2019-07-10 12:54:03

标签: machine-learning deep-learning pytorch

我创建了一个自定义数据集类,该类继承自PyTorch的Dataset类,以便处理我已经过预处理的自定义数据集。

当我尝试创建DataLoader对象时,出现此错误:

/usr/local/lib/python3.6/dist-packages/torch/utils/data/dataloader.py in __init__(self, dataset, batch_size, shuffle, sampler, batch_sampler, num_workers, collate_fn, pin_memory, drop_last, timeout, worker_init_fn)
    174             if sampler is None:
    175                 if shuffle:
--> 176                     sampler = RandomSampler(dataset)
    177                 else:
    178                     sampler = SequentialSampler(dataset)

/usr/local/lib/python3.6/dist-packages/torch/utils/data/sampler.py in __init__(self, data_source, replacement, num_samples)
     62                              "since a random permute will be performed.")
     63 
---> 64         if not isinstance(self.num_samples, int) or self.num_samples <= 0:
     65             raise ValueError("num_samples should be a positive integer "
     66                              "value, but got num_samples={}".format(self.num_samples))

/usr/local/lib/python3.6/dist-packages/torch/utils/data/sampler.py in num_samples(self)
     70         # dataset size might change at runtime
     71         if self._num_samples is None:
---> 72             return len(self.data_source)
     73         return self._num_samples
     74 

/usr/local/lib/python3.6/dist-packages/torch/utils/data/dataset.py in __len__(self)
     18 
     19     def __len__(self):
---> 20         raise NotImplementedError
     21 
     22     def __add__(self, other):

NotImplementedError: 

因此,错误消息与在dataset.py中未实现 len ()函数有关,对吧?但是我确实实现了它,还实现了 getitem (), init ()。

我该如何克服? 谢谢

1 个答案:

答案 0 :(得分:0)

确保名称在您的代码中正确。它应该是__len__