CSR矩阵将其值存储在3个数组中。它不是一个数组或数组子类,因此h5py
不能直接保存它。你能做的最好的事情是保存属性,并在加载时重新创建矩阵:
In [248]: M = sparse.random(5,10,.1, 'csr')
In [249]: M
Out[249]:
<5x10 sparse matrix of type '<class 'numpy.float64'>'
with 5 stored elements in Compressed Sparse Row format>
In [250]: M.data
Out[250]: array([ 0.91615298, 0.49907752, 0.09197862, 0.90442401, 0.93772772])
In [251]: M.indptr
Out[251]: array([0, 0, 1, 2, 3, 5], dtype=int32)
In [252]: M.indices
Out[252]: array([5, 7, 5, 2, 6], dtype=int32)
In [253]: M.data
Out[253]: array([ 0.91615298, 0.49907752, 0.09197862, 0.90442401, 0.93772772])
coo
格式具有 data
、row
和 col
属性,基本上与您用于创建 a
的 (dat,(row,col))
相同。
In [254]: M.tocoo().row
Out[254]: array([1, 2, 3, 4, 4], dtype=int32)
新的
save_npz
函数的功能如下:
arrays_dict = dict(format=matrix.format, shape=matrix.shape, data=matrix.data)
if matrix.format in ('csc', 'csr', 'bsr'):
arrays_dict.update(indices=matrix.indices, indptr=matrix.indptr)
...
elif matrix.format == 'coo':
arrays_dict.update(row=matrix.row, col=matrix.col)
...
np.savez(file, **arrays_dict)
换句话说,它会将相关属性收集到一个字典中,并使用
savez
创建zip归档文件。类似的方法也可以用于
h5py
文件。有关
save_npz
的更多信息,请参阅最近的SO问题,并链接到源代码。
save_npz方法缺失于scipy.sparse
看看你能否让它工作。如果您可以创建一个
csr
矩阵,则可以从其属性(或等效的
coo
)重新创建它。如果需要,我可以提供一个可行的示例。
将csr转换为h5py的示例。
import numpy as np
import h5py
from scipy import sparse
M = sparse.random(10,10,.2, 'csr')
print(repr(M))
print(M.data)
print(M.indices)
print(M.indptr)
f = h5py.File('sparse.h5','w')
g = f.create_group('Mcsr')
g.create_dataset('data',data=M.data)
g.create_dataset('indptr',data=M.indptr)
g.create_dataset('indices',data=M.indices)
g.attrs['shape'] = M.shape
f.close()
f = h5py.File('sparse.h5','r')
print(list(f.keys()))
print(list(f['Mcsr'].keys()))
g2 = f['Mcsr']
print(g2.attrs['shape'])
M1 = sparse.csr_matrix((g2['data'][:],g2['indices'][:],
g2['indptr'][:]), g2.attrs['shape'])
print(repr(M1))
print(np.allclose(M1.A, M.A))
f.close()
生产
1314:~/mypy$ python3 stack43390038.py
<10x10 sparse matrix of type '<class 'numpy.float64'>'
with 20 stored elements in Compressed Sparse Row format>
[ 0.13640389 0.92698959 .... 0.7762265 ]
[4 5 0 3 0 2 0 2 5 6 7 1 7 9 1 3 4 6 8 9]
[ 0 2 4 6 9 11 11 11 14 19 20]
['Mcsr']
['data', 'indices', 'indptr']
[10 10]
<10x10 sparse matrix of type '<class 'numpy.float64'>'
with 20 stored elements in Compressed Sparse Row format>
True
COO 替代方案
Mo = M.tocoo()
g = f.create_group('Mcoo')
g.create_dataset('data', data=Mo.data)
g.create_dataset('row', data=Mo.row)
g.create_dataset('col', data=Mo.col)
g.attrs['shape'] = Mo.shape
g2 = f['Mcoo']
M2 = sparse.coo_matrix((g2['data'], (g2['row'], g2['col'])),
g2.attrs['shape'])
a
不是 numpy 数组或其子类。首先只需保存输入dat
、row
、col
。最近的scipy.sparse
版本有一个save_npz
函数,可以作为模板 - 查看它的代码即可。 - hpauljsave_npz
的问题,链接为http://stackoverflow.com/q/43014503 - hpaulj