nupanick

NumLinAlg Problem 2-8

May 5th, 2015
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.03 KB | None | 0 0
  1. # Numeric linear Algebra, Project 2, Problem 8
  2. # Nicholas Lamicela
  3. import numpy as np
  4.  
  5. # Input
  6. A = np.matrix(((1, 2, 4),(1, 3, 3),(0, 0, 1)))
  7.  
  8. # Apparently, numpy returns U, the diagonal of s, and V transpose,
  9. # so that A = U * diag(s) * Vt.
  10. U, s, Vt = np.linalg.svd(A)
  11.  
  12. # Rank 1 and 2 approximation:
  13. # This line truncates s to r elements then pads the matrix to nxn with 0s.
  14. n = 3
  15. r = 1
  16. S1 = np.pad(np.diag(s[0:r]), (0,n-r), mode='constant')
  17. r = 2
  18. S2 = np.pad(np.diag(s[0:r]), (0,n-r), mode='constant')
  19.  
  20. # Output
  21. print("Original Matrix:")
  22. print(A)
  23.  
  24. print("Rank-1 Approximation:")
  25. print(U*S1*Vt)
  26.  
  27. print("Rank-2 Approximation:")
  28. print(U*S2*Vt)
  29.  
  30. ==================== Output ====================
  31. Original Matrix:
  32. [[1 2 4]
  33.  [1 3 3]
  34.  [0 0 1]]
  35. Rank-1 Approximation:
  36. [[ 1.01071168  2.51252097  3.64361002]
  37.  [ 0.95524374  2.37463362  3.44364841]
  38.  [ 0.17868048  0.44418052  0.64414212]]
  39. Rank-2 Approximation:
  40. [[ 0.9420343   2.013099    4.00704661]
  41.  [ 1.03999729  2.99096147  2.99513772]
  42.  [ 0.11405527 -0.02577403  0.98613485]]
Advertisement
Add Comment
Please, Sign In to add comment