zoukankan      html  css  js  c++  java
  • Missing key(s) in state_dict: Unexpected key(s) in state_dict

    如果加载的预训练模型之前使用了torch.nn.DataParallel(),而此时的训练并没有使用,则会出现这样的错误。
    解决方案有两个:
    1:此时的训练加入torch.nn.DataParallel()即可。
    2:创建一个没有module.的新字典,即将原来字典中module.删除掉。
    解决方案1:

    model = torch.nn.DataParallel(model)
    cudnn.benchmark = True


    解决方案2:
    # original saved file with DataParallel
    state_dict = torch.load('myfile.pth')
    # create new OrderedDict that does not contain `module.`
    from collections import OrderedDict
    new_state_dict = OrderedDict()
    for k, v in state_dict.items():
        name = k[7:] # remove `module.`
        new_state_dict[name] = v
    # load params
    model.load_state_dict(new_state_dict)

    解决方案3:
    model.load_state_dict({k.replace('module.',''):v for k,v in torch.load('myfile.pth').items()})

  • 相关阅读:
    JS在线编辑器
    meta标签
    webstorm快捷键
    微信JS-SDK调用
    iOS -- UIApplication
    Xcode -- apple llvm 6.0 error错误如何解决
    C -- 字符串数组与字符串指针
    MAC -- 小技巧
    C语言 -- 折半查找小程序
    C -- 小程序
  • 原文地址:https://www.cnblogs.com/llfctt/p/11045066.html
Copyright © 2011-2022 走看看