在csr_matrix中添加一列零

8

我有一个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]])
2个回答

9
您可以使用scipy.sparse.vstackscipy.sparse.hstack来更快地完成此操作:
from scipy.sparse import csr_matrix, vstack, hstack

B = csr_matrix((5, 2), dtype=int)
C = csr_matrix((5, 2), dtype=int)
D = csr_matrix((10, 10), dtype=int)

B2 = vstack((B, C))
#<10x2 sparse matrix of type '<type 'numpy.int32'>'
#        with 0 stored elements in COOrdinate format>

hstack((B2, D))
#<10x12 sparse matrix of type '<type 'numpy.int32'>'
#        with 0 stored elements in COOrdinate format>

请注意,输出结果是一个coo_matrix,可以高效地转换为CSR或CSC格式。

6

您想要做的并不是 numpy 或 scipy 理解的重塑。但是针对您的特定情况,您可以创建一个新的 CSR 矩阵,重用原始矩阵中的 dataindicesindptr,而无需复制它们:

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))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接