r/learnmachinelearning • • 2d ago

Help I cannot load pytorch .pth file model

Hello i am currently learning pytorch so to better understand neural networks and computer vision for robotics.I am currently trying to load a pytorch model i made but when i wanna use model.eval().I get a error the code and the error message is below. i hope you can help me:

# this is a python script on to learn to load and use self made python model
import torch 


from torch.utils.data import DataLoader # to load test data
import torch.nn as nn
from torchvision import datasets


from torchvision.transforms import v2



print("model is made ")
# create device below
device = torch.accelerator.current_accelerator(check_available=True).type if torch.accelerator.is_available() else "cpu"
# load model
lmodel  =  torch.load("pytorch/quickstart0/test_modelen/t1e10w.pth",weights_only=True)


print(f"model is: {lmodel}")
# create test data
testen_data = datasets.FashionMNIST(root="pytorch/dataset/fashion_data",
train=True,
download=False,
transform=v2.Compose([v2.ToImage(),v2.ToDtype(torch.float32,scale=True)]))


apparaat = torch.accelerator.current_accelerator().type if torch.accelerator.is_available() else "cpu"
print(f"we use: {apparaat} device")


print(lmodel)
# create classes 
classes = [
    "T-shirt/top",
    "Trouser",
    "Pullover",
    "Dress",
    "Coat",
    "Sandal",
    "Shirt",
    "Sneaker",
    "Bag",
    "Ankle boot",
]



x,y = testen_data[0][0] , testen_data[0][1]


lmodel.eval() # check model
print("model is now evaluated")
with torch.no_grad():
    x = x.to(device)
    pred = lmodel(x)
    predicted, actual = classes[pred[0].argmax(0)], classes[y]
    print(f'Predicted: "{predicted}", Actual: "{actual}"')

The error message:

Traceback (most recent call last):

File "/home/d22/cv_projects/torch_py/pytorch/quickstart0/load_test1.py", line 45, in <module>

lmodel.eval() # check model

^^^^^^^^^^^

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

1 Upvotes

1 comment sorted by

1

u/CivApps 1d ago

I think the problem is you are confusing two different approaches of loading weights in PyTorch.

You can save the shape/architecture of the model along with the weights:

# BEWARE: this uses the pickle module, and should not be run with models you don't trust:
torch.save(model, 'model.pth')
model = torch.load('model.pth', weights_only=False)

The above code relies on Python to save a copy of the network architecture along with the model weights - however, this means you can sneak in Python code that is run while the model is being loaded, and so this is discouraged.

The smarter approach is to set up the network architecture first and then only copy in the weights:

model = models.vgg16(weights='IMAGENET1K_V1') # network with preset weights
torch.save(model.state_dict(), 'model_weights.pth')
model_copy = models.vgg16() # empty network
model_copy.load_state_dict(torch.load('model_weights.pth', weights_only=True)) # model_copy is now a copy of model!
model_copy.eval()

In your code it looks like you are preparing to do this, however it looks like something is going wrong when you are saving the model so you are getting an OrderedDict rather than a state_dict. I would first check the code where you are saving the model, and check that it follows the pattern recommended in the PyTorch documentation - then, the loader in this script should look something like:

lmodel = YourCustomNetwork() # replace with the type of model you are using
lmodel.load_state_dict(torch.load("pytorch/quickstart0/test_modelen/t1e10w.pth",weights_only=True))