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

前两天刚在服务器上安装了torch,开开心心开始自己的DL之旅。但是在将训练好的模型参数,加载到模型中时,出现了如下图所示的错误,百度半天无果。
Pytorch学习|使用torch.load()加载模型参数时,提示“xxx.pt is a zip archive(did you mean to use torch.jit.load()?)“
文章图片

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.
Pytorch学习|使用torch.load()加载模型参数时,提示“xxx.pt is a zip archive(did you mean to use torch.jit.load()?)“
文章图片

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)

    推荐阅读