AttributeError: 'collections.OrderedDict' object has no attribute 'to'

The following is my test_model.py. When executing it, there exist AttributeError: ‘collections.OrderedDict’ object has no attribute ‘to’. Pytorch version is 1.2.0 python version 3.7.4
import torch

from PIL import Image
from torchvision import transforms

classes = (‘a’,‘b’,‘c’,‘d’)
device = torch.device(‘cuda’)
transform=transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485,0.456,0.406],
std=[0.229,0.224,0.225])
])
def prediect(img_path):
net=torch.load(‘best.mdl’)
net=net.to(device)
torch.no_grad()
img=Image.open(img_path)
img=transform(img).unsqueeze(0)
img_ = img.to(device)
outputs = net(img_)
_, predicted = torch.max(outputs, 1)
# print(predicted)
print(‘this picture maybe :’,classes[predicted[0]])
if name == ‘main’:
prediect(’./test/name.jpg’)


runfile(‘C:/classification-master/Test_model.py’, wdir=‘C:/classification-master’)
Traceback (most recent call last):

File “”, line 1, in
runfile(‘C:/classification-master/Test_model.py’, wdir=‘C:/classification-master’)

File “C:\Users\derek\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py”, line 827, in runfile
execfile(filename, namespace)

File “C:\Users\derek\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py”, line 110, in execfile
exec(compile(f.read(), filename, ‘exec’), namespace)

File “C:/classification-master/Test_model.py”, line 27, in
prediect(’./test/name.jpg’)

File “C:/classification-master/Test_model.py”, line 17, in prediect
net=net.to(device)

AttributeError: ‘collections.OrderedDict’ object has no attribute ‘to’

1 Like

When you do net=torch.load(...) you are loading pretrained weights. It is just a python dictionary containing the weights, not the pytorch network. You need (in addition) to set a model (model= Model(*args,**kwargs) and then to load those weights into the model (model.load_state_dict(net))

1 Like

Thanks a lot Juan. Your solution worked, at least for me.
I was trying to load a pkl GAN generator, so I did as you said and it works!
I also changed net.to(device) to model.to(device), for information.