Beispiel #1
0
def plot_in_2d(X, y=None, title=None, accuracy=None, legend_labels=None):

    cmap = plt.get_cmap('viridis')
    X_transformed = PCA().transform(X, 2)

    x1 = X_transformed[:, 0]
    x2 = X_transformed[:, 1]
    class_distr = []
    y = np.array(y).astype(int)

    colors = [cmap(i) for i in np.linspace(0, 1, len(np.unique(y)))]

    # Plot the different class distributions
    for i, l in enumerate(np.unique(y)):
        _x1 = x1[y == l]
        _x2 = x2[y == l]
        _y = y[y == l]
        class_distr.append(plt.scatter(_x1, _x2, color=colors[i]))

    # Plot legend
    if not legend_labels is None:
        plt.legend(class_distr, legend_labels, loc=1)

    # Plot title
    if title:
        if accuracy:
            perc = 100 * accuracy
            plt.suptitle(title)
            plt.title("Accuracy: %.1f%%" % perc, fontsize=10)
        else:
            plt.title(title)

    # Axis labels
    plt.xlabel('Principal Component 1')
    plt.ylabel('Principal Component 2')

    plt.show()
Beispiel #2
0
@author: Eric
"""

from os import chdir
chdir("..")

import numpy as np
import matplotlib.pyplot as plt
import scipy.io
from pca.pca import PCA
import SAILnet

imfile = "patches.mat"
imname = "patches"

nullpca = PCA()
normalpca = PCA()
whiteningpca = PCA(whiten=True)

patches = scipy.io.loadmat(imfile)[imname]
origshape = patches.shape
veclength = origshape[0] * origshape[1]
nimages = origshape[2]

# unroll images
patches = patches.reshape((veclength, nimages))

scipy.io.savemat("unrolledpatches.mat", {"patches": patches})

# the PCA object wants each row to be a data point by default
patches = np.transpose(patches)
import numpy as np
from pca.pca import PCA


def sd_normalize(mat: np.ndarray):
    sd = np.sqrt(np.var(mat, 0))
    return mat / sd


def eigen_normalize(mat, eigen, ep):
    return mat / np.array(np.sqrt(eigen[0:2] + ep))


if __name__ == '__main__':
    data = np.array([[5, 0, 1], [0, 1, 1], [1, 0, 1], [1, 1, 1], [0, 0, 1],
                     [1, 2, 1], [2, 3, 4], [0, 0, 1]])

    pca = PCA(data)
    out, eigen, vector = pca.fit()
    pca_whitening_mat = sd_normalize(out)
    pca_whitening_mat2 = eigen_normalize(out, eigen, 0.01)
    print(pca_whitening_mat)
    a = 1