修改官方文档的错误
运行官方文档中的代码可能会报错(维度不一致):
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "e:Anaconda3libsite-packages orch
nmodulesmodule.py", line 489, in __call__
result = self.forward(*input, **kwargs)
File "e:Anaconda3libsite-packages orchvisionmodels
esnet.py", line 150, in forward
x = self.conv1(x)
File "e:Anaconda3libsite-packages orch
nmodulesmodule.py", line 489, in __call__
result = self.forward(*input, **kwargs)
File "e:Anaconda3libsite-packages orch
nmodulesconv.py", line 320, in forward
self.padding, self.dilation, self.groups)
RuntimeError: Expected 4-dimensional input for 4-dimensional weight [64, 3, 7, 7], but got 2-dimensional input of size [5, 5] instead
因为model需要四维变量,而官方文档中的是二维变量,所以会报错
修改方法:去掉Variable函数,这是0.4版本的函数,我们现在使用的大多数是1.0版本
regular_input=torch.randn(1,3,224,224)#默认是True volatile_input=torch.randn(1,3,224,224) Model=torchvision.models.resnet18(pretrained=True) Model(regular_input).requires_grad with torch.no_grad(): Model(volatile_input).requires_grad
总结:(1)requires_grad=Fasle时不需要更新梯度, 适用于冻结某些层的梯度;
volatile=True相当于requires_grad=False,适用于推断阶段,不需要反向传播。这个现在已经取消了,使用with torch.no_grad()来替代