Pytorch学习|使用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)# 训练所有数据后,保存网络的参数
【Pytorch学习|使用torch.load()加载模型参数时,提示“xxx.pt is a zip archive(did you mean to use torch.jit.load()?)“】大功告成
-----------------------------分割线–方法来源于 《爬爬怪》的评论--------------------------------
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)
推荐阅读
- C语言学习|第十一届蓝桥杯省赛 大学B组 C/C++ 第一场
- paddle|动手从头实现LSTM
- pytorch|使用pytorch从头实现多层LSTM
- SG平滑轨迹算法的原理和实现
- 推荐系统论文进阶|CTR预估 论文精读(十一)--Deep Interest Evolution Network(DIEN)
- pytorch|YOLOX 阅读笔记
- Pytorch学习|sklearn-SVM 模型保存、交叉验证与网格搜索
- 前沿论文|论文精读(Neural Architecture Search without Training)
- 联邦学习|【阅读笔记】Towards Efficient and Privacy-preserving Federated Deep Learning
- OpenCV|OpenCV-Python实战(18)——深度学习简介与入门示例