pytorch加载模型报错RuntimeError: Error(s) in loading state_dict for SSD:Missing key(s) in state_dict:...

报错信息:

RuntimeError: Error(s) in loading state_dict for SSD:
Missing key(s) in state_dict: “backbone.vgg.0.weight”, “backbone.vgg.0.bias”, “backbone.vgg.2.weight”, “backbone.vgg.2.bias”, “backbone.vgg.5.weight”, “backbone.vgg.5.bias”, “backbone.vgg.7.weight”, “backbone.vgg.7.bias”, “backbone.vgg.10.weight”, “backbone.vgg.10.bias”, “backbone.vgg.12.weight”, “backbone.vgg.12.bias”,…

Unexpected key(s) in state_dict: “0.weight”, “0.bias”, “2.weight”, “2.bias”, “5.weight”, “5.bias”, “7.weight”, “7.bias”, “10.weight”, “10.bias”, “12.weight”, “12.bias”,…

原因:

加载使用模型时和训练模型时的环境不一致,可以看到丢失的Keys和没定义的keys前面相差一个backbone.vgg。

解决方法:

在ssd_model.py中加载预训练模型的语句后面,加上一个False就可以了。

出错代码:

def load_pretrained_weight(self, weight_pkl):
        self.load_state_dict(torch.load(weight_pkl))

改为:

def load_pretrained_weight(self, weight_pkl):
        self.load_state_dict(torch.load(weight_pkl),False)

另外,如果预训练模型是在gpu上训练的,加载到cpu上也会报错,解决办法如下:

net.load_state_dict(torch.load(model_file, map_location='cpu'))

不设置map_location参数则会报错:

RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location=torch.device(‘cpu’) to map your storages to the CPU.

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天涯小才

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值