Guest User

Untitled

a guest
Oct 19th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. import numpy as np
  2.  
  3. def shifting_redirection(M, eigenvalue, eigenvector):
  4. """
  5. Apply shifting redirection to the matrix to compute next eigenpair: M = M-lambda v
  6. """
  7. return(M-eigenvalue*np.matmul(eigenvector.T, eigenvector))
  8.  
  9. def power_method(M, epsilon = 0.0001, max_iter = 10000):
  10. """
  11. This function computes the principal component of M by using the power method with parameters:
  12. - epsilon: (float) Termination criterion to stop the power method when changes in the solution is marginale
  13. - max_iter: (int) Hard termination criterion
  14. Notes:
  15. - I added another condition based on the dot product of two consecutive solutions
  16. """
  17. # Initialization
  18. x = [None]*int(max_iter)
  19. x[0] = np.random.rand(M.shape[0])
  20. x[1] = np.matmul(M, x[0])
  21. count = 0
  22.  
  23. # Compute eigenvector
  24. while((np.linalg.norm(x[count] - x[count-1]) > epsilon) & (count < max_iter)):
  25. # Actual computations
  26. x[count+1] = np.matmul(M, x[count])/np.linalg.norm(np.matmul(M, x[count]))
  27. count += 1
  28.  
  29. # Compute eigenvalue
  30. eigenvalue = np.matmul(np.matmul(x[count].T, M), x[count])
  31.  
  32. return(x[count], eigenvalue)
  33.  
  34. def eigenpairs(M, epsilon = 0.00001, max_iter = 10e2, plot = True):
  35. # Initialization
  36. eigenvectors = [None]*M.shape[0]
  37. eigenvalues = [None]*M.shape[0]
  38.  
  39. for i in range(0, M.shape[0]):
  40. # Actual computing
  41. eigenvectors[i], eigenvalues[i] = power_method(M, epsilon, max_iter, iteration = i+1)
  42. M = shifting_redirection(M, eigenvalues[i], eigenvectors[i])
  43.  
  44. return(eigenvectors, eigenvalues)
Add Comment
Please, Sign In to add comment