Pytorch model saving and loading 模型保存和读取

Posted 蠢材少年

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Pytorch model saving and loading 模型保存和读取相关的知识,希望对你有一定的参考价值。

It is really useful to save and reload the model and its parameters during or after training in deep learning.

Pytorch provides two methods to do so.

1. Only restore the parameters (recommended)

torch.save(the_model.state_dict(), PATH)    # save parameters to PATH

the_model = TheModelClass(*args, **kwargs)    # declare the_model as a object of TheModelClass
the_model.load_state_dict(torch.load(PATH))    # load parameters from PATH

 

2. Save all structure and parameters

torch.save(the_model, PATH)

the_model = torch.load(PATH)

 

3. Get parameters of certain layer

params=model.state_dict() 
for k,v in params.items():
    print(k)    # print the variable names in networks
print(params[‘conv1.weight‘])   #print conv1‘s weight
print(params[‘conv1.bias‘])   #print conv1‘s bias  

  

 

reference:http://www.pytorchtutorial.com/pytorch-note5-save-and-restore-models/

  

以上是关于Pytorch model saving and loading 模型保存和读取的主要内容,如果未能解决你的问题,请参考以下文章

每天讲解一点PyTorch 15model.load_state_dict torch.load torch.save

每天讲解一点PyTorch 15model.load_state_dict torch.load torch.save

每天讲解一点PyTorch 15model.load_state_dict torch.load torch.save

pytorch保存模型遇到点问题

如何使用 PyTorch 模型进行预测?

pytorch保存模型等相关参数,利用torch.save(),以及读取保存之后的文件