pytorch加载自定义网络权重的实现

yipeiwu_com5年前Python基础

在将自定义的网络权重加载到网络中时,报错:

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加载自定义网络权重的实现就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python中zfill()方法的使用教程

 zfill()方法用零垫串来填充左边宽度。 语法 以下是zfill()方法的语法: str.zfill(width) 参数    ...

详解js文件通过python访问数据库方法

详解js文件通过python访问数据库方法

我来教你 js文件怎么通过python访问数据库,希望能够为你带来帮助。 1、如果是要提交表单内容给 服务器的 python 处理,那么只需要在表单 <form> 里面的 a...

Python API自动化框架总结

Python API自动化框架总结

学完了Python脚本接口自动化之后,一直没有对该框架做总结,今天终于试着来做一份总结了。 框架结构如下图: 来说一下每个目录的作用: Configs:该目录下存放的是.conf,.i...

django项目环境搭建及在虚拟机本地创建django项目的教程

django项目环境搭建及在虚拟机本地创建django项目的教程

1.Python虚拟环境创建 首先我们为什么要创建虚拟环境呢?因为不同的项目所依赖的环境不一样,他们需要不同的第三方库等等。为了避免冲突,所以我们要创建虚拟环境,在次此我用的的Linux...

Python图像的增强处理操作示例【基于ImageEnhance类】

Python图像的增强处理操作示例【基于ImageEnhance类】

本文实例讲述了Python图像的增强处理操作。分享给大家供大家参考,具体如下: python中PIL模块中有一个叫做ImageEnhance的类,该类专门用于图像的增强处理,不仅可以增强...