这篇文章主要介绍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如何加载自定义网络权重”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注恰卡编程网行业资讯频道!