参考链接: Serialization semantics
原文及翻译:
Serialization semantics 序列化语义
Best practices 最佳惯例
Recommended approach for saving a model 推荐采用的保存模型的方法
There are two main approaches for serializing and restoring a model.
序列化模型并保存模型和加载并恢复模型的方法主要有以下两种.
The first (recommended) saves and loads only the model parameters:
第一种方式(也是推荐使用的方式)是只保存和加载模型的参数:
torch.save(the_model.state_dict(), PATH)
Then later: 然后:
the_model = TheModelClass(*args, **kwargs)
the_model.load_state_dict(torch.load(PATH))
The second saves and loads the entire model:
第二种方式是保存和加载整个全部的模型:
torch.save(the_model, PATH)
Then later: 然后:
the_model = torch.load(PATH)
However in this case, the serialized data is bound to the specific classes
and the exact directory structure used, so it can break in various ways
when used in other projects, or after some serious refactors.
然而在这个例子中,序列化后的数据会关联到特定的类型以及所使用的特定的目录结构,
因此在其他项目中使用时或者在其他重要的重构之后,它会出现各种各样的问题.