1. 程式人生 > >AI-020: 練習:PCA

AI-020: 練習:PCA

練習1:將2維資料通過PCA降為1維

過程:

  1. 原始資料歸一化處理
  2. 計算協方差
  3. 計算新的特徵向量
  4. 將原始資料對映到新的特徵向量
  5. 反向恢復資料,對比驗證

50*2資料:

  1. 原始資料歸一化處理
    %  variable X in your environment
    load ('ex7data1.mat');
    
    %  Before running PCA, it is important to first normalize X
    [X_norm, mu, sigma] = featureNormalize(X);
  2. 通過PCA函式計算新的特徵向量
    %  Run PCA
    [U, S] = pca(X_norm);
    function [U, S] = pca(X)
    %PCA Run principal component analysis on the dataset X
    %   [U, S, X] = pca(X) computes eigenvectors of the covariance matrix of X
    %   Returns the eigenvectors U, the eigenvalues (on diagonal) in S
    %
    
    % Useful values
    [m, n] = size(X);
    
    % You need to return the following variables correctly.
    U = zeros(n);
    S = zeros(n);
    
    cm = (1/m)*transpose(X)*X;
    [U, S, V] = svd(cm);
    
    end

  3. 將原始資料對映到新的特徵向量
    %  Project the data onto K = 1 dimension
    K = 1;
    Z = projectData(X_norm, U, K);
  4. 反向恢復資料,對比驗證
    X_rec  = recoverData(Z, U, K);

練習2:人臉特徵提取

問題描述:原始資料為32*32的灰度人臉圖片,通過PCA演算法提取100個主特徵

過程跟練習1是一樣的,不同之處是開始是的資料預處理,這裡原始資料是1024(32*32)列的灰度值,m*1024矩陣,m是圖片張數;

原始資料:

原始圖片:

提取100個特徵後效果:

原始資料與PCA後恢復的資料對比: