Python运行报错_RuntimeError: Error(s) in loading state_dict for DataParallel:

问题描述:

        RuntimeError: Error(s) in loading state_dict for DataParallel: size mismatch for module.fcc.weight:

        pytorch代码,加载预训练模型时报错,分类类别数不一致

报错信息:

错误代码:

checkpoint = torch.load('pretrain.pth', map_location=device)
model = nn.DataParallel(model)
model.load_state_dict(checkpoint['model_state_dict'], strict=False)
model.to(device)

尝试: 

checkpoint = torch.load('pretrain.pth', map_location=device)

del_keys = ['module.fcc.weight', ' module.fcc.bias', ' module.head.weight', 'module.head.bias']
for k in del_keys:
    del checkpoint[k]

model = nn.DataParallel(model)
model.load_state_dict(checkpoint['model_state_dict'], strict=False)
model.to(device)

报错:


 

 Debug发现checkpoint['model_state_dict'']才是要删除的预训练模型对应的字典

In[3]: checkpoint.keys()
Out[3]: dict_keys(['iter', 'model_state_dict'])

In[3]: checkpoint['model_state_dict'].keys()
Out[4]: odict_keys([ 'module.bn1.weight', 'module.bn1.bias', ......, 'module.head.weight', 'module.head.bias', ......])

则解决方案为:

checkpoint = torch.load('pretrain.pth', map_location=device)

del_key = []
for key, _ in checkpoint['model_state_dict'].items():
    if 'fcc' in key:
        del_key.append(key)
    elif 'head' in key:
        del_key.append(key)
    else:
        pass
for key in del_key:
    del checkpoint['model_state_dict'][key]

model = nn.DataParallel(model)
model.load_state_dict(checkpoint['model_state_dict'], strict=False)
model.to(device)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值