#! /usr/bin/env python3 # def pca_eigen_glass ( ): #*****************************************************************************80 # ## pca_eigen_glass uses an eigenvalue approach for PCA of glass data. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 24 June 2019 # # Author: # # John Burkardt # import matplotlib.pyplot as plt import numpy as np import platform print ( '' ) print ( 'pca_eigen_glass:' ) print ( ' Python version: %s' % ( platform.python_version ( ) ) ) print ( ' Read data about chemical properties of glass samples.' ) print ( ' Create matrix A after subtracting averages.' ) print ( ' Get eigenvalue factorization of A'' A.' ) print ( ' Plot eigenvalues.' ) print ( ' Plot cumulative sum of eigenvalues.' ) data = np.loadtxt ( 'glass_data.txt' ) # # Copy all but first and last columns of data into A. # m, n = data.shape A = data[:,1:n-1] m, n = A.shape print ( '' ) print ( ' Array A has dimensions M = %d, N = %d' % ( m, n ) ) # # Subtract off the mean value of each column. # mu = np.mean ( A, axis = 0 ) for j in range ( 0, n ): A[:,j] = A[:,j] - mu[j] # # Compute the NxN symmetric positive semi-definite matrix A'A. # ATA = np.matmul ( A.T, A ) # # Get the N eigenvalues LAM and NxN eigenvector matrix V. # lam, v = np.linalg.eig ( ATA ) # # Display the eigenvalues. # x = np.arange ( 9 ) plt.plot ( x, lam, 'ko-', linewidth = 3 ) plt.grid ( True ) plt.xlabel ( '<-- Eigenvalue index -->' ) plt.ylabel ( '<-- Eigenvalue -->' ) plt.title ( 'Eigenvalues of A\'A ' ) filename = 'pca_eigen_glass_1.png' plt.savefig ( filename ) print ( '' ) print ( ' Graphics saved in "%s"' % ( filename ) ) plt.show ( ) plt.clf ( ) # # Display the relative sum of the first K eigenvalues. # x = np.arange ( 10 ) y = [ 0.0 ] y = np.append ( y, np.cumsum(lam) ) y = y / np.sum ( lam ) plt.plot ( x, y, 'ro-', linewidth = 3 ) plt.grid ( True ) plt.xlabel ( '<-- K: Number of components-->' ) plt.ylabel ( '<-- Amount of variance explained-->' ) plt.title ( 'Information proportion in first K components' ) filename = 'pca_eigen_glass_2.png' plt.savefig ( filename ) print ( '' ) print ( ' Graphics saved in "%s"' % ( filename ) ) plt.show ( ) plt.clf ( ) # # Terminate. # print ( '' ) print ( 'pca_eigen_glass:' ) print ( ' Normal end of execution.' ) return if ( __name__ == '__main__' ): pca_eigen_glass ( )