MATLAB内置PCA举例

加载数据

加载样本数据。

load cities
categories

categories =
climate
housing
health
crime
transportation
education
arts
recreation
economics
总之,cities数据集包含有三种变量

  • categories, a string matrix containing the names of the indices
  • names, a string matrix containing the 329 city names ratings, the
  • data matrix with 329 rows and 9 columns

画出数据

画出盒图来查看ratings数据的分布。

figure()
boxplot(ratings,'orientation','horizontal','labels',categories)

由图可知,ratings中arts和housing比crime和climate具有更强的变化性。
检查每对变量之间的相关性。

C = corr(ratings,ratings);

计算主成分

若变量所使用的单位不同,或不同变量方差相差很大,需要对数据进行缩放或进行加权处理。
Perform the principal component analysis by using the inverse variances of the ratings as weights.

w = 1./var(ratings);
[wcoeff,score,latent,tsquared,explained] = pca(ratings,...
'VariableWeights',w);

Or equivalently:

[wcoeff,score,latent,tsquared,explained] = pca(ratings,...
'VariableWeights','variance');

The following sections explain the five outputs of pca.

主成分系数

第一个输出, wcoeff, 包含着主成分的系数。前三个主成分对应的系数向量为:

c3 = wcoeff(:,1:3)

c3 =
1.0e+03 *
0.0249 -0.0263 -0.0834
0.8504 -0.5978 -0.4965
0.4616 0.3004 -0.0073
0.1005 -0.1269 0.0661
0.5096 0.2606 0.2124
0.0883 0.1551 0.0737
2.1496 0.9043 -0.1229
0.2649 -0.3106 -0.0411
0.1469 -0.5111 0.6586
因为这些系数已经被加权,因此系数矩阵不是正交的。

对系数进行变换

对系数变换之后,系数将变为正交的。

coefforth = inv(diag(std(ratings)))*wcoeff;

检查系数的正交性

现在,变换之后的系数是正交的。

I = c3'*c3

成分得分

第二个输出, score, 包含着主成分定义的新坐标系统中原数据的坐标。得分矩阵与输入数据矩阵是同维的。可以通过使用正交系数和归一化ratings得到成分得分,如下所示:

cscores = zscore(ratings)*coefforth;

所得到的cscores 与 score是相同的矩阵。

画出成分得分图

画出score前两列的图。

figure()
plot(score(:,1),score(:,2),'+')
xlabel('1st Principal Component')
ylabel('2nd Principal Component')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值