以可移植数据格式保存/加载scipy稀疏csr_matrix


问题内容

如何csr_matrix以可移植格式保存/加载稀疏稀疏?稀疏稀疏矩阵是在Python 3(Windows 64位)上创建的,以在Python
2(Linux 64位)上运行。最初,我使用pickle(协议= 2,fix_imports = True),但是从Python 3.2.2(Windows
64位)到Python 2.7.2(Windows 32位)不起作用,并出现错误:

TypeError: ('data type not understood', <built-in function _reconstruct>, (<type 'numpy.ndarray'>, (0,), '[98]')).

接下来,尝试了numpy.savenumpy.load以及,scipy.io.mmwrite()并且scipy.io.mmread()这些方法都不起作用。


问题答案:

编辑: SciPy
1.19现在具有scipy.sparse.save_npzscipy.sparse.load_npz

from scipy import sparse

sparse.save_npz("yourmatrix.npz", your_matrix)
your_matrix_back = sparse.load_npz("yourmatrix.npz")

对于这两个函数,file参数也可以是类似于文件的对象(即的结果open),而不是文件名。


从Scipy用户组得到了答案:

一个csr_matrix有3个数据属性此事:.data.indices,和.indptr。所有都是简单的ndarray,因此numpy.save可以在它们上使用。用numpy.save或保存三个数组,用numpy.savez加载它们numpy.load,然后用以下方法重新创建稀疏矩阵对象:

new_csr = csr_matrix((data, indices, indptr), shape=(M, N))

因此,例如:

def save_sparse_csr(filename, array):
    np.savez(filename, data=array.data, indices=array.indices,
             indptr=array.indptr, shape=array.shape)

def load_sparse_csr(filename):
    loader = np.load(filename)
    return csr_matrix((loader['data'], loader['indices'], loader['indptr']),
                      shape=loader['shape'])