nirvair
nirvair

Reputation: 4180

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

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???

EDIT: I want to use the model that I trained to visualize the filters and grads. I am using this repo to make the vis. I replaced line 179 with torch.load('model_best.pth.tar')

Upvotes: 10

Views: 35058

Answers (2)

**net.eval() AttributeError: 'dict' object has no attribute 'eval'**

I am trying to run this command: sudo python3 train.py

But I'm getting the following error:

2023-07-11 12:09:29,168   INFO  Loading KITTI dataset
2023-07-11 12:09:29,237   INFO  Total samples for KITTI dataset: 3769
./logs/1.pt
Traceback (most recent call last):
  File "eval.py", line 138, in <module>
    eval(net, val_data, logf, log_path, epoch, cfg, eval_set, logger)
  File "eval.py", line 54, in eval
    net.eval()
AttributeError: 'dict' object has no attribute 'eval'

enter image description here

Upvotes: -2

Salih Karagoz
Salih Karagoz

Reputation: 2289

First, you have stated your model. And torch.load() gives you a dictionary. That dictionary has not an eval function. So you should upload the weights to your model.

import torch
from modelfolder import yourmodel

model = yourmodel()
checkpoint = torch.load('model_best.pth.tar')
try:
    checkpoint.eval()
except AttributeError as error:
    print error
### 'dict' object has no attribute 'eval'

model.load_state_dict(checkpoint['state_dict'])
### now you can evaluate it
model.eval()

Upvotes: 5

Related Questions