[英]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格式,然后使用
data
, row
和col
属性。
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: 注意:上面的代码中有两个错误:
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.