Load a pretrained model pytorch - dict object has no attribute eval


(Nikhilesh Vaishy) #1
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):
    torch.save(state, filename)
    if is_best:
        shutil.copyfile(filename, 'model_best.pth.tar')


save_checkpoint({
                'epoch': epoch + 1,
                'arch': args.arch,
                'state_dict': model.state_dict(),
                'best_prec1': best_prec1,
                'optimizer': optimizer.state_dict()
            }, is_best)

I am saving my model like this. How can I load back the model so that I can use it in other places, like cnn visualization?

This is how I am loading the model now:

torch.load('model_best.pth.tar')

But when I do this, I get this error:

AttributeError: ‘dict’ object has no attribute ‘eval’

What am I missing here???


(Justus Schock) #2

You have to create a model instance and then load the saved weights as statdict:

model = MyModel() 
model.load_state_dict(torch.load('model_best.pth.tar')['state_dict'])

The statedict itself is only a dict containing the tensor names and the corresponding weights. It has no information of the model’s structure.