导航

deep learning 练习1 线性回归练习

Posted on 2016-05-06 20:33  Joekk  阅读(233)  评论(0编辑  收藏  举报

                                           线性回归练习

跟着Andrew Ng做做练习:http://openclassroom.stanford.edu/MainFolder/DocumentPage.php?course=DeepLearning&doc=exercises/ex2/ex2.html

这一小节做线性回归的小练习,数据摘自上面的网站,其中X是小男孩身高,Y是小男孩年龄,数据集包括50组训练数据。

1,预处理

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

加载数据;

然后生成X的单位向量

m = length(y); % store the number of training examples
x = [ones(m, 1), x]; % Add a column of ones to x

2,线性回归

线性回归模型为

                       

参数批量更新规则为

其中学习速率设置为α=0.07,参数初始化为0;

然后开始迭代,直到theta收敛。

由于这个东西十分简单,现直接贴代码如下

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

figure % open a new figure window
plot(x, y, 'o');%离散点
ylabel('Height in meters')
xlabel('Age in years')

m = length(y); % store the number of training examples
x = [ones(m, 1)  x]; % Add a column of ones to x----这个是由于f(x)=w'*X+b可以转化为f(x)=[X,1]*[w';b]
a=0.07;
theta = zeros(size(x(1,:)))'; %参数包括两个,k,,,,b

for i=1:1500
    theta=theta-a./m.*x'*(x*theta-y);%批量梯度下降
end
hold on % Plot new data without clearing old plot
plot(x(:,2), x*theta, '-') % remember that x is now a matrix with 2 columns
                           % and the second column contains the time info
legend('Training data', 'Linear regression')