溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

pytorch如何加載自定義網(wǎng)絡(luò)權(quán)重

發(fā)布時(shí)間:2021-05-28 10:55:12 來(lái)源:億速云 閱讀:226 作者:小新 欄目:開(kāi)發(fā)技術(shù)

這篇文章主要介紹pytorch如何加載自定義網(wǎng)絡(luò)權(quán)重,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

在將自定義的網(wǎng)絡(luò)權(quán)重加載到網(wǎng)絡(luò)中時(shí),報(bào)錯(cuò):

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.

我們一步一步分析。

模型網(wǎng)絡(luò)權(quán)重保存額代碼是:torch.save(net.state_dict(),'net.pkl')

(1)查看獲取模型權(quán)重的源碼:

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']

  """

將網(wǎng)絡(luò)中所有的狀態(tài)保存到一個(gè)字典中了,我自己構(gòu)建的就是一個(gè)字典,沒(méi)問(wèn)題!

(2)查看保存模型權(quán)重的源碼:

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.

函數(shù)功能是將字典保存為磁盤文件(二進(jìn)制數(shù)據(jù)),那么我們?cè)趖orch.load()時(shí),就是在內(nèi)存中加載二進(jìn)制數(shù)據(jù),這就是報(bào)錯(cuò)點(diǎn)。

解決方案:將字典保存為BytesIO文件之后,模型再net.load_state_dict()

#b為自定義的字典
torch.save(b,'new.pkl')
net.load_state_dict(torch.load(b))

解決方法很簡(jiǎn)單,主要記錄解決思路。

以上是“pytorch如何加載自定義網(wǎng)絡(luò)權(quán)重”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI