PyTorch保存和加载模型

本文介绍了PyTorch中两种常见的模型保存与加载方法。一种仅保存模型参数,适用于模型迁移;另一种则保存整个模型,但可能受限于特定目录结构。文章详细展示了每种方法的实现代码。

转自:

http://www.cnblogs.com/darkknightzh/p/8108466.html

参考网址:

https://pytorch.org/tutorials/beginner/saving_loading_models.html

https://pytorch.org/docs/stable/notes/serialization.html#best-practices

https://github.com/clcarwin/sphereface_pytorch

 

有两种方式保存和载入模型

1. 只保存和载入模型参数

保存:

torch.save(the_model.state_dict(), PATH)

载入:

the_model = TheModelClass(*args, **kwargs)
the_model.load_state_dict(torch.load(PATH))

当model使用gpu训练时,可以将数据转换到cpu中,并保存(载入时,还是上面的方法。需要使用gpu时,加上.cuda()):

def save_model(model, filename):
    state = model.state_dict()
    for key in state: state[key] = state[key].clone().cpu()
    torch.save(state, filename)

Remember that you must call model.eval() to set dropout and batch normalization layers to evaluation mode before running inference. Failing to do this will yield inconsistent inference results.

在加载已经保存好的模型, 务必调用model.eval()再进行前向计算. 

A common PyTorch convention is to save models using either a .pt or .pth file extension. 

2. 保存和载入整个模型

保存:

torch.save(the_model, PATH)

载入:

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.

第二种方式,序列化后的数据使用特殊的结构,缺点就是当在其他工程中使用时,可能会碰到各种问题。因而,官方更建议使用第一种方式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值