AttributeError: '_MultiProcessingDataLoaderIter' object has no attribute 'next'
回答 2
浏览 1.4万
2022-11-02
我试图用Torch Dataset and DataLoader
加载数据集,但我得到了以下的错误。
AttributeError: '_MultiProcessingDataLoaderIter' object has no attribute 'next'
我使用的代码是:
class WineDataset(Dataset):
def __init__(self):
# Initialize data, download, etc.
# read with numpy or pandas
xy = np.loadtxt('./data/wine.csv', delimiter=',', dtype=np.float32, skiprows=1)
self.n_samples = xy.shape[0]
# here the first column is the class label, the rest are the features
self.x_data = torch.from_numpy(xy[:, 1:]) # size [n_samples, n_features]
self.y_data = torch.from_numpy(xy[:, [0]]) # size [n_samples, 1]
# support indexing such that dataset[i] can be used to get i-th sample
def __getitem__(self, index):
return self.x_data[index], self.y_data[index]
# we can call len(dataset) to return the size
def __len__(self):
return self.n_samples
dataset = WineDataset()
train_loader = DataLoader(dataset=dataset,
batch_size=4,
shuffle=True,
num_workers=2)
我试着让num_workers=0,仍然有同样的错误。
Python version 3.8.9
PyTorch version 1.13.0
2 个回答
#1楼
已采纳
得票数 25
我也遇到了同样的问题,当我试图调用next()方法时,如下所示
dataiter = iter(dataloader)
data = dataiter.next()
你需要用下面的方法来代替,它可以完美地工作。
dataiter = iter(dataloader)
data = next(dataiter)
最后,你的代码应该如下所示。
class WineDataset(Dataset):
def __init__(self):
# Initialize data, download, etc.
# read with numpy or pandas
xy = np.loadtxt('./data/wine.csv', delimiter=',', dtype=np.float32, skiprows=1)
self.n_samples = xy.shape[0]
# here the first column is the class label, the rest are the features
self.x_data = torch.from_numpy(xy[:, 1:]) # size [n_samples, n_features]
self.y_data = torch.from_numpy(xy[:, [0]]) # size [n_samples, 1]
# support indexing such that dataset[i] can be used to get i-th sample
def __getitem__(self, index):
return self.x_data[index], self.y_data[index]
# we can call len(dataset) to return the size
def __len__(self):
return self.n_samples
dataset = WineDataset()
train_loader = DataLoader(dataset=dataset,
batch_size=4,
shuffle=True,
num_workers=2)
dataiter = iter(dataloader)
data = next(dataiter)
#2楼
得票数 2
在pytorch 1.12中,语法是:
iter(trn_loader).next()
工作正常以及:
next(iter(trn_loader))
从pytorch 1.13开始,唯一可以工作的语法是:
next(iter(trn_loader))