gpt4 book ai didi

python - 以可移植数据格式保存/加载 scipy sparse csr_matrix

转载 作者:IT老高 更新时间:2023-10-28 21:32:57 25 4
gpt4 key购买 nike

如何以可移植格式保存/加载 scipy 稀疏 csr_matrix? scipy 稀疏矩阵是在 Python 3(Windows 64 位)上创建的,可以在 Python 2(Linux 64 位)上运行。最初,我使用了 pickle(协议(protocol) = 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 0.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 用户组的答复:

A csr_matrix has 3 data attributes that matter: .data, .indices, and .indptr. All are simple ndarrays, so numpy.save will work on them. Save the three arrays with numpy.save or numpy.savez, load them back with numpy.load, and then recreate the sparse matrix object with:

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

关于python - 以可移植数据格式保存/加载 scipy sparse csr_matrix,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8955448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com