PCA降维展示数据
程序员文章站
2022-07-16 18:05:37
...
%--------------------------------------------------------------------------
% pca 降维展示数据 方法1: 直接使用matlab pca函数,最大的特征向量在第一列
% 展示降1维的数据时候要用testSet_centered作为输入
%--------------------------------------------------------------------------
load testSet.txt;
plot(testSet(:,1),testSet(:,2),'r^');
testSet_mean=mean(testSet,1);
testSet_centered=testSet-testSet_mean;
V=pca(testSet);
PC1=V(:,1);
reduced=testSet_centered*PC1;
reconstruct=reduced*transpose(PC1)+testSet_mean;
plot(testSet(:,1),testSet(:,2),'r^');
hold on;
plot(reconstruct(:,1),reconstruct(:,2),'bo');
hold off;
方法1效果图:
%--------------------------------------------------------------------------
% pca 降维展示数据 方法2: 先计算协方差矩阵,然后求特征值/特征向量,最大的特征向量在最后一列
%--------------------------------------------------------------------------
load testSet.txt;
plot(testSet(:,1),testSet(:,2),'r^');
testSet_mean=mean(testSet,1);
testSet_centered=testSet-testSet_mean;
testSet_cov=cov(testSet_centered);
[V,D]=eig(testSet_cov);
PC1=V(:,end);
reduced=testSet_centered*PC1;
reconstruct=reduced*transpose(PC1)+testSet_mean;
plot(testSet(:,1),testSet(:,2),'r^');
hold on;
plot(reconstruct(:,1),reconstruct(:,2),'bo');
hold off;
方法2效果图:
%--------------------------------------------------------------------------
% pca 降维后恢复回原始数据
%--------------------------------------------------------------------------
load testSet.txt;
plot(testSet(:,1),testSet(:,2),'r^');
testSet_mean=mean(testSet,1);
testSet_centered=testSet-testSet_mean;
testSet_cov=cov(testSet_centered);
[V,D]=eig(testSet_cov);
reduced=testSet_centered*V;
reconstruct=reduced*transpose(V)+testSet_mean;
plot(testSet(:,1),testSet(:,2),'r^');
hold on;
plot(reconstruct(:,1),reconstruct(:,2),'bo');
hold off;
恢复回原始数据:
testSet.txt文件请在此链接处下载:
http://muchong.com/bbs/attachment.php?tid=6881223&aid=22076
\解压目录\machinelearninginaction\Ch13\testSet.txt
上一篇: 主成分分析(PCA)