对于mmwrite 答案的所有赞成票,我很惊讶没有人试图回答实际问题。不过既然重启了,那我试试看。
这再现了 OP 案例:
In [90]: x=sparse.csr_matrix(np.arange(10).reshape(2,5))
In [91]: np.save('save_sparse.npy',x)
In [92]: X=np.load('save_sparse.npy')
In [95]: X
Out[95]:
array(<2x5 sparse matrix of type '<type 'numpy.int32'>'
with 9 stored elements in Compressed Sparse Row format>, dtype=object)
In [96]: X[()].A
Out[96]:
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
In [93]: X[()].A
Out[93]:
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
In [94]: x
Out[94]:
<2x5 sparse matrix of type '<type 'numpy.int32'>'
with 9 stored elements in Compressed Sparse Row format
`user4713166 给我们的[()] 并不是提取稀疏数组的“硬方法”。
np.save 和 np.load 设计用于在 ndarray 上运行。但是稀疏矩阵不是这样的数组,也不是子类(就像np.matrix 一样)。 np.save 似乎将非数组对象包装在 object dtype array 中,并将其与对象的腌制形式一起保存。
当我尝试保存另一种无法腌制的对象时,我在以下位置收到错误消息:
403 # We contain Python objects so we cannot write out the data directly.
404 # Instead, we will pickle it out with version 2 of the pickle protocol.
--> 405 pickle.dump(array, fp, protocol=2)
所以回答Is Scipy smart enough to understand that it has loaded a sparse array?,不。 np.load 不知道稀疏数组。但是np.save 足够聪明,可以在给定不是数组的东西时下注,而np.load 会根据在文件中找到的内容尽其所能。
关于保存和加载稀疏数组的替代方法,已经提到了io.savemat,MATLAB 兼容方法。这将是我的第一选择。但是这个例子也表明你可以使用普通的 Python pickling。如果您需要保存特定的稀疏格式,那可能会更好。如果您可以接受[()] 提取步骤,np.save 也不错。 :)
https://github.com/scipy/scipy/blob/master/scipy/io/matlab/mio5.py
write_sparse - 稀疏以csc 格式保存。除了标题之外,它还保存A.indices.astype('i4'))、A.indptr.astype('i4'))、A.data.real 和可选的A.data.imag。
在快速测试中,我发现np.save/load 处理所有稀疏格式,除了dok,load 抱怨缺少shape。否则我在稀疏文件中找不到任何特殊的酸洗代码。