Now I want to train again using the weights of my trained model. So what I did is:
pretrained_weights = torch.load('trained.pth'')
model = resnet50(pretrained=False)
model.load_state_dict(pretrained_weights)
But it throws error:
model.load_state_dict(pretrained_weights)
File "/home/user/.local/lib/python3.6/site-packages/torch/nn/modules/module.py", line 751, in load_state_dict
state_dict = state_dict.copy()
File "/home/user/.local/lib/python3.6/site-packages/torch/nn/modules/module.py", line 539, in __getattr__
type(self).__name__, name))
AttributeError: 'ResNet' object has no attribute 'copy'
What I am doing wrong, can you please tell me ? I want to use my trained model’s weights to initialize my new training, same model as before resnet50.
There are two ways of saving and loading models in Pytorch. You can either save/load the whole python class, architecture, weights or only the weights.
pretrained_weights = torch.load('trained.pth'')
model = resnet50(pretrained=False)
model.load_state_dict(pretrained_weights)
you save your model state_dict with model structure by using torch.save(trained_model, 'trained.pth') , but you just load state_dict by model.load_state_dict(pretrained_weights)
now you are saving as a pickle object which doesn’t save the model’s classes, but saves paths to them. As mentioned in the documentation, this may cause a problem during load time.