练习1:将2维数据通过PCA降为1维
过程:
- 原始数据归一化处理
- 计算协方差
- 计算新的特征向量
- 将原始数据映射到新的特征向量
- 反向恢复数据,对比验证
50*2数据:
- 原始数据归一化处理
% variable X in your environment load ('ex7data1.mat'); % Before running PCA, it is important to first normalize X [X_norm, mu, sigma] = featureNormalize(X);
- 通过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
- 将原始数据映射到新的特征向量
% Project the data onto K = 1 dimension K = 1; Z = projectData(X_norm, U, K);
- 反向恢复数据,对比验证
X_rec = recoverData(Z, U, K);
练习2:人脸特征提取
问题描述:原始数据为32*32的灰度人脸图片,通过PCA算法提取100个主特征
过程跟练习1是一样的,不同之处是开始是的数据预处理,这里原始数据是1024(32*32)列的灰度值,m*1024矩阵,m是图片张数;
原始数据:
原始图片:
提取100个特征后效果:
原始数据与PCA后恢复的数据对比: