python - 扩展(添加行或列) scipy.sparse 矩阵

标签 python scipy sparse-matrix

假设我有一个来自 scipy.sparse 的 NxN 矩阵 M(lil_matrix 或 csr_matrix),我想将其设为 (N+1)xN,其中 M_modified[i,j] = M[i,j] 为 0 <= i < N(和所有 j)和 M[N,j] = 0 对于所有 j。基本上,我想在 M 的底部添加一行零并保留矩阵的其余部分。有没有办法在不复制数据的情况下做到这一点?

最佳答案

Scipy 无法在不复制数据的情况下执行此操作,但您可以通过更改定义稀疏矩阵的属性自行完成。

构成 csr_matrix 的属性有 4 个:

data:包含矩阵中实际值的数组

indices:一个数组,包含与data中每个值对应的列索引

indptr:一个数组,它指定每行数据中第一个值之前的索引。如果该行为空,则索引与上一列相同。

shape:包含矩阵形状的元组

如果您只是在底部添加一行零,您只需更改矩阵的形状和 indptr。

x = np.ones((3,5))
x = csr_matrix(x)
x.toarray()
>> array([[ 1.,  1.,  1.,  1.,  1.],
          [ 1.,  1.,  1.,  1.,  1.],
          [ 1.,  1.,  1.,  1.,  1.]])
# reshape is not implemented for csr_matrix but you can cheat and do it  yourself.
x._shape = (4,5)
# Update indptr to let it know we added a row with nothing in it. So just append the last
# value in indptr to the end.
# note that you are still copying the indptr array
x.indptr = np.hstack((x.indptr,x.indptr[-1]))
x.toarray()
array([[ 1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.],
       [ 0.,  0.,  0.,  0.,  0.]])

这是一个处理更一般的 vstacking 任意 2 个 csr_matrices 情况的函数。您最终仍然会复制底层的 numpy 数组,但它仍然比 scipy vstack 方法快得多。

def csr_vappend(a,b):
    """ Takes in 2 csr_matrices and appends the second one to the bottom of the first one. 
    Much faster than scipy.sparse.vstack but assumes the type to be csr and overwrites
    the first matrix instead of copying it. The data, indices, and indptr still get copied."""

    a.data = np.hstack((a.data,b.data))
    a.indices = np.hstack((a.indices,b.indices))
    a.indptr = np.hstack((a.indptr,(b.indptr + a.nnz)[1:]))
    a._shape = (a.shape[0]+b.shape[0],b.shape[1])
    return a

关于python - 扩展(添加行或列) scipy.sparse 矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4695337/

相关文章:

python - 将 numpy 数组(行形式)转换为图像

python - 使用 Python/Scipy 对角化大型稀疏矩阵

r - 为Ax = b并行求解Solve()吗?

matlab - 我什么时候应该使用 `sparse` ?

python - 属性错误: 'NoneType' object has no attribute 'group' Can't Parse (Python)

python - 没有适用于 Linux 的 lxml Wheel?

python - 根据已过滤的 pandas 数据帧绘制定义的 x/y 范围的 pcolormesh,即使该行或列不存在于已过滤的数据帧中

Python 的 str.replace 不抛出异常

python - Scipy:在对整个表面进行集成时加快集成速度?

python - Theano 损失函数中的对数行列式