【问题标题】:Given a matrix of type `scipy.sparse.coo_matrix` how to determine index and value of maximum of each row?给定“scipy.sparse.coo_matrix”类型的矩阵,如何确定每行的最大值的索引和值?
【发布时间】:2012-03-05 08:07:09
【问题描述】:

给定一个稀疏矩阵R,类型为scipy.sparse.coo_matrix,形状为1.000.000 x 70.000,我想通了

row_maximum = max(R.getrow(i).data)

会给我第 i 行的最大值。

我现在需要的是值row_maximum对应的索引。

有什么想法可以实现吗?

提前感谢您的任何建议!

【问题讨论】:

    标签: python matrix scipy max sparse-matrix


    【解决方案1】:

    getrow(i) 返回一个 1 x n 的 CSR 矩阵,该矩阵具有一个 indices 属性,该属性给出了 data 属性中相应值的行索引。 (我们知道形状是 1 x n,所以我们不必处理 indptr 属性。)所以这会起作用:

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

    我们必须单独处理row.nnz为0的情况,因为如果row.data为空数组,row.data.argmax()会引发异常。

    【讨论】:

      【解决方案2】:

      使用numpy.argmax(或scipy.argmax,这是同一件事)

      index_of_maximum = scipy.argmax(R.getrow(i).data)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-09
        • 2022-01-23
        • 1970-01-01
        • 1970-01-01
        • 2020-10-11
        • 1970-01-01
        • 1970-01-01
        • 2019-06-01
        相关资源
        最近更新 更多