加载预训练模型 pytorch - dict 对象没有属性 eval [英] load a pretrained model pytorch - dict object has no attribute eval

查看:93
本文介绍了加载预训练模型 pytorch - dict 对象没有属性 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)

我正在像这样保存我的模型.如何加载模型以便我可以在其他地方使用它,比如 cnn 可视化?

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' 对象没有属性 'eval'

AttributeError: 'dict' object has no attribute 'eval'

我在这里错过了什么???

What am I missing here???

我想使用我训练的模型来可视化过滤器和梯度.我正在使用这个 repo使可见.我用 torch.load('model_best.pth.tar')

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')

推荐答案

首先,您已经说明了您的模型.而torch.load() 会给你一本字典.那本字典没有 eval 函数.所以你应该将权重上传到你的模型中.

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()

这篇关于加载预训练模型 pytorch - dict 对象没有属性 eval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆