import numpy as np
import seaborn as sns
- A symmetric matrix has real eigen values
# create a symmetric matrix
def get_random_symmetrix_matrix(n=3):
= np.random.randint(-10,10, (3,3))
a return (a + a.transpose())/2
= get_random_symmetrix_matrix()
s s
array([[-5. , -2.5, -2. ],
[-2.5, -9. , 4.5],
[-2. , 4.5, 3. ]])
= np.linalg.eig(s)
w, v w, v
(array([ 5.22047873, -5.17812095, -11.04235778]),
array([[-0.2587962 , 0.91904091, -0.29730177],
[ 0.33248317, -0.20422367, -0.92073212],
[ 0.90690654, 0.3371298 , 0.25271333]]))
# check the magnitude of the first eigen vector.
print(np.dot(v[0], v[0]))
# check the dot product.
print(np.dot(v[0], v[1]))
# as dimension is one and dot product is close to zero, they are orthonormal
1.0
-1.520268617663237e-16
Power method to find the dominant eigan value
We initialize a random vector x, usually 1s. We multiply ax and divide the output to make the
= 0.001
error = 3
n
= get_random_symmetrix_matrix(n)
s = np.array([1.0] * n)
x
def get_dominant_eig_value(a):
= []
eigs = None
eig_old = np.array([1.0] * a.shape[1])
x while True:
= np.matmul(a,x)
x = np.max(np.abs(x))
eig = x/eig
x if eig_old and abs(eig - eig_old) < error:
break
= eig
eig_old
eigs.append(eig)return (eig, eigs)
= get_dominant_eig_value(s)
dom_eig, eigs print(f'dominant eig is {dom_eig} in {len(eigs)} iterations with margin {error}')
=range(len(eigs)), y=eigs) sns.scatterplot(x
dominant eig is 11.085887005510221 in 6 iterations with margin 0.001
abs( np.
Input In [6] np.abs( ^ SyntaxError: unexpected EOF while parsing