主成分分析(PCA)——matlab程序及函數詳解

參考來源:

http://www.cnblogs.com/Hand-Head/articles/5156435.html

http://www.matlabsky.com/thread-11751-1-1.html

matlab幫助文檔


程序源碼下載鏈接http://download.csdn.net/detail/ckzhb/9903051

包含三個m文件:

drtool_pca:函數封裝。不包括盒形圖。
pca_test:matlab自帶的例子——pca()函數
princomp_test:matlab自帶的例子——princomp()函數


例子說明:

它使用了衡量美國329個城市生活質量的9個指標:氣候、住房、健康、犯罪率、交通、教育、藝術、娛樂和經濟。

對於各指標,越高表示越好,如高的犯罪指標表示低的犯罪率。

本文例子程序:

%% test for princomp(Principal Component Analysis)
% 20170706 BY Hubery_Zhang
clear;
clc;
%% load data set
load cities;
%% box plot forratings data
% To get a quickimpression of the ratings data, make a box plot
figure;
boxplot(ratings,'orientation','horizontal','labels',categories);
grid on;
%% pre-process
stdr =std(ratings);
sr =ratings./repmat(stdr,329,1);
%% use princomp
[coeff,score,latent,tsquare]= princomp(sr);
%% 如何提取主成分,達到降爲的目的
% 通過latent,可以知道提取前幾個主成分就可以了.
% 圖中的線表示的累積變量解釋程度.
% 通過看圖可以看出前七個主成分可以表示出原始數據的90%.
% 所以在90%的意義下只需提取前七個主成分即可,進而達到主成分提取的目的.
figure;
percent_explained= 100*latent/sum(latent); %cumsum(latent)./sum(latent)
pareto(percent_explained);
xlabel('PrincipalComponent');
ylabel('VarianceExplained (%)');
%% Visualizing theResults
% 橫座標和縱座標分別表示第一主成分和第二主成分
% 紅色的點代表329個觀察量,其座標就是那個score
% 藍色的向量的方向和長度表示了每個原始變量對新的主成分的貢獻,其座標就是那個coeff.
figure;
biplot(coeff(:,1:2),'scores',score(:,1:2),...
'varlabels',categories);
axis([-.26 1 -.51.51]);

程序詳解:

1、std()函數

(1)std(A)——函數求解的是最常見的標準差,此時除以的是N-1,按照列求標註差即輸出每一列的標準差。

(2)std(A,flag)——flag代表的是用哪一種標準差函數,如果取0,則代表除以N-1,如果是1代表的是除以N。

(3)std(A,flag,dim)——dim代表的是按照列求標準差還是按照行求標準差,std(A,1,1)代表的是按照列求標準差,std(A,1,2)代表的是按照行求標準差。

 

2、B = repmat(A,m,n) 複製和平鋪矩陣

將矩陣 A 複製 m×n 塊,即把 A 作爲 B 的元素,B 由 m×n 個 A 平鋪而成。B 的維數是 [size(A,1)*m, size(A,2)*n]


3、“./

矩陣中,點運算表示元素之間的運算。

 

小結:

%% pre-process

stdr = std(ratings);

sr = ratings./repmat(stdr,329,1);

使所有特徵的方差相等即單位化,保證所有屬性在同一個數量級上面。

note:

無論之前是否進行了去均值化(即每個數據減去特徵的均值),通過此操作(求特徵的標準差,然後每個數據除以標準差)均可以達到特徵歸一化。

當然,使用PCA必須進行歸一化,函數princomp自動對列進行去均值化

princomp centers X bysubtracting off column means, but does not rescale the columns of X. To perform principal components analysis with standardizedvariables, that is, based on correlations, use princomp(zscore(X)). To perform principal components analysis directly on acovariance or correlation matrix, use pcacov.

 

4、[COEFF,SCORE,latent,tsquare] = princomp(X)

princomp函數未來被廢棄,系統推薦使用pca函數。

X是n行P列的。n是數據樣本個數,p是特徵數。

(1)

COEFF is a p-by-p matrix, each columncontaining coefficients for one principal component. The columns are in orderof decreasing component variance.

主成分系數:即原始數據線性組合生成主成分數據中每一維數據前面的係數.COEFF的每一列代表一個新生成的主成分的係數.

(2)

 SCORE, the principal component scores; that is, the representationof X in the principal component space. Rows of SCORE correspond to observations, columns to components.n-by-p matrix

即原始數據在新生成的主成分空間裏的座標值.

(3)

 latent, a vector containing the eigenvalues of the covariancematrix of X.

即 latent = sort(eig(cov(sr)),'descend');

(4)

 tsquare, which contains Hotelling's T2 statistic foreach data point.

一種多元統計距離,記錄的是每一個觀察量到中心的距離。

The scores are the data formed by transformingthe original data into the space of the principal components. The values of thevector latent are thevariance of the columns of SCORE. Hotelling'sT2 is a measure of the multivariate distance of each observationfrom the center of the data set.

When n <= pSCORE(:,n:p) and latent(n:p) arenecessarily zero, and the columns of COEFF(:,n:p) definedirections that are orthogonal to X.

 

5、percent_explained = 100*latent/sum(latent);

或者%cumsum(latent)./sum(latent)

b=sum(a)函數:若a是向量,則求和即可;若a是矩陣,默認對列求和,可以改變dim參數進行按行求和。

b=cumsum(a)函數:當a是向量時,返回向量中各元素分別是該元素在a中位置之前所有元素之和如a=1 2 3,b=1 3 6。
當a是矩陣時,默認b中每一列都是對應列前面各行元素之和,當dim爲2時,b的各行爲對應行前面各列元素。

6、pareto(percent_explained);

Pareto charts display the values in thevector Y as bars drawn in descending order. Values in Y mustbe nonnegative and not include NaNs. Only the first 95% of the cumulativedistribution is displayed. also plots a line displaying the cumulative sum of Y.

 

7、biplot(coefs,'Name',Value)

biplot(coefs) creates a biplot of the coefficients in the matrix coefs. The biplot is 2-D if coefs has two columns or 3-D if it has three columns. coefs usually contains principal component coefficients createdwith pca, pcacov, or factor loadings estimated with factoran. The axes in the biplot represent the principal componentsor latent factors (columns of coefs), and the observed variables (rows of coefs) are represented as vectors.

比如在2-D圖中,橫座標和縱座標分別表示第一主成分和第二主成分;紅色的點代表329個觀察量,其座標就是那個score;藍色的向量的方向和長度表示了每個原始變量對新的主成分的貢獻,其座標就是那個coef.

 

'Name',Value)   

'Scores':

scores usually contains principal component scores created with pca or factor scores estimated with factoran. Each observation (row of scores) is represented as a pointin the biplot.

'VarLabels':

Labels each vector (variable) with the text inthe character array or cell array varlabels.





發佈了78 篇原創文章 · 獲贊 134 · 訪問量 38萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章