Pytorch保存模型UserWarning:无法检索网络类型的容器的源代码

时间:2018-09-11 13:28:54

标签: python save warnings pytorch

使用以下方法在Pytorch中保存模型时

torch.save(model, 'checkpoint.pth')

我收到以下警告:

  

/opt/conda/lib/python3.6/site-packages/torch/serialization.py:193:   UserWarning:无法检索类型为的容器的源代码   网络。加载后不会检查其正确性。 “类型” +   obj。名称 +“。不会被选中”

当我加载它时,出现以下错误:

state_dict = torch.load('checkpoint_state_dict.pth')
model = torch.load('checkpoint.pth')
model.load_state_dict(state_dict)


AttributeError                            Traceback (most recent call last)
<ipython-input-2-6a79854aef0f> in <module>()
      2 state_dict = torch.load('checkpoint_state_dict.pth')
      3 model = 0
----> 4 model = torch.load('checkpoint.pth')
      5 model.load_state_dict(state_dict)

/opt/conda/lib/python3.6/site-packages/torch/serialization.py in load(f, map_location, pickle_module)
    301         f = open(f, 'rb')
    302     try:
--> 303         return _load(f, map_location, pickle_module)
    304     finally:
    305         if new_fd:

/opt/conda/lib/python3.6/site-packages/torch/serialization.py in _load(f, map_location, pickle_module)
    467     unpickler = pickle_module.Unpickler(f)
    468     unpickler.persistent_load = persistent_load
--> 469     result = unpickler.load()
    470 
    471     deserialized_storage_keys = pickle_module.load(f)

AttributeError: Can't get attribute 'Network' on <module '__main__'>

为什么无法保存模型并完全重新加载它?

1 个答案:

答案 0 :(得分:2)

保存

torch.save({'state_dict': model.state_dict()}, 'checkpoint.pth.tar')

加载

model = describe_model()
checkpoint = torch.load('checkpoint.pth.tar')
model.load_state_dict(checkpoint['state_dict'])