将对角稀疏矩阵转换为一维向量
Convert a Diagonal Sparse Matrix to a 1-D vector
我有一个很大的 n 方对角矩阵,采用 scipy 的稀疏 DIA 格式
(假设 n = 100000)
D_sparse = sprs.diags(np.ones(100000),0)
我想将对角线检索为向量(在 numpy 数组中)
但是如果我这样做 np.diag(D_sparse.toarray())
,我会得到一个 MemoryError
因为 D_sparse.toarray()
生成一个巨大的数组,准全是 0.
我有方法或函数可以直接将 D_sparse
的对角线作为 numpy 数组吗?
dia_matrix
对象returns主对角线的diagonal
方法。
例如,
In [165]: d
Out[165]:
<6x6 sparse matrix of type '<class 'numpy.float64'>'
with 6 stored elements (1 diagonals) in DIAgonal format>
In [166]: d.A
Out[166]:
array([[ 10., 0., 0., 0., 0., 0.],
[ 0., 11., 0., 0., 0., 0.],
[ 0., 0., 12., 0., 0., 0.],
[ 0., 0., 0., 13., 0., 0.],
[ 0., 0., 0., 0., 14., 0.],
[ 0., 0., 0., 0., 0., 15.]])
In [167]: d.diagonal()
Out[167]: array([ 10., 11., 12., 13., 14., 15.])
我有一个很大的 n 方对角矩阵,采用 scipy 的稀疏 DIA 格式 (假设 n = 100000)
D_sparse = sprs.diags(np.ones(100000),0)
我想将对角线检索为向量(在 numpy 数组中)
但是如果我这样做 np.diag(D_sparse.toarray())
,我会得到一个 MemoryError
因为 D_sparse.toarray()
生成一个巨大的数组,准全是 0.
我有方法或函数可以直接将 D_sparse
的对角线作为 numpy 数组吗?
dia_matrix
对象returns主对角线的diagonal
方法。
例如,
In [165]: d
Out[165]:
<6x6 sparse matrix of type '<class 'numpy.float64'>'
with 6 stored elements (1 diagonals) in DIAgonal format>
In [166]: d.A
Out[166]:
array([[ 10., 0., 0., 0., 0., 0.],
[ 0., 11., 0., 0., 0., 0.],
[ 0., 0., 12., 0., 0., 0.],
[ 0., 0., 0., 13., 0., 0.],
[ 0., 0., 0., 0., 14., 0.],
[ 0., 0., 0., 0., 0., 15.]])
In [167]: d.diagonal()
Out[167]: array([ 10., 11., 12., 13., 14., 15.])