将零列添加到csr_matrix
问题内容:
我有一个MxN稀疏的列csr_matrix
,我想在矩阵的右边添加一些只有零的列。原则上,阵列indptr
,indices
并data
保持相同的,所以我只是想改变矩阵的尺寸。但是,这似乎没有实现。
>>> A = csr_matrix(np.identity(5), dtype = int)
>>> A.toarray()
array([[1, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 1, 0],
[0, 0, 0, 0, 1]])
>>> A.shape
(5, 5)
>>> A.shape = ((5,7))
NotImplementedError: Reshaping not implemented for csr_matrix.
水平堆叠零矩阵似乎也不起作用。
>>> B = csr_matrix(np.zeros([5,2]), dtype = int)
>>> B.toarray()
array([[0, 0],
[0, 0],
[0, 0],
[0, 0],
[0, 0]])
>>> np.hstack((A,B))
array([ <5x5 sparse matrix of type '<type 'numpy.int32'>'
with 5 stored elements in Compressed Sparse Row format>,
<5x2 sparse matrix of type '<type 'numpy.int32'>'
with 0 stored elements in Compressed Sparse Row format>], dtype=object)
这是我最终要实现的目标。是否可以快速重塑我的造型csr_matrix
而不复制其中的所有内容?
>>> C = csr_matrix(np.hstack((A.toarray(), B.toarray())))
>>> C.toarray()
array([[1, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0]])
问题答案:
您要做的并不是真正的numpy或scipy理解为重塑。但是对于您的特定情况,您可以重新创建CSR矩阵data
,indices
并重新使用indptr
,而无需复制它们:
import scipy.sparse as sps
a = sps.rand(10000, 10000, density=0.01, format='csr')
In [19]: %timeit sps.csr_matrix((a.data, a.indices, a.indptr),
... shape=(10000, 10020), copy=True)
100 loops, best of 3: 6.26 ms per loop
In [20]: %timeit sps.csr_matrix((a.data, a.indices, a.indptr),
... shape=(10000, 10020), copy=False)
10000 loops, best of 3: 47.3 us per loop
In [21]: %timeit sps.csr_matrix((a.data, a.indices, a.indptr),
... shape=(10000, 10020))
10000 loops, best of 3: 48.2 us per loop
因此,如果您不再需要原始矩阵a
,因为默认值为copy=False
,则只需执行以下操作:
a = sps.csr_matrix((a.data, a.indices, a.indptr), shape=(10000, 10020))