pytorch如何加载自定义网络权重

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

发布于 2021-05-30 14:06:17
收藏
分享
海报
0 条评论
162
上一篇:Pytorch如何实现自定义数据集 下一篇:PHP中Cookie怎么创建
目录

    0 条评论

    本站已关闭游客评论,请登录或者注册后再评论吧~

    忘记密码?

    图形验证码