多变量线性回归 matlab

%multivariate_linear_regression

data=load('data.txt');
x=data(:,1:2);
y=data(:,3);
m=length(x(:,1));
x=[ones(m,1),x];
sigma=std(x);
mu=mean(x);
x(:,2)=(x(:,2)-mu(2))./sigma(2);
x(:,3)=(x(:,3)-mu(3))./sigma(3);
theta=zeros(size(x(1,:)))';
alpha=0.18;
j=zeros(50,1);%迭代次数
for num=1:50
    j(num)=(x*theta-y)'*(x*theta-y)/(m*2);
    theta=theta-((x*theta-y)'*x)'*alpha/m/2;
end
%代价函数绘制
subplot(2,1,1)
plot(0:49,j(1:50),'g-')
xlabel('number of interations')
ylabel('cost j')
%预测
subplot(2,1,2)
realx=[1,4.1,3.04];
tempx=realx;
realx(2)=(realx(2)-mu(2))./sigma(2);
realx(3)=(realx(3)-mu(3))./sigma(3);
pre_y=realx*theta
stem3(data(:,1),data(:,2),data(:,3),'fill','b-.*');
hold on
stem3(tempx(2),tempx(3),pre_y,'filled','r-')

  运行结果:

 

posted @ 2018-04-25 21:55  夜游星  阅读(1505)  评论(1编辑  收藏  举报