Skip to content
Snippets Groups Projects
ex3_1_4.py 979 B
Newer Older
  • Learn to ignore specific revisions
  • pheithar's avatar
    pheithar committed
    # (requires data structures from ex. 3.1.1)
    
    from ex3_1_1 import *
    from matplotlib.pyplot import figure, legend, plot, show, title, xlabel, ylabel
    from scipy.linalg import svd
    
    # Subtract mean value from data
    Y = X - np.ones((N, 1)) * X.mean(0)
    
    # PCA by computing SVD of Y
    U, S, Vh = svd(Y, full_matrices=False)
    # scipy.linalg.svd returns "Vh", which is the Hermitian (transpose)
    # of the vector V. So, for us to obtain the correct V, we transpose:
    V = Vh.T
    
    # Project the centered data onto principal component space
    Z = Y @ V
    
    # Indices of the principal components to be plotted
    i = 0
    j = 1
    
    # Plot PCA of the data
    f = figure()
    title("NanoNose data: PCA")
    # Z = array(Z)
    for c in range(C):
        # select indices belonging to class c:
        class_mask = y == c
        plot(Z[class_mask, i], Z[class_mask, j], "o", alpha=0.5)
    legend(classNames)
    xlabel("PC{0}".format(i + 1))
    ylabel("PC{0}".format(j + 1))
    
    # Output result to screen
    show()