Determine the eigenvectors needed to capture 96% of the variance in an image

import numpy as np from PIL import Image import matplotlib.pyplot as plt from sklearn.decomposition import TruncatedSVD from scipy.linalg import svd im = Image.open('bird.jpg').convert('L') imnp = np.array(im) restore_percentage = 96 components = 200 last_component = 0 trsvd = TruncatedSVD(n_components=components) trsvd.fit_transform(imnp) for k in range(components): if(sum(trsvd.explained_variance_ratio_[:k]) > restore_percentage/100): print('{0} eigenvectors are needed to restore {1}% of the variance in the image.'.format(k+1, restore_percentage)) last_component = k break # 80 eigenvectors are needed to restore 96% of the variance in the image. left_eigvecs, eigvals, right_eigvecs = svd(imnp) first, last = eigvals[0], eigvals[last_component] print("The first eigenvalue is {0} times bigger than the {1}th eigenvalue.".format(round(first/last, 2), last_component+1)) # The first eigenvalue is 176.78 times bigger than the 80th eigenvalue.