【问题标题】:Swap rows csr_matrix scipy交换行 csr_matrix scipy
【发布时间】:2015-02-05 12:24:09
【问题描述】:

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

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

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


编辑:

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]]

【问题讨论】:

  • 什么是idenRows?除非你了解csr格式,否则最好使用索引,而不是尝试直接修改属性。
  • idenRows 是具有新行顺序的向量。所以:[0,1,3,2] 将交换第 2 行和第 3 行。(这只是一个例子,idenRows 实际上是 256 个元素长)
  • 只是为了确定:想要的结果是[[8 5 2], [1 2 4], [6 3 4]]吗?如果是这样,请编辑问题以包含此内容。

标签: numpy scipy


【解决方案1】:
  • 从 CSR 转换为 COO 格式。

    x = Hz.tocoo()
    

    根据文档字符串sparse.coo_matrix.__doc__,COO 具有“与 CSR/CSC 格式的非常快速的转换”。

  • 置换COO矩阵的行

    idenRows = np.argsort(idenRows)
    x.row = idenRows[x.row]
    
  • 从 COO 转回 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]]

PS。通常,只有当矩阵的大小非常大时才使用稀疏矩阵。如果形状仅为 (256, 256),尚不清楚为什么要使用稀疏矩阵。此外,矩阵应包含at least 80% zeros for sparse matrices to pay off

【讨论】:

  • 不确定它是否有效(请参阅我的编辑)。不过谢谢!
  • 我猜你想要[[8 5 2], [1 2 4], [6 3 4]]。在这种情况下,使用idenRows = np.argsort(idenRows)idenRows 转换为正确的值,以便使用x.row = idenRows[x.row] 进行索引。
猜你喜欢
  • 2016-01-21
  • 2023-03-17
  • 2014-10-22
  • 2015-08-02
  • 2020-02-01
  • 2023-03-31
  • 2022-01-26
  • 2013-03-11
  • 2020-11-25
相关资源
最近更新 更多