如何在SciPy稀疏矩阵中迭代一行?

7

我有一个稀疏矩阵随机矩阵,创建方法如下:

import numpy as np
from scipy.sparse import rand
foo = rand(100, 100, density=0.1, format='csr')

我想循环遍历特定行中的单元格并执行两个计算:
row1 = foo.getrow(bar1)
row2 = foo.getrow(bar2)

"""
Like the following:
sum1 = 0
sum2 = 0
for each cell x in row1:
    sum1 += x
    if the corresponding cell (in the same column) in row2 y is non-zero:
        sum2 += x*y
"""

1
你只是在寻找一个解决方案还是一个高效的解决方案? - tooty44
一个高效的方法,我宁愿不使用"todense"。 - gornvix
1个回答

3
这里有一种方法 -
# Get first row summation by simply using sum method of sparse matrix
sum1 = row1.sum()

# Get the non-zero indices of first row
idx1 = row1.indices
data1 = row1.data  # Or get sum1 here with : `data1.sum()`.

# Get the non-zero indices of second row and corresponding data
idx2 = row2.indices
data2 = row2.data

# Get mask of overlap from row1 nonzeros on row2 nonzeros. 
# Select those from data2 and sum those up for the second summation o/p.
sum2 = data1[np.in1d(idx1,idx2)].dot(data2[np.in1d(idx2,idx1)])

另外,正如@user2357112的评论所建议的那样,我们可以简单地使用矩阵乘法来获得第二个求和 -

sum2 = sum((row1*row2.T).data)

1
在我看来,您可以使用 row1 * row2.T 来简化大部分 sum2 计算。 - user2357112
@user2357112 好主意!已添加到帖子中。谢谢! - Divakar
我在(row1*row2.T).data[0]处遇到了间歇性错误。如果没有碰撞,例如乘积为0时,这个方法能正常工作吗? - gornvix
1
@tyebillion 是的,那确实是一个bug。现在应该已经修复了。去看看吧! - Divakar

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