问题原因
Expected 4-dimensional input for 4-dimensional weight [64, 3, 3, 3], but got 3-dimensional input of size [3, 224, 224] instead
找到出错的地方:
return F.conv2d(input, weight, bias, self.stride,
self.padding, self.dilation, self.groups)
这个报错的意思是由于weight是[64, 3, 3, 3]
的4维卷积核,因此对应的input也必须是4维的,而这里我们给进去的图片输入只有三个维度[3, 224, 224]
,这里少了一个维度,而在torch中,Conv2d
需要(n_samples, channels, height, width)
这样的输入,所以我们需要给单张图片的输入加上一个batch_size维度,让他的维度变成[1, 3, 224, 224]
,这里直接用unsqueeze()
方法就行了:
print(f'添加前:{image.shape}')
image = image.unsqueeze(0)
print(f'添加后:{image.shape}')
>>>添加前:torch.Size([3, 224, 224])
>>>添加后:torch.Size([1, 3, 224, 224])