You are a professional machine learning specialist and python programmer. The below code…
- User
You are a professional machine learning specialist and python programmer. The below code investigates the eigenface "Python import numpy as np from sklearn import preprocessing def featureNormalize(X): mu = np.mean(X,axis=0).reshape(1,-1) X = X - np.tile(mu, (X.shape[0], 1)) return X, mu
def pca(X, K=10): # Compute the NxN covariance matrix, where N is the no. of samples sigma = np.cov(X)
# The column vector eigenvectors[:,i] is the eigenvector with eigenvalues[i] # eigenvectors.shape: (N, N) eigenvalues, eigenvectors = np.linalg.eig(sigma) # Sort from largest to smallest according to eigenvalues index = np.argsort(-eigenvalues) eigenvectors = eigenvectors[:, index] # Obtain the PCA projection matrix V = np.transpose(X) @ eigenvectors # Normalize V to make unit norm V = preprocessing.normalize(V, norm='l2', axis=0) # Select the K PC V = V[:, 0:K] # Project the face images to eigenspace #Z = np.transpose(V) @ np.transpose(X) Z = X @ V return Z, np.transpose(V)import scipy.io data = scipy.io.loadmat('../data/faces.mat') nPC = 400 X, mu = featureNormalize(data['faces']) # X: (400,93600); mu: (1,93600) Z, eigenvectors = pca(X, K=nPC) # Z: (400, nPC); eigenvectors: (nPC,93600) Xhat = Z @ eigenvectors # Xhat: (400,93600) Xhat = Xhat + np.tile(mu, (Xhat.shape[0], 1)) print(Xhat.shape) %matplotlib inline import matplotlib.pyplot as plt
def show(data): fig, ax = plt.subplots(nrows=2, ncols=5, sharex=True, sharey=True, ) ax = ax.flatten() for i in range(10): img = data[i].reshape(360, 260) img = ax[i].imshow(img, interpolation='nearest', cmap='gray')
ax[0].set_xticks([]) ax[0].set_yticks([]) plt.tight_layout() plt.show()plt.figure(figsize = (2,2)) plt.imshow(mu[0].reshape(360, 260), cmap='gray') show(eigenvectors) " I want to add the code that plot the eigenvalues against the component index just like :"
Plot the eigenvalue against the component index
plt.plot(pca.explained_variance_[0:200]) plt.xlabel('Component index') plt.ylabel('Eigenvalue') " (But this code can't be directly run)
- Assistant
In the code you've provided,
pcais a custom function, not the PCA object fromsklearn.decomposition. The attribute you referred to belongs to the PCA object. Since we are not using 's PCA, but rather a custom function, we'll need to extract the eigenvalues from the function to plot them. - User
show full code.
- Assistant
Certainly! Combining all the necessary parts, here is the full code with the added capability to plot eigenvalues against the component index:
import numpy as np from sklearn import preprocessing import scipy.io import matplotlib.pyplot as plt def featureNormalize(X): mu = np.mean(X, axis=0).reshape(1, -1) X_norm = X - np.tile(mu, (X.shape[0], 1)) return X_norm, mu def pca(X, K=10): sigma = np.cov(X, rowvar=False) # Compute covariance matrix MxM where M is the no. of features eigenvalues, eigenvectors = np.linalg.eigh(sigma) # Use eigh, since sigma is symmetric index = np.argsort(-eigenvalues) sorted_eigenvalues = eigenvalues[index] sorted_eigenvectors = eigenvectors[:, index] U = sorted_eigenvectors[:, :K] # Obtain the K principal components Z = X @ U # Project the data onto the K principal components return Z, U, sorted_eigenvalues def show(data): fig, ax = plt.subplots(nrows=2, ncols=5, sharex=True, sharey=True) ax = ax.flatten() for i in range(10): img = data[i].reshape(360, 260) ax[i].imshow(img, interpolation='nearest', cmap='gray') ax[0].set_xticks([]) ax[0].set_yticks([]) plt.tight_layout() plt.show() # Load the data data = scipy.io.loadmat('../data/faces.mat') X = data['X'] # Assume 'X' is the key for face images within the loaded 'faces.mat' mu = np.mean(X, axis=0) # Feature normalization nPC = 400 X_norm, mean = featureNormalize(X) # PCA Z, eigenvectors, sorted_eigenvalues = pca(X_norm, K=nPC) # Dimensionality reduction and reconstruction Xhat = Z @ eigenvectors.T # Project back to original space Xhat = Xhat + mean # Add mean to approximate the original data # Show the average face plt.figure(figsize=(2, 2)) plt.imshow(mu.reshape(360, 260), cmap='gray') plt.title('Average face') # Show the eigenfaces show(eigenvectors.T) # Plot eigenvalues plt.figure(figsize=(8, 4)) plt.plot(sorted_eigenvalues[:200], 'o-') plt.xlabel('Component index') plt.ylabel('Eigenvalue') plt.title('Eigenvalues per Principal Component') plt.show()