高效重塑稀疏矩阵,Python,SciPy 0.12
如果要添加更多的行或列,则可分别使用高效重塑稀疏矩阵,Python,SciPy 0.12,python,scipy,sparse-matrix,Python,Scipy,Sparse Matrix,如果要添加更多的行或列,则可分别使用scipy.sparse.vstack或hstack,接受答案将起作用。在SciPy 0.12中,仍然没有实现or方法 在SciPy 0.12中,是否有一些稳定的良好实践来重塑稀疏矩阵?进行一些时间比较会很好。我不知道有任何既定的良好实践,因此这里有一个相当直接的coo_矩阵重塑函数。它将其参数转换为coo_矩阵,因此它将实际用于其他稀疏格式(但返回coo_矩阵) 例如: In [43]: a = coo_matrix([[0,10,0,0],[0,0,0,0
scipy.sparse.vstack
或hstack
,接受答案将起作用。在SciPy 0.12中,仍然没有实现or方法
在SciPy 0.12中,是否有一些稳定的良好实践来重塑稀疏矩阵?进行一些时间比较会很好。我不知道有任何既定的良好实践,因此这里有一个相当直接的coo_矩阵重塑函数。它将其参数转换为coo_矩阵,因此它将实际用于其他稀疏格式(但返回coo_矩阵) 例如:
In [43]: a = coo_matrix([[0,10,0,0],[0,0,0,0],[0,20,30,40]])
In [44]: a.A
Out[44]:
array([[ 0, 10, 0, 0],
[ 0, 0, 0, 0],
[ 0, 20, 30, 40]])
In [45]: b = reshape(a, (2,6))
In [46]: b.A
Out[46]:
array([[ 0, 10, 0, 0, 0, 0],
[ 0, 0, 0, 20, 30, 40]])
现在,我确信这里有几个常规的贡献者可以想出更好的方法(更快、更高效、更少的内存填充…)我有一个CSR矩阵的工作示例,但我不能保证它总是有效的 展平矩阵A:
indices = zeros_like(A.indices)
indices[A.indptr[1:-1]] = A.shape[1]
indices = cumsum( indices)+A.indices
A_flat = sparse.csc_matrix((T_rot.data, indices,[0,size(A)]),shape=(prod(A.shape),1))
重塑矩阵A
indices = zeros_like(A.indices)
indices[A.indptr[1:-1]] = A.shape[1]
indices = cumsum( indices)+A.indices
indices %= N*A.shape[1]
indptr = r_[0, where(diff(indices)<0)[0]+1, size(A)]
A_reshaped = sparse.csc_matrix((A.data, indices,indptr),shape=(N*A.shape[1],A.shape[0]/N ))
索引=类零(A.索引)
索引[A.indptr[1:-1]]=A.shape[1]
指数=总和(指数)+A指数
指数%=N*A.shape[1]
indptr=r_0,其中(diff(index)截至,和set_shape
方法已针对所有稀疏矩阵类型实施。签名是您所期望的,并且与NumPy中的等效方法尽可能相同(例如,您不能重塑为向量或张量)
签名:
重塑(self,shape:Tuple[int,int],顺序:'C'|'F'='C',copy:bool=False)->spmatrix
例如:
In [43]: a = coo_matrix([[0,10,0,0],[0,0,0,0],[0,20,30,40]])
In [44]: a.A
Out[44]:
array([[ 0, 10, 0, 0],
[ 0, 0, 0, 0],
[ 0, 20, 30, 40]])
In [45]: b = reshape(a, (2,6))
In [46]: b.A
Out[46]:
array([[ 0, 10, 0, 0, 0, 0],
[ 0, 0, 0, 20, 30, 40]])
>>从scipy.sparse导入csr\u矩阵
>>>A=csr_矩阵([[0,0,2,0],[0,1,0,3]]
>>>印刷品(A)
(0, 2) 2
(1, 1) 1
(1, 3) 3
>>>B=A.重塑((4,2))
>>>印刷品(B)
(1, 0) 2
(2, 1) 1
(3, 1) 3
>>>C=A.重塑((4,2),顺序='F')
>>>印刷品(C)
(0, 1) 2
(3, 0) 1
(3, 1) 3
全面披露:我了解了实施情况。更新:这个问题已在中得到解决,@Warren Weckesser的解决方案已被选中。