在稀疏lil_matrix中找到最大值及其索引(Scipy/Python) [英] Finding maximum value and their indices in a sparse lil_matrix (Scipy/Python)
问题描述
在Scipy稀疏使用itertools.izip 遍历非零条目,但是还有什么更好的办法吗?我觉得我这里缺少明显的东西.
What's the best way to find the maximum value and their corresponding row and column indices in a Scipy sparse lil_matrix object ? I can loop through the nonzero entries using itertools.izip, but is there anything better ? I feel like I'm missing something obvious here ..
推荐答案
您可以转换为COO格式,然后使用data
,row
和col
属性.
You could convert to COO format, and then use the data
, row
and col
attributes.
例如,假设LIL矩阵为x
.这是一种获取最大值及其行和列的方法:
For example, suppose the LIL matrix is x
. Here's one way to get the maximum value along with its row and column:
In [41]: x
Out[41]:
<1000x1000 sparse matrix of type '<type 'numpy.float64'>'
with 1999 stored elements in LInked List format>
In [42]: y = x.tocoo()
In [43]: k = y.data.argmax()
In [44]: maxval = y.data[k]
In [45]: maxrow = y.row[k]
In [46]: maxcol = y.col[k]
注意:上面的代码中有两个错误:
Note: There are two bugs in the above code:
- 如果所有非零值均为负,它将找到最大的负值.但是在这种情况下,正确答案应该为0.
- 如果没有 no 个非零值,则
k = y.data.argmax()
行将引发异常,因为y.data
是一个空数组.
- If all the nonzero values are negative, it will find the largest negative value. But the correct answer should be 0 in that case.
- If there are no nonzero values, then the line
k = y.data.argmax()
will raise an exception, becausey.data
is an empty array.
如果在您的应用程序中不会发生这些情况,那么可以忽略这些错误.
If those cases can't happen in your application, then those bugs can be ignored.
这篇关于在稀疏lil_matrix中找到最大值及其索引(Scipy/Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!