【PyTorch】加载模型报错:RuntimeError: Error(s) in loading state_dict for ResNet:Missing key(s) in state_dict
问题描述
resnet.load_state_dict(t.load(PHOTO_RESNET, map_location=t.device('cpu')))
Traceback (most recent call last):
File "SketchyDatabase\feature\feature_extract.py", line 66, in <module>
resnet.load_state_dict(t.load(PHOTO_RESNET, map_location=t.device('cpu')))
File "D:\ProgramData\Anaconda\envs\pytorch\lib\site-packages\torch\nn\modules\module.py", line 2215, in load_state_dict
raise RuntimeError('Error(s) in loading state_dict for {}:\n\t{}'.format(
RuntimeError: Error(s) in loading state_dict for ResNet:
Missing key(s) in state_dict: "conv1.weight", "bn1.weight", "bn1.bias", "bn1.running_mean", "bn1.running_var", "layer1.0.conv1.weight",
...
原因分析
加载的模型状态字典中的键名带有 “module.” 前缀,这是因为模型在训练时使用了 torch.nn.DataParallel
。
解决方案
将 strict 设为 False:
resnet.load_state_dict(t.load(PHOTO_RESNET, map_location=t.device('cpu'), weights_only=True), strict=False)