Singular Value Decomposition Notes

Code examples from andrew.gibiansky.com tutorial


In [9]:
from scipy import ndimage, misc
import matplotlib.pyplot as plt

tiger = misc.imread('tiger.jpg', flatten=True)
plt.gray()
plt.imshow(tiger)
plt.show()

In [13]:
tiger.shape


Out[13]:
(1000L, 1600L)

In [34]:
from scipy import linalg
U, s, Vh = linalg.svd(tiger, full_matrices=0)
U.shape, Vh.shape, s.shape


Out[34]:
((1000L, 1000L), (1000L, 1600L), (1000L,))

In [17]:
import numpy as np
plt.plot(np.log10(s))
plt.show()

In [29]:
s_sum=sum(s)
s_cumsum=np.cumsum(s)
s_cumsum_norm=s_cumsum / s_sum
plt.title('Cumulative Percent of Total Sigmas')
plt.plot(s_cumsum_norm)
plt.ylim(0,1)
plt.show()

In [42]:
def approx_image(U, s, Vh, rank):
    """ 
    U: first argument from scipy.slinalg.svd output
    s: second argument from scipy.slinalg.svd output. The diagonal elements.
    Vh: third argument from scipy.slinalg.svd output
    """
    
    approx_sigma = s
    approx_sigma[rank:] = 0
    approx_S = np.diag(approx_sigma)
    print U.shape, approx_S.shape, Vh.shape
    approx_tiger = U.dot(approx_S).dot(Vh)
    
    return approx_tiger
    
approx_tiger_200 = approx_image(U, s, Vh, 200)


(1000L, 1000L) (1000L, 1000L) (1000L, 1600L)