raise RuntimeError(‘Error(s) in loading state_dict for {}:\n\t{}‘.format(

在对目标检测模型进行测试出现以下问题:

raise RuntimeError('Error(s) in loading state_dict for {}:\n\t{}'.format(
RuntimeError: Error(s) in loading state_dict for DataParallel:
    Missing key(s) in state_dict: "module.vgg.0.weight", "module.vgg.0.bias"...........
    Unexpected key(s) in state_dict: "vgg.0.weight", "vgg.0.bias", "vgg.5.weight"................... 

RuntimeError: Error(s) in loading state_dict for DataParallel:     size mismatch for module.loc.0.weight: copying a param with shape torch.Size([16, 512, 1, 1]) from checkpoint, the shape in current model is torch.Size([16, 512, 3, 3]).     size mismatch for mo

问题原因:

1.模型训练时使用的GPU,nn.DataParallel
2.原模型和载入模型参数不匹配

解决代码如下:

    # load net
    num_classes = len(labelmap) + 1                    # +1 for background
    net = build_ssd('test', 300, num_classes).cuda()          # initialize SSD
    # net = nn.DataParallel(net).cuda()

    state_dict = torch.load(args.trained_model)
    new_state_dict = {}
    for key, value in state_dict.items():
        new_key = key
        if not key.startswith('module.'):
            new_key = 'module.' + key
        new_state_dict[new_key] = value

    # net.load_state_dict(new_state_dict,strict=False)
    try:
        net.load_state_dict(new_state_dict)
    except RuntimeError as e:
        print('Ignoring "' + str(e) + '"')

    # checkpoint  = torch.load(args.trained_model)
    # # net.load_state_dict({k.replace('module.vgg',''):v for k,v in checkpoint['vgg'].items()})
    # net.load_state_dict(checkpoint)
    net.eval()
    print('Finished loading model!')

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值