1. 程式人生 > >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()

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))

解決方法很簡單,主要記錄解決思路。