principal component analysis(PCA) 主成分分析法是一种数学变换的方法, 它把给定的一组相关变量通过线性变换转成另一组不相关的变量,这些新的变量按照方差依次递减的顺序排列。在数学变换中保持变量的总方差不变,使第一变量具有最大的方差,称为第一主成分,第二变量的方差次大,并且和第一变量不相关,称为第二主成分。依次类推,I个变量就有I个主成分。
基本思想:
PCA的基本原理就是将一个矩阵中的样本数据投影到一个新的空间中去。对于一个矩阵来说,将其对角化即产生特征根及特征向量的过程,也是将其在标准正交基上投影的过程,而特征值对应的即为该特征向量方向上的投影长度,因此该方向上携带的原有数据的信息越多。
主要目的:
是希望用较少的变量去解释原来资料中的大部分变量,将我们手中许多相关性很高的变量转化成彼此相互独立或不相关的变量。通常是选出比原始变量个数少,能解释大部分资料中变量的几个新变量,即所谓主成分,并用以解释资料的综合性指标。由此可见,主成分分析实际上是一种降维方法。
分析步骤:
-
将原始数据按行排列组成矩阵X
-
对X进行数据标准化,使其均值变为零
-
求X的协方差矩阵C
-
将特征向量按特征值由大到小排列,取前k个按行组成矩阵P
-
通过计算Y = PX,得到降维后数据Y
-
用下式计算每个特征根的贡献率Vi;Vi=xi/(x1+x2+........)
根据特征根及其特征向量解释主成分物理意义。
matlab代码:
clear,clc;
cx = [1.4000 1.5500
3.0000 3.2000
0.6000 0.7000
2.2000 2.3000
1.8000 2.1000
2.0000 1.6000
1.0000 1.1000
2.5000 2.4000
1.5000 1.6000
1.2000 0.8000
2.1000 2.5000];
[m,n] = size(cx);
figure(1); % 原图
plot(cx(:,1), cx(:,2), 'k+');
hold on
plot(([0,0]), ([-1,4]), 'k-'); % x axis
hold on
plot(([-1,4]), ([0,0]), 'k-'); % y axis
axis([-1, 4, -1, 4]);
xlabel('Feature_1');
ylabel('Feature_2');
title('original Data');
%% convariance Matrix
covx = cov(cx);
%% using Matrix definition 1
% meanX_1 = mean(cx); % 列向量均值
% cx1 = cx(:,1) - meanX_1(1); %
% cx2 = cx(:,2) - meanX_1(2); %
% Mcx = [cx1 cx2];
% covx_1 = (transpose(Mcx) * (Mcx))/(m-1);
%% using Matrix definition 2
% meanX_2 = mean(cx);
% cx1_2 = cx(:, 1);
% cx2_2 = cx(:, 2);
% covx_2 = ((transpose(cx) * (cx)) / (m-1)) - ((transpose(meanX_2) * meanX_2) * (m/(m-1)));
%% compute the Eigenvalues and Eigenvector
[W,L] = eig(covx);
%% Eigenvector Graph
figure(2);
plot(cx(:,1), cx(:,2), 'k+');
hold on
plot(([0, W(1,1)*4]), ([0,W(1,2)*4]), 'k-');
hold on
plot(([0, W(2,1)*4]), ([0,W(2,2)*4]), 'k-');
axis([-4,4,-4,4]);
xlabel('Feature1');
ylabel('Feature2');
title('Eigenvector');
%% Transfrom data
cy = cx * W;
%% Graph the Transfrom Data
figure(3);
plot(cy(:,1), cy(:,2), 'k+');
hold on
plot(([0,0]), ([-1,5]), 'k-');
hold on
plot(([-1,5]), ([0,0]), 'k-');
axis([-1,5,-1,5]);
xlabel('Feature1');
ylabel('Feature2');
title('Transform Data');
%% Classification Example
meanY = mean(cy);
figure(4);
plot(([-1,5]), ([meanY(2),meanY(2)]), 'k:');
hold on
plot(([0,0]), ([-1,5]), 'k-');
hold on
plot(([-1,5]), ([0,0]), 'k-');
hold on
plot((cy(:,1)), (cy(:,2)), 'k+');
axis([-1,5,-1,5]);
xlabel('Feature1');
ylabel('Feature2');
title('Classification Example');
legend('Mean');
%% Data Compression Example
cy(:,1) = zeros;
xr = transpose(transpose(W) * transpose(cy));
figure(5);
plot(xr(:,1), xr(:,2), 'k+');
hold on
plot(([0,0]), ([-1,4]), 'k-');
hold on
plot(([-1,4]), ([0,0]), 'k-');
axis([-1,4,-1,4]);
xlabel('Feature1');
ylabel('Feature2');
title('Data Compressiom Example');