chenyuntc / pytorch-book

PyTorch tutorials and fun projects including neural talk, neural style, poem writing, anime generation (《深度学习框架PyTorch:入门与实战》)
MIT License
12.11k stars 3.74k forks source link

第五章代码报错 #146

Open Hiker01 opened 5 years ago

Hiker01 commented 5 years ago

运行以下代码: dataloader = DataLoader(dataset, shuffle=True, batch_size=16) from torchvision.utils import make_grid, save_image dataiter = iter(dataloader) img = make_grid( next(dataiter)[0], 4) # 拼成4*4网格图片,且会转成3通道 to_img(img)

报错信息: The expanded size of the tensor (1) must match the existing size (3) at non-singleton dimension 0

运行环境: pytorch : 0.4.1 python : 3.6

CescMessi commented 5 years ago

应该是不能自动转为3通道,原图片换成三通道的图片就不会报错了

sdzbft commented 5 years ago

不太清楚为啥,,但是和pytorch版本有关,,,换成1.0.1 是没有问题的,亲测

huangpan2507 commented 5 years ago

你的dataset 里面的transform 是不是用了三通道的归一化 mean=[0.5,0.5,0.5] std=[0.5,0.5,0.5]?

huangpan2507 commented 5 years ago

改成对单一通道归一化就好了。 transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)) ])

huangpan2507 commented 5 years ago

不太清楚为啥,,但是和pytorch版本有关,,,换成1.0.1 是没有问题的,亲测

不太清楚为啥,,但是和pytorch版本有关,,,换成1.0.1 是没有问题的,亲测

看我上面的,是因为你归一化用的是三个通道的

huangpan2507 commented 5 years ago

或者法二: 将单通道扩展为三通道: transform = transforms.Compose([ transforms.ToTensor(), transforms.Lambda(lambda x: x.repeat(3,1,1)), transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)) ])