Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Numeric linear Algebra, Project 2, Problem 8
- # Nicholas Lamicela
- import numpy as np
- # Input
- A = np.matrix(((1, 2, 4),(1, 3, 3),(0, 0, 1)))
- # Apparently, numpy returns U, the diagonal of s, and V transpose,
- # so that A = U * diag(s) * Vt.
- U, s, Vt = np.linalg.svd(A)
- # Rank 1 and 2 approximation:
- # This line truncates s to r elements then pads the matrix to nxn with 0s.
- n = 3
- r = 1
- S1 = np.pad(np.diag(s[0:r]), (0,n-r), mode='constant')
- r = 2
- S2 = np.pad(np.diag(s[0:r]), (0,n-r), mode='constant')
- # Output
- print("Original Matrix:")
- print(A)
- print("Rank-1 Approximation:")
- print(U*S1*Vt)
- print("Rank-2 Approximation:")
- print(U*S2*Vt)
- ==================== Output ====================
- Original Matrix:
- [[1 2 4]
- [1 3 3]
- [0 0 1]]
- Rank-1 Approximation:
- [[ 1.01071168 2.51252097 3.64361002]
- [ 0.95524374 2.37463362 3.44364841]
- [ 0.17868048 0.44418052 0.64414212]]
- Rank-2 Approximation:
- [[ 0.9420343 2.013099 4.00704661]
- [ 1.03999729 2.99096147 2.99513772]
- [ 0.11405527 -0.02577403 0.98613485]]
Advertisement
Add Comment
Please, Sign In to add comment