import numpy as np
from time import clock
from scipy.linalg import eigh as largest_eigh
from scipy.sparse.linalg.eigen.arpack import eigsh as largest_eigsh
np.set_printoptions(suppress=True)
np.random.seed(0)
N=5000
k=1
X = np.random.random((N,N)) - 0.5
X = np.dot(X, X.T) #create a symmetric matrix
# Benchmark the dense routine
start = clock()
evals_large, evecs_large = largest_eigh(X, eigvals=(N-k,N-1))
elapsed = (clock() - start)
print ("eigh elapsed time: ", elapsed)
# Benchmark the sparse routine
start = clock()
evals_large_sparse, evecs_large_sparse = largest_eigsh(X, k, which='LM')
elapsed = (clock() - start)
print ("eigsh elapsed time: ", elapsed)
输出:
eigh elapsed time: 12.561862699999999
eigsh elapsed time: 2.3652462000000014
可见,对于 5000 维的对称矩阵,求解其最大特征值只需 2 秒