pytorch 模型保存与加载

  一、模型保存有两种形式:保存整体模型(包括模型结构和参数)、只保存模型参数

import torch

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# 保存整体模型
output_dir = 'checkpoint.ckp'
model_to_save = model.module if hasattr(model, "module") else model
torch.save(model_to_save, output_dir)
# 加载整体模型
model = torch.load(output_dir, map_location=device)

# =========================================================================
# 只保存模型参数 state_dict
torch.save(model.state_dict(), output_dir)
# 只加载模型参数 state_dict
model.load_state_dict(torch.load(output_dir, map_location=device))

二、当训练的代码中使用了“torch.nn.DataParallel()”,这个命令是将网络在多块gpu中进行训练然后合并,这时采用上面“只保存模型参数”的方式时,保存的参数key中会在最前面多一个module.

解决方式有三个:

1.加载模型时去掉key中的module.

model.load_state_dict({k.replace('module.',''):v for k,v in torch.load('checkpoint.pth').items()})

2.加载时也用“torch.nn.DataParallel()

    if cuda:
        g_model = torch.nn.DataParallel(g_model)
        cudnn.benchmark = True
        g_model = g_model.cuda()

    if os.path.exists(model_path):
        print('Loading weights into state dict...')
        model_dict = g_model.state_dict()
        pretrained_dict = torch.load(model_path, map_location=device)
        g_model.load_state_dict(pretrained_dict)
        print('Finished!')

3.只有一个GPU就没有必要使用“torch.nn.DataParallel()”了

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小殊小殊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值