我有一个大的稀疏块对角矩阵,我想对角线化。我可以将各个块对角线对角化,但这意味着在许多小的(6x6到15x15)矩阵中进行特征分解,并将所有结果堆叠在稀疏矩阵中。这样可行,但循环的大小使其不可行。这是我的基于循环的代码,它表明您可以使用它来重建原始矩阵。在我的情况下,我做的不仅仅是重建,但在我的情况下,这仅仅意味着我在循环中对特征值做了一些事情。
我没有Numba或Cython的经验,我也不知道他们是否会在这种情况下有用。
import numpy as np
import scipy.sparse as sp
# A fast block_diag for equally sized blocks
# Currently a PR in scipy: https://github.com/scipy/scipy/pull/5619)
from utils import block_diag
n_pixels = 10 # Number of elements
n_p = 7 # Number of elements per block
# Main diagonal of each block
sigma = np.array([0.12, 0.7, 0.0959, 0.15, 1.5, 0.2, 0.5])
# The individual block definition
little_p = np.diag ( sigma**2).astype(np.float32)
# Add some off-diagonal elements. For fun.
little_p[5,2] = 0.8862*0.0959*0.2
little_p[2,5] = 0.8862*0.0959*0.2
# Stack a large number of these in a block diagonal matrix
xlist = [little_p for m in xrange(n_pixels)]
A = block_diag(xlist, dtype=np.float32)
# Try to reconstruct using diagonalisation of individual blocks
blocks = []
A = A.tolil()
for i in xrange(n_pixels):
M = A[(i*n_p):((i+1)*n_p), (i*n_p):((i+1)*n_p)].todense()
s,u = np.linalg.eigh(M)
blocks.append ( u.dot(np.diag(s).dot(u.T)) )
B = block_diag(blocks, dtype=np.float32)
np.allclose(B.todense(), A.todense()) # Should be True