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

Pytorch saving model UserWarning: Couldn't retrieve source code for container of type Network

在 Pytorch 中保存模型时使用:

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

我收到以下警告:

/opt/conda/lib/python3.6/site-packages/torch/serialization.py:193: UserWarning: Couldn't retrieve source code for container of type Network. It won't be checked for correctness upon loading. "type " + obj.name + ". It won't be checked "

加载时出现以下错误:

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__'>

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

节省

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'])