交换行 csr_matrix scipy [英] Swap rows csr_matrix scipy

查看:76
本文介绍了交换行 csr_matrix scipy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 scipy 中有一个 256x256 csr_matrix,我有一个我想应用的新行顺序列表.我试过这个:

I have a 256x256 csr_matrix in scipy and I have a list of a new row order that I'd like to apply. I tried this:

def HblockDiag(z):
        Hz = H(z) # H(z) returns a 256x256 csr_matrix
        Hz.indices = idenRows
        return Hz

但它不起作用,因为 indices 没有给出每一行的索引......这样做的最佳方法是什么?

but it didn't work work because indices doesn't give the indices of each row... What's the best way to do this?

def HblockDiag(H, idenRows):
    x = H.tocoo()
    idenRows = np.asarray(idenRows, dtype=x.row.dtype)
    x.row = idenRows[x.row]
    H = x.tocsr()
    return H

test = sps.csr_matrix([[1,2,4],[6,3,4],[8,5,2]])
print test.toarray()
test = HblockDiag(test, [2,0,1])
print test.toarray()

我明白了:

[[1 2 4]
 [6 3 4]
 [8 5 2]]
[[6 3 4]
 [8 5 2]
 [1 2 4]]

相反,我想得到:

[[8 5 2]
 [1 2 4]
 [6 3 4]]

推荐答案

  • 从 CSR 转换为 COO 格式.

    • Convert from CSR to COO format.

      x = Hz.tocoo()
      

      根据文档字符串 sparse.coo_matrix.__doc__,COO 具有与 CSR/CSC 格式之间的快速转换".

      Per the doc string, sparse.coo_matrix.__doc__, COO has "very fast conversion to and from CSR/CSC formats".

      排列 COO 矩阵的行

      Permute the rows of the COO matrix

      idenRows = np.argsort(idenRows)
      x.row = idenRows[x.row]
      

    • 从 COO 转回 CSR

    • Convert from COO back to CSR

      Hz = x.tocsr()
      

    • 例如

      import numpy as np
      import scipy.sparse as sps
      
      def HblockDiag(H, idenRows):
          x = H.tocoo()
          idenRows = np.argsort(idenRows)
          idenRows = np.asarray(idenRows, dtype=x.row.dtype)
          x.row = idenRows[x.row]
          H = x.tocsr()
          return H
      
      test = sps.csr_matrix([[1,2,4],[6,3,4],[8,5,2]])
      print test.toarray()
      # [[1 2 4]
      #  [6 3 4]
      #  [8 5 2]]
      
      test = HblockDiag(test, [2,0,1])
      print test.toarray()
      

      收益

      [[8 5 2]
       [1 2 4]
       [6 3 4]]
      

      <小时>

      附注.一般只有在矩阵的大小非常大时才使用稀疏矩阵.如果形状仅为 (256, 256),则不清楚为什么要使用稀疏矩阵.此外,矩阵应包含稀疏矩阵至少有 80% 的零值.

      这篇关于交换行 csr_matrix scipy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆