[Exercise 1] Linear Regression

数据描述

这次练习是多元线性回归中最简单的二元线性回归,参考exericse1给出的题目,50个数据样本点,其中x为这50个小朋友到的年龄,年龄为2岁到8岁,年龄小数形式呈现。Y为这50个小朋友对应的身高,小数形式表示的。

线性回归

回想一下线性回归模型 h θ ( x ) = θ T x = ∑ i = 1 n θ i x i
梯度更新规则: θ j := θ j − α 1 m ∑ i = 1 m ( h θ ( x ( i ) ) − y ( i ) ) x j ( i )
J ( θ ) 公式: J ( θ ) = 1 2 m ∑ i = 1 m ( h θ ( x ( i ) ) − y ( i ) ) 2
实验内容:
1. 实现梯度下降 α = 0.07
2. 迭代计算 θ 0 θ 1
3. 预测x = 3 .5 和x=7

实验结果和程序[matlab]

求解问题可以通过2个方法求解normal equation和gradient descend.

x = load('ex2x.dat');
y = load('ex2y.dat');

figure
plot(x,y,'o')
xlabel('Age in years')
ylabel('Height in meters')

m = length(y);  %store the number of training examples
x = [ones(m,1), x]; %Add a colum of ones to x
w = inv(x'*x)*x'*y
hold on
% w = 0.7502 0.0639
plot(x(:,2), 0.0639*x(:,2) + 0.7502)

这里写图片描述

  • 采用gradient descend过程求解:
%exercise 2 linearRegression
%gradient descent update 
% x refers to a boy's age
% y is a boy's height in meters

clear all; close all,clc
x = load('ex2x.dat'); y = load('ex2y.dat');
m = length(y);

% plot the traning
figure;
plot(x,y,'o')
ylabel('Height in meters')
xlabel('Age in years')

% gradient descent 
x = [ones(m,1), x];
theta = zeros(size(x(1,:)))';
MAX_ITR = 1500;
alpha = 0.07;

for num_iterations = 1:MAX_ITR
    grad = (1/m).*x'*(x*theta - y);
    theta = theta - alpha.*grad;    
end
%print theta to screeen
theta

%plot the linear fit
hold on;
plot(x(:,2), x*theta, '-')
legend('Traning data', 'Linear regression')
hold off

exact_theta = (x'*x)\x'*y
%predict values for age 3.5 and 7
predict1 = [1, 3.5]*theta
predict2 = [1, 7]*theta

%calculate J matrx
theta0_vals = linspace(-3,3,100);
theta1_vals = linspace(-1,1,100);
J_vals = zeros(length(theta0_vals), length(theta1_vals));

for i = 1:length(theta0_vals)
    for j = 1:length(theta1_vals)
    t = [theta0_vals(i); theta1_vals(j)];
    J_vals(i,j) = (0.5/m).*(x*t - y)'*(x*t - y);
    end

end

J_vals = J_vals';
figure;
surf(theta0_vals, theta1_vals, J_vals)
xlabel('\theta_0');
ylabel('\theta_1');

figure;
contour(theta0_vals, theta1_vals, J_vals, logspace(-2,2,15))
xlabel('\theta_0');
ylabel('\theta_1');

这里写图片描述
这里写图片描述

这里写图片描述

参考资料:

  1. http://blog.csdn.net/xiazdong/article/details/7950087
  2. http://openclassroom.stanford.edu/MainFolder/DocumentPage.php?course=DeepLearning&doc=exercises/ex2/ex2.html
  3. http://www.cnblogs.com/tornadomeet/archive/2013/03/15/2961660.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值