Which Python function should I use to calculate the singular value decomposition of a matrix?

+1 vote

Best answer

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

The SVD theorem states:

A_{nxp}= U_{nxn}S_{nxp}V^{T}_{pxp}Where U^{T}U = I_{nxn }and V^{T}V = I_{pxp}(i.e. U and V are orthogonal)

The svd() function will return unitary matrices "U" and "V^{T}" 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]])