(原+译)pytorch中保存和载入模型

本文介绍了PyTorch中两种常见的模型保存与加载方法。一种仅保存模型参数,适用于模型迁移;另一种则保存整个模型状态,但可能因依赖具体目录结构而限制其通用性。推荐使用第一种方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载请注明出处:

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

参考网址:

http://pytorch.org/docs/master/notes/serialization.html

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)

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、付费专栏及课程。

余额充值