pytorch加载自定义网络权重的实现
2020-02-13 10:06
1576 查看
在将自定义的网络权重加载到网络中时,报错:
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()
def state_dict(self, destination=None, prefix='', keep_vars=False): r"""Returns a dictionary containing a whole state of the module. Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Returns: dict: a dictionary containing a whole state of the module Example:: >>> module.state_dict().keys() ['bias', 'weight'] """
将网络中所有的状态保存到一个字典中了,我自己构建的就是一个字典,没问题!
(2)查看保存模型权重的源码:
pytorch源码:torch.save()
def save(obj, f, pickle_module=pickle, pickle_protocol=DEFAULT_PROTOCOL): """Saves an object to a disk file. See also: :ref:`recommend-saving-models` Args: obj: saved object f: a file-like object (has to implement write and flush) or a string containing a file name pickle_module: module used for pickling metadata and objects pickle_protocol: can be specified to override the default protocol .. warning:: If you are using Python 2, torch.save does NOT support StringIO.StringIO as a valid file-like object. This is because the write method should return the number of bytes written; StringIO.write() does not do this. Please use something like io.BytesIO instead.
函数功能是将字典保存为磁盘文件(二进制数据),那么我们在torch.load()时,就是在内存中加载二进制数据,这就是报错点。
解决方案:将字典保存为BytesIO文件之后,模型再net.load_state_dict()
#b为自定义的字典 torch.save(b,'new.pkl') net.load_state_dict(torch.load(b))
解决方法很简单,主要记录解决思路。
以上这篇pytorch加载自定义网络权重的实现就是小编分享给大家的全部内容了,希望能给大家一个参考
您可能感兴趣的文章:
相关文章推荐
- 自定义带进度的ProgressRelativeLayout,实现加载网络数据时有进度条样式
- 使用自定义的item、Adapter和AsyncTask、第三方开源框架PullToRefresh联合使用实现自定义的下拉列表(从网络加载图片显示在item中的ImageView)
- 自定义ImageView实现类似微信朋友圈发图片点击出来阴影效果;同时使用Picasso加载网络图片
- Android--自定义View加载网络图片,实现缩放,圆形剪裁
- TextView使用自定义HtmlHttpImageGetter实现异步加载网络图片,可限制加载图片数量
- 使用自定义的item、Adapter和AsyncTask、第三方开源框架PullToRefresh联合使用实现自定义的下拉列表(从网络加载图片显示在item中的ImageView)
- android自定义BaseAdapter,实现从网络加载包含图片的listview
- Android 自定义圆形头像CircleImageView支持加载网络图片的实现代码
- JS实现的自定义显示加载等待图片插件(loading.gif)
- 自定义ImageLoader实现GridView加载图片
- Silverlight:利用异步加载Xap实现自定义loading效果
- 在Unity3D的网络游戏中实现资源动态加载
- 自定义SwipeRefreshLayout实现上拉加载更多并自带系统的下拉刷新
- 自定义view实现圆形加载
- Android中自定义加载样式图片的具体实现
- Android实现加载网络端图片
- 在Unity3D的网络游戏中实现资源动态加载
- Android异步加载学习笔记之二:实现ListView中的图片数据从网络加载
- 自定义加载网络图片工具: 三级缓存 解决图片显示错位的问题
- IOS开发之异步加载网络图片并缓存本地实现瀑布流(二)