Esempio n. 1
0
def toyExample():
    mat = scipy.io.loadmat('../data/toy_data.mat')
    data = mat['toy_data']

    # TODO: Train PCA
    pca = PCA(-1)
    pca.train(data)

    print("Variance of the data")
    # TODO 1.2: Compute data variance to the S vector computed by the PCA
    data_variance = np.var(data, axis=1)
    print(data_variance)
    print(np.power(pca.S, 2) / data.shape[1])
    # TODO 1.3: Compute data variance for the projected data (into 1D) to the S vector computed by the PCA
    Xout = pca.project(data, 1)
    print("Variance of the projected data")
    data_variance = np.var(Xout, axis=1)
    print(data_variance)
    print(np.power(pca.S[0], 2) / data.shape[1])

    plt.figure()
    plt.title('PCA plot')
    plt.subplot(1, 2, 1)  # Visualize given data and principal components
    # TODO 1.1: Plot original data (hint, use the plot_pca function
    pca.plot_pca(data)
    plt.subplot(1, 2, 2)
    # TODO 1.3: Plot data projected into 1 dimension
    pca.S[1] = 0
    pca.plot_pca(Xout)
    plt.show()
Esempio n. 2
0
def toyExample() -> None:
    ## Toy Data Set
    mat = scipy.io.loadmat('../data/toy_data.mat')
    data = mat['toy_data']

    data = importGallery()
    ## limit datafor testing purposes
    data = data[:, :144].T
    print(data.shape)

    ## Iris dataset. Just for testing purposes
    #iris = datasets.load_iris()
    #data = iris['data'].astype(np.float32)  # a 150x4 matrix with features
    #data = data.T
    # TODO: Train PCA
    nComponents = 25

    pca = PCA(nComponents)

    ## 1.1 Calculate PCA manuelly. SVD is following
    #pca.pca_manuel(data)
    ## 1.2 Calculate PCA via SVD
    mu, U, C, dataCenter = pca.train(data)

    ## 2. Transform RAW data using first n principal components
    alpha = pca.to_pca(dataCenter)

    ## 3. Backtransform alpha to Raw data
    Xout = pca.from_pca(alpha)

    print("Variance")
    # TODO 1.2: Compute data variance to the eigenvalue vector computed by the PCA

    print(f'Total Variance: {np.var(data)}')
    print(f'Eigenvalues: {C} \n')

    # TODO 1.3: Compute data variance for the projected data (into 1D) to the S vector computed by the PCA
    print(f'Total Variance Transform: {np.var(alpha)}')
    print(f'Mean Eigenvalues: {np.mean(C)}')

    ## Plot only if fewer than 2 components
    if nComponents == 2:
        plt.figure()
        plt.title('PCA plot')
        plt.subplot(1, 2, 1)  # Visualize given data and principal components
        # TODO 1.1: Plot original data (hint, use the plot_pca function
        pca.plot_pca(data)
        plt.subplot(1, 2, 2)
        # TODO 1.3: Plot data projected into 1 dimension
        pca.plot_pca(Xout)
        plt.show()

        ## Plot variances
    else:
        x = np.arange(1, len(C) + 1)
        plt.bar(x, C)
        plt.show()