Python: how do you store a sparse matrix using python?

前端 未结 7 1943
灰色年华
灰色年华 2021-02-06 06:17

I have got an output using sparse matrix in python, i need to store this sparse matrix in my hard disk, how can i do it? if i should create a database then how should i do?? thi

7条回答
  •  一生所求
    2021-02-06 07:09

    For me, using the -1 option in cPickle.dump function caused the pickled file to not be loadable afterwards.

    The object I dumped through cPickle was an instance of scipy.sparse.dok_matrix.

    Using only two arguments did the trick for me; documentation about pickle.dump() states the default value of the protocol parameter is 0.

    Working on Windows 7, Python 2.7.2 (64 bits), and cPickle v 1.71.

    Example:

    >>> import cPickle
    >>> print cPickle.__version__
    1.71
    >>> from scipy import sparse
    >>> H = sparse.dok_matrix((135, 654), dtype='int32')
    >>> H[33, 44] = 8
    >>> H[123, 321] = -99
    >>> print str(H)
      (123, 321)    -99
      (33, 44)  8
    >>> fname = 'dok_matrix.pkl'
    >>> f = open(fname, mode="wb")
    >>> cPickle.dump(H, f)
    >>> f.close()
    >>> f = open(fname, mode="rb")
    >>> M = cPickle.load(f)
    >>> f.close()
    >>> print str(M)
      (123, 321)    -99
      (33, 44)  8
    >>> M == H
    True
    >>> 
    

提交回复
热议问题