'iterator'对象在python 3.7中没有属性'next'

问题描述 投票:0回答:3

我正在尝试迭代我的数据集并获取第一个元素

    transform = transforms.Compose([transforms.ToTensor(),transforms.Normalize((0.5),(0.5)),])
    trainloader = datasets.MNIST('~/.pytorch/MNIST_data' , download=True,train=True , transform=transform)
    ds = iter(trainloader)
    img, labels = ds.next()

但它返回此错误

    AttributeError: 'iterator' object has no attribute 'next'

我也试过这个

    img , labels = next(ds)

返回此错误

    StopIteration:

我错过了什么吗?

python-3.x iterator pytorch
3个回答
4
投票

可能是这个问题: https://github.com/microsoft/DeepSpeedExamples/issues/222

然后更改为:

images, labels = dataiter.next()

至:

images, labels = next(dataiter)

2
投票

如果您按照 https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html 上的教程进行操作

trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
                                        download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,
                                          shuffle=True, num_workers=2)

dataiter = iter(trainloader)
images, labels = dataiter.next()

您的数据集上缺少 DataLoader() 函数


0
投票

考虑同一个例子:

transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])
mnist_train_dataset = datasets.MNIST('mnist_train_data', download=True, train=True, transform=transform)
mnist_train_data_loader = torch.utils.data.DataLoader(mnist_train_dataset, batch_size=64, shuffle=True)
train_data_iterator = iter(mnist_train_data_loader)
train_images, train_labels = next(train_data_iterator)

变化是来自

train_images, train_labels = train_data_iterator.next()

train_images, train_labels = next(train_data_iterator)

绘制数字图像:

plt.imshow(train_images[63].numpy().squeeze(), cmap='gray')
plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.