SciPy:稀疏CSR矩阵的对称排列

SciPy: Symmetric permutation of sparse CSR matrix

我想对称置换稀疏矩阵,以相同的方式置换行和列。例如,我想旋转行和列,这需要:

 1     2     3
 0     1     0
 0     0     1

 1     0     0
 0     1     0
 2     3     1

在 Octave 或 MATLAB 中,可以使用矩阵索引简洁地完成此操作:

A = sparse([1 2 3; 0 1 0; 0 0 1]);
perm = [2 3 1];
Aperm = A(perm,perm);

我有兴趣在 Python 和 NumPy/SciPy 中进行此操作。这是一个尝试:

#!/usr/bin/env python
import numpy as np
from scipy.sparse import csr_matrix

row = np.array([0, 0, 0, 1, 2])
col = np.array([0, 1, 2, 1, 2])
data = np.array([1, 2, 3, 1, 1])
A = csr_matrix((data, (row, col)), shape=(3, 3))

p = np.array([1, 2, 0])

#Aperm = A[p,p]            # gives [1,1,1], the permuted diagonal
Aperm = A[:,p][p,:]        # works, but more verbose

有没有更简洁的方法来完成这种矩阵的对称排列?

(我对简洁的语法比对性能更感兴趣)

在 MATLAB 中

A(perm,perm)

是块操作。 In numpy A[perm,perm] 选择对角线上的元素。

A[perm[:,None], perm]

是块索引。 MATLAB 对角线需要类似 sub2ind 的东西。一个是简洁的,另一个是冗长的,v.v.

实际上numpy在这两种情况下使用相同的逻辑。它 'broadcasts' 一个索引对另一个,A (n,) 在对角线情况下对 (n,),在块情况下 (n,1)(1,n)。结果是 (n,)(n,n) 形。

numpy 索引也适用于稀疏矩阵,但速度不那么快。它实际上使用矩阵乘法来进行这种索引 - 使用基于索引的 'extractor' 矩阵(可能是 2,M*A*M.T)。


MATLAB 关于置换矩阵的文档:

https://www.mathworks.com/help/matlab/math/sparse-matrix-operations.html#f6-13070