我正在学习PyTorch,并按照教程进行学习。我发现当我尝试使用torchvision时,我的脚本运行了两次。我想知道它是否配置错误,还是我不小心引入了某种并行性。
这是我的代码:
# show images
import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import numpy as np
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
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)
testset = torchvision.datasets.CIFAR10(root='./data', train=False,
download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=4,
shuffle=False, num_workers=2)
classes = ('plane', 'car', 'bird', 'cat',
'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
def imshow(img):
img = img / 2 + 0.5 # unnormalize
npimg = img.numpy()
plt.imshow(np.transpose(npimg, (1, 2, 0)))
plt.show()
# get some random training images
print('Type of trainloader')
print(type(trainloader))
dataiter = iter(trainloader)
images, labels = dataiter.next()
# show images
imshow(torchvision.utils.make_grid(images))
# print labels
print(' '.join('%5s' % classes[labels[j]] for j in range(4)))
我的输出是:
C:\Users\Avi\Anaconda3\python.exe C:/Users/Avi/PycharmProjects/ExampleNN/test.py
Files already downloaded and verified
Files already downloaded and verified
Type of trainloader
<class 'torch.utils.data.dataloader.DataLoader'>
Files already downloaded and verified
Files already downloaded and verified
Type of trainloader
<class 'torch.utils.data.dataloader.DataLoader'>
然后dataiter = iter(trainloader)
第二次崩溃,大概是因为迭代已经完成。
有人可以告诉我我在做什么错吗?
更新:
我发现,如果我在DataLoader构造函数中设置num_workers = 0,则它只会运行一次,并且不会崩溃。如果将其设置为1,它会运行两次并像将其设置为2一样崩溃。我仍然不明白为什么会这样,但是至少我可以解决我的问题。