tridentifer
tridentifer

Reputation: 37

Pytorch error loading state dict of model: Expected state_dict to be dict-like

I am trying to save and load a model, but there is always an error. I save the model with:

torch.save(model.state_dict(),'01.Code/models/SNNNotEncoded.pth' )

and I try to load the model with

model.load_state_dict('01.Code/models/SNNNotEncoded.pth')

Then, the following error will come up:

Traceback (most recent call last): File "/home/demaisch/git/ros_workspaces/demaisch_ws/PythonFIles/SNNtrainNotEncoded.py", line 26, in model.load_state_dict('01.Code/models/SNNNotEncoded.pth') File "/home/demaisch/.local/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1994, in load_state_dict raise TypeError("Expected state_dict to be dict-like, got {}.".format(type(state_dict))) TypeError: Expected state_dict to be dict-like, got <class 'str'>

Thanks in advance

Upvotes: 1

Views: 14593

Answers (2)

Phoenix
Phoenix

Reputation: 1048

first load the state_dict from the file then create a new instance of your model and finally load the state_dict into the model:

state_dict = torch.load('01.Code/models/SNNNotEncoded.pth')
model = YourModelClass()

model.load_state_dict(state_dict)

Upvotes: 3

tgaudier
tgaudier

Reputation: 496

model.load_state_dict does not take a filepath but a dictionnary giving the weights of all layers (see this link from pytorch doc). To use the saved state dict, you must load it before.

You can replace your second line with :

model.load_state_dict(torch.load('01.Code/models/SNNNotEncoded.pth'))

torch.load first loads the object saved in the file, and it is then given to the load_state_dict function which sets all the weights of your model.

Upvotes: 3

Related Questions