主成分回归

function  [coeffs2] = PCR(x,y)
%*******************************************************
%   This programme is designed by Zihao Wang           %
%   Version 1.0 completed in 2009,4,2                  %
%   Copyright 2009,WZZY,Inc,Email:[email protected] %
%   Protected by Zihao Wang.                           %
%*******************************************************
%   PCR Summary of this function goes here
%   x 是自变量数据,y 是要回归的因变量
%   标准化输入数据矩阵
%   m 是主成分个数, sum 是累积贡献率
%   xmean 是输入数据均值,xstd 是输入数据方差
m = 1;
sum = 0;
xmean = mean(x);
xstd = std(x);
xstandar = zscore(x);
[pc,score,latent,tsqure] = princomp(xstandar);
for i = 1 : length(latent)
    sum = latent(i) + sum;
    if sum/length(latent) >= 0.85
        m = i;
        break;
    end
end
%   计算主成分回归
xregress = [ones(length(y),1) score(:,1:m)];
b = regress(y,xregress);
%   还原原变量
%   constantInOne 是还原原始常量的中间变量
%   coeffInOne 是要回归的变量系数的中间变量
%   constantInAll 是要回归的总体常数项
%   coeffInAll 是要回归的总体变量系数
constantInAll = 0;
coeffInAll = 0;
for i = 1 : m
%   i 为第i个特征向量   
constantInOne = 0;
coeffInOne = 0;
    for j = 1 : length(pc(:,1))
%   j 为第i个特征向量的第j个元素     
        constantInOne = constantInOne + pc(j,i)*xmean(j)/xstd(j);
        coeffInOne(j) = (pc(j,i)/xstd(j));
    end
constantInAll = constantInAll + constantInOne*b(i+1);
coeffInAll = coeffInAll + coeffInOne*b(i+1);
end
%   输出选取的特征值、特征向量、得分向量
latents = latent(1:m,1);
pcs = pc(:,1:m);
scores = score(:,1:m);
%   输出回归结果
constant = b(1)-constantInAll;
coeffs1 = coeffInAll';
coeffs2 = [constant;coeffs1];

主成分回归_第1张图片

x =

  149.3000    4.2000  108.1000
  161.2000    4.1000  114.8000
  171.5000    3.1000  123.2000
  175.5000    3.1000  126.9000
  180.8000    1.1000  132.1000
  190.7000    2.2000  137.7000
  202.1000    2.1000  146.0000
  212.4000    5.6000  154.1000
  226.1000    5.0000  162.3000
  231.9000    5.1000  164.3000
  239.0000    0.7000  167.6000

  y =

   15.9000
   16.4000
   19.0000
   19.1000
   18.8000
   20.4000
   22.7000
   26.5000
   28.1000
   27.6000
   26.3000

PCR(x3,y)

ans =

   -9.1301
    0.0728
    0.6092
    0.1063

得出结果为 y = -9.1301+0.0728*x1+0.6092*x2+0.1063*x3

你可能感兴趣的:(MATLAB)