【问题标题】:Missing keys when loading the model weight in pytorch在 pytorch 中加载模型重量时缺少键
【发布时间】:2022-01-17 00:25:30
【问题描述】:

我打算从 pth 文件加载权重,例如,

model = my_model()
model.load_state_dict(torch.load("../input/checkpoint/checkpoint.pth")

但是,这里有一个错误,说:

RuntimeError: Error(s) in loading state_dict for my_model:
Missing key(s) in state_dict: "att.in_proj_weight", "att.in_proj_bias", "att.out_proj.weight", "att.out_proj.bias". 
Unexpected key(s) in state_dict: "in_proj_weight", "in_proj_bias", "out_proj.weight", "out_proj.bias".

似乎我的模型的参数名称与state_dict中存储的参数名称不同。在这种情况下,我应该如何使它们保持一致?

【问题讨论】:

    标签: python machine-learning deep-learning neural-network pytorch


    【解决方案1】:

    您可以创建新字典并修改不带 att. 前缀的键,并且可以将新字典加载到模型中,如下所示:

    
    state_dict = torch.load('path\to\checkpoint.pth')
    
    from collections import OrderedDict
    new_state_dict = OrderedDict()
    
    for key, value in state_dict.items():
        key = key[4:] # remove `att.`
        new_state_dict[key] = value
    
    # load params
    model = my_model()
    model.load_state_dict(new_state_dict)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-09
      • 1970-01-01
      • 2020-05-03
      • 2019-06-21
      • 2020-02-07
      • 2019-07-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多