pytorch如何加载自定义网络权重
这篇文章主要介绍pytorch如何加载自定义网络权重,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
在将自定义的网络权重加载到网络中时,报错:
AttributeError: 'dict' object has no attribute 'seek'. You can only torch.load from a file that is seekable. Please pre-load the data into a buffer like io.BytesIO and try to load from it instead.
我们一步一步分析。
模型网络权重保存额代码是:torch.save(net.state_dict(),'net.pkl')
(1)查看获取模型权重的源码:
pytorch源码:net.state_dict()
defstate_dict(self,destination=None,prefix='',keep_vars=False): r"""Returnsadictionarycontainingawholestateofthemodule. Bothparametersandpersistentbuffers(e.g.runningaverages)are included.Keysarecorrespondingparameterandbuffernames. Returns: dict: adictionarycontainingawholestateofthemodule Example:: >>>module.state_dict().keys() ['bias','weight'] """
将网络中所有的状态保存到一个字典中了,我自己构建的就是一个字典,没问题!
(2)查看保存模型权重的源码:
pytorch源码:torch.save()
defsave(obj,f,pickle_module=pickle,pickle_protocol=DEFAULT_PROTOCOL): """Savesanobjecttoadiskfile. Seealso::ref:`recommend-saving-models` Args: obj:savedobject f:afile-likeobject(hastoimplementwriteandflush)orastring containingafilename pickle_module:moduleusedforpicklingmetadataandobjects pickle_protocol:canbespecifiedtooverridethedefaultprotocol ..warning:: IfyouareusingPython2,torch.savedoesNOTsupportStringIO.StringIO asavalidfile-likeobject.Thisisbecausethewritemethodshouldreturn thenumberofbyteswritten;StringIO.write()doesnotdothis. Pleaseusesomethinglikeio.BytesIOinstead.
函数功能是将字典保存为磁盘文件(二进制数据),那么我们在torch.load()时,就是在内存中加载二进制数据,这就是报错点。
解决方案:将字典保存为BytesIO文件之后,模型再net.load_state_dict()
#b为自定义的字典 torch.save(b,'new.pkl') net.load_state_dict(torch.load(b))
解决方法很简单,主要记录解决思路。
以上是“pytorch如何加载自定义网络权重”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注恰卡编程网行业资讯频道!
推荐阅读
-
Pytorch中model.eval()的作用是什么
Pytorch中model.eval()的作用是什么这篇文章主要介...
-
怎么使用pytorch读取数据集
怎么使用pytorch读取数据集这篇“怎么使用pytorch读取数...
-
pytorch中的view()函数怎么使用
pytorch中的view()函数怎么使用这篇文章主要介绍了pyt...
-
PyTorch中的torch.cat怎么用
PyTorch中的torch.cat怎么用这篇文章主要介绍PyTo...
-
pytorch中的hook机制是什么
pytorch中的hook机制是什么本篇内容介绍了“pytorch...
-
pytorch中的广播语义是什么
pytorch中的广播语义是什么这篇文章主要介绍“pytorch中...
-
PyTorch梯度下降反向传播实例分析
PyTorch梯度下降反向传播实例分析本文小编为大家详细介绍“Py...
-
python中的Pytorch建模流程是什么
python中的Pytorch建模流程是什么小编给大家分享一下py...
-
pytorch如何实现多项式回归
pytorch如何实现多项式回归这篇文章主要为大家展示了“pyto...
-
pytorch怎样实现线性回归
pytorch怎样实现线性回归这篇文章给大家分享的是有关pytor...