+3 votes
in Programming Languages by (73.8k points)
Which Python function should I use to calculate the singular value decomposition of a matrix?

1 Answer

+1 vote
by (348k points)
selected by
 
Best answer

scipy's svd() function can be used to calculate the singular value decomposition of a matrix.

The SVD theorem states:

Anxp= UnxnSnxpVTpxp  Where UTU = Inxn and VTV = Ipxp  (i.e. U and V are orthogonal)
The svd() function will return unitary matrices "U" and "VT" and an array of singular values "S".
Here is an example:
>>> import numpy as np
>>> from scipy import linalg
>>> a=np.array([[2,4],[1,3],[5,6],[3,7]])
>>> a
array([[2, 4],
       [1, 3],
       [5, 6],
       [3, 7]])
>>> U, s, Vh = linalg.svd(a)
>>> U
array([[-0.36948216, -0.15785407, -0.75762858, -0.51435781],
       [-0.2563533 , -0.36583405,  0.63150404, -0.63375948],
       [-0.63725653,  0.75299288,  0.16342737, -0.01404726],
       [-0.62583546, -0.52368813,  0.02220543,  0.57757046]])
>>> s
array([12.08072986,  1.74813213])
>>> Vh
array([[-0.50155138, -0.86512786],
       [ 0.86512786, -0.50155138]])
 

...