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设计】。

相关文章

Django urls.py重构及参数传递详解

Django urls.py重构及参数传递详解

1. 内部重构# 2. 外部重构# website/blog/urls.py website/website/urls.py 3. 两种参数处理方式 # 1. blog/ind...

TensorFlow Session使用的两种方法小结

TensorFlow Session使用的两种方法小结

TensorFlow Session 在TensorFlow中是通过session进行交互的,使用session有两种方法。下面通过一个简单的例子(两个矩阵相乘)说一下 {[3,1] 与...

Python连接phoenix的方法示例

本文实例讲述了Python连接phoenix的方法。分享给大家供大家参考,具体如下: phoenix是由saleforce.com开源的一个项目,后又捐给了Apache。它相当于一个Ja...

Python实现平行坐标图的绘制(plotly)方式

Python实现平行坐标图的绘制(plotly)方式

平行坐标图简介 当数据的维度超过三维时,此时数据的可视化就变得不再那么简单。为解决高维数据的可视化问题,我们可以使用平行坐标图。以下关于平行坐标图的解释引自百度百科:为了克服传统的笛卡尔...

PyTorch中的padding(边缘填充)操作方式

PyTorch中的padding(边缘填充)操作方式

简介 我们知道,在对图像执行卷积操作时,如果不对图像边缘进行填充,卷积核将无法到达图像边缘的像素,而且卷积前后图像的尺寸也会发生变化,这会造成许多麻烦。 因此现在各大深度学习框架的卷积层...