Given a matrix of type `scipy.sparse.coo_matrix` how to determine index and value of maximum of each row?

随声附和 提交于 2019-12-05 17:18:57

getrow(i) returns a 1 x n CSR matrix, which has an indices attribute that gives the row indices of the corresponding values in the data attribute. (We know the shape is 1 x n, so we don't have to deal with the indptr attribute.) So this will work:

row = R.getrow(i)
max_index = row.indices[row.data.argmax()] if row.nnz else 0

We have to deal with the case where row.nnz is 0 separately, because row.data.argmax() will raise an exception if row.data is an empty array.

use numpy.argmax (or scipy.argmax which is the same thing)

index_of_maximum = scipy.argmax(R.getrow(i).data)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!