Numpy 矩陣的特徵值分解
阿新 • • 發佈:2018-11-07
>>> a
array([[1, 2, 3],
[5, 8, 7],
[1, 1, 1]])
>>> e_vals,e_vecs = np.linalg.eig(a)
>>> e_vals
array([ 10.254515 , -0.76464793, 0.51013292])
>>> e_vecs
array([[-0.24970571, -0.89654947, 0.54032982],
[-0.95946634, 0.19306928, -0.73818337 ],
[-0.13065753, 0.39865186, 0.40389232]])
# 注意上面矩陣的列向量才是特徵向量,l2範數為 1
>>> [np.linalg.norm(e_vecs[:,i],ord=2) for i in [0,1,2]]
[0.99999999999999989, 0.99999999999999989, 1.0]
挑選出前 k 大的特徵值與特徵向量:
def topk(mat,k):
e_vals,e_vecs = np.linalg.eig(mat)
sorted_indices = np.argsort(e_vals)
return e_vals[sorted_indices[:-k-1:-1]],e_vecs[:,sorted_indices[:-k-1:-1]]
a = np.array([[1,2,3],[5,8,7],[1,1,1]])
vals,vecs = topk(a,2)
print(vals)
print(vecs)
[ 10.254515 0.51013292]
[[-0.24970571 0.54032982]
[-0.95946634 -0.73818337]
[-0.13065753 0.40389232]]