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

转载请注明出处:

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.

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

因而,官方更建议使用第一种方式。

posted on 2017-12-25 11:05  darkknightzh  阅读(6024)  评论(0编辑  收藏  举报

导航