Error(s) in loading state_dict for DataParallel: Missing key(s) in state_dict: “module.conv0.weight

在加载已经训练好的模型时,报错。

报错描述:

Error(s) in loading state_dict for DataParallel:
Missing key(s) in state_dict: “module.conv0.weight”, “module.bn0.weight”, “module.bn0.bias”, “module.bn0.running_mean”, “module.bn0.running_var”, “module.conv1.weight”, “module.bn1.weight”, “module.bn1.bias”, “module.bn1.running_mean”, “module.bn1.running_var”, “module.conv2.weight”, “module.bn2.weight”, “module.bn2.bias”, “module.bn2.running_mean”, “module.bn2.running_var”, “module.conv3.weight”, “module.bn3.weight”, “module.bn3.bias”, “module.bn3.running_mean”, “module.bn3.running_var”, “module.conv4.weight”, “module.bn4.weight”, “module.bn4.bias”, “module.bn4.running_mean”, “module.bn4.running_var”, “module.conv5.weight”, “module.bn5.weight”, “module.bn5.bias”, “module.bn5.running_mean”, “module.bn5.running_var”, “module.fc.weight”, “module.fc.bias”.
Unexpected key(s) in state_dict: “epoch”, “state_dict”, “best_prec1”.

原因:

保存模型的代码:

save_checkpoint({
        'state_dict': model.state_dict(),
        'best_prec1': best_prec1,
    }, is_best, filename=os.path.join(args.save_dir, 'model.th'))

该函数:

# 保存最新和最佳模型
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):
    """
    Save the training model
    """
    torch.save(state, filename)
    if is_best:
        shutil.copyfile(filename, 'model_best.pth.tar')

由以上可知,在调用torch.save函数时,state对应的是{ 'state_dict': model.state_dict(), 'best_prec1': best_prec1, },因此在加载的时候要指明值。

解决方案:

修改为:

model.load_state_dict(torch.load("C:\\Users\\83543\\Desktop\\model_best.pth.tar")['state_dict'])

第二种错误原因:

导入的是ResNet-20的模型参数的模型文件,但是引入的模型框架是vgg的导致错误,记得对应。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值