简体   繁体   English

在稀疏lil_matrix(Scipy / Python)中查找最大值及其索引

[英]Finding maximum value and their indices in a sparse lil_matrix (Scipy/Python)

What's the best way to find the maximum value and their corresponding row and column indices in a Scipy sparse lil_matrix object ? 在Scipy稀疏lil_matrix对象中找到最大值及其对应的行和列索引的最佳方法是什么? I can loop through the nonzero entries using itertools.izip , but is there anything better ? 我可以使用itertools.izip遍历非零条目 ,但有什么更好的吗? I feel like I'm missing something obvious here .. 我觉得我在这里遗漏了一些明显的东西......

You could convert to COO format, and then use the data , row and col attributes. 您可以转换为COO格式,然后使用datarowcol属性。

For example, suppose the LIL matrix is x . 例如,假设LIL矩阵是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: 注意:上面的代码中有两个错误:

  • If all the nonzero values are negative, it will find the largest negative value. 如果所有非零值都为负,则会找到最大的负值。 But the correct answer should be 0 in that case. 但在这种情况下,正确答案应为0。
  • If there are no nonzero values, then the line k = y.data.argmax() will raise an exception, because y.data is an empty array. 如果没有非零值,则行k = y.data.argmax()将引发异常,因为y.data是一个空数组。

If those cases can't happen in your application, then those bugs can be ignored. 如果在您的应用程序中不能发生这些情况,则可以忽略这些错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM