对于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
设计为在 ndarrays 上运行。但是稀疏矩阵不是这样的数组,也不是子类(原样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(数组,fp,协议=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
. 否则我在稀疏文件中找不到任何特殊的酸洗代码。