python - 对 scipy.sparse.csr_matrix 中的行求和

标签 python numpy scipy scikit-learn sparse-matrix

我有一个大的 csr_matrix,我想添加行并获得一个具有相同列数但行数减少的新 csr_matrix。 (上下文:该矩阵是从sklearn CountVectorizer获得的文档术语矩阵,我希望能够根据与这些文档关联的代码快速组合文档)

举个简单的例子,这是我的矩阵:

import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse import vstack

row = np.array([0, 4, 1, 3, 2])
col = np.array([0, 2, 2, 0, 1])
dat = np.array([1, 2, 3, 4, 5])
A = csr_matrix((dat, (row, col)), shape=(5, 5))
print A.toarray()

[[1 0 0 0 0]
 [0 0 3 0 0]
 [0 5 0 0 0]
 [4 0 0 0 0]
 [0 0 2 0 0]]

不,假设我想要一个新的矩阵 B,其中行 (1, 4) 和 (2, 3, 5) 通过求和来组合,看起来像这样:

[[5 0 0 0 0]
 [0 5 5 0 0]]

并且应该再次采用稀疏格式(因为我正在使用的实际数据很大)。我尝试对矩阵的切片进行求和,然后将其堆叠:

idx1 = [1, 4]
idx2 = [2, 3, 5]
A_sub1 = A[idx1, :].sum(axis=1)
A_sub2 = A[idx2, :].sum(axis=1)
B = vstack((A_sub1, A_sub2))

但这只为我提供了切片中非零列的求和值,因此我无法将其与其他切片组合,因为求和切片中的列数不同。

我觉得一定有一种简单的方法可以做到这一点。但我在网上或文档中找不到任何对此的讨论。我错过了什么?

感谢您的帮助

最佳答案

请注意,您可以通过仔细构建另一个矩阵来做到这一点。以下是密集矩阵的工作原理:

>>> S = np.array([[1, 0, 0, 1, 0,], [0, 1, 1, 0, 1]])
>>> np.dot(S, A.toarray())
array([[5, 0, 0, 0, 0],
       [0, 5, 5, 0, 0]])
>>>

稀疏版本只是稍微复杂一点。有关哪些行应汇总在一起的信息在 row 中编码:

col = range(5)
row = [0, 1, 1, 0, 1]
dat = [1, 1, 1, 1, 1]
S = csr_matrix((dat, (row, col)), shape=(2, 5))
result = S * A
# check that the result is another sparse matrix
print type(result)
# check that the values are the ones we want
print result.toarray()

输出:

<class 'scipy.sparse.csr.csr_matrix'>
[[5 0 0 0 0]
 [0 5 5 0 0]]

您可以通过在 row 中包含更高的值并相应地扩展 S 的形状来处理输出中的更多行。

关于python - 对 scipy.sparse.csr_matrix 中的行求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29629821/

相关文章:

python - 使用 Numpy/SciPy 进行线条平滑

python - 根据列标签 reshape Pandas 中的数据框

Python写入数据库时​​总线报错问题

python - 如何从外部托管源 pip 安装 pyx 包?

python - 从 float 转换为百分比

python - "pyenv virtualenvwrapper"是做什么的?

python - 一致的数字类型检查

python vs Octave 随机生成器

python - 排列numpy中每列内容的最佳方法

python - 为什么我不能通过 import scipy as sp 使用 sp.signal?