使用torch.load()加载模型参数时,提示“xxx.pt is a zip archive(did you mean to use torch.jit.load()?)“

前两天刚在服务器上安装了torch,开开心心开始自己的DL之旅。但是在将训练好的模型参数,加载到模型中时,出现了如下图所示的错误,百度半天无果。
在这里插入图片描述

1.官网查看torch.save参数

torch官网查看了torch.save的介绍,如下图所示。可以看到在torch1.6版本中,对torch.save进行了更改.The 1.6 release of PyTorch switched torch.save to use a new zipfile-based file format. torch.load still retains the ability to load files in the old format. If for any reason you want torch.save to use the old format, pass the kwarg _use_new_zipfile_serialization=False.

在这里插入图片描述

2.解决方法

使用torch.__version__查看自己的torch版本,果不其然,是1.6。因此,对代码进行修改

torch.save(model.state_dict(), model_cp,_use_new_zipfile_serialization=False)  # 训练所有数据后,保存网络的参数

大功告成

-----------------------------分割线–方法来源于 《爬爬怪》的评论--------------------------------

3.另一种方法

如果使用torch 1.6版本进行了训练,并且在训练时没有更改参数“_use_new_zipfile_serialization=False”,为了节省时间,大家可以在1.6中直接加载模型,然后再次使用torch.save 进行保存为非zip格式的。具体代码如下:

#在torch 1.6版本中重新加载一下网络参数
model = MyNetwork().to(device) #实例化模型并加载到cpu货GPU中
model.load_state_dict(torch.load(model_cp))  #加载模型参数,model_cp为之前训练好的模型参数(zip格式)
#重新保存网络参数,此时注意改为非zip格式
torch.save(model.state_dict(), model_cp,_use_new_zipfile_serialization=False)
  • 53
    点赞
  • 103
    收藏
    觉得还不错? 一键收藏
  • 26
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 26
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值