You are on page 1of 2

Machine Learning Example 2

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

ylabel('Height in meters')
xlabel('Age in years')

m = length(y); % store the size of data


x = [ ones(m,1),x]; %add a column to the x

%% linear regresion
theta = [0 0];
ss_old =theta;
ss_new = [inf inf];
alpha = 0.007;
while (abs(ss_new-ss_old)>0.0000000001)
ss_old = ss_new;
h_the = x*theta'; % prediction
theta(1)=theta(1)-alpha*(1/m).*sum(((h_the-y) .* x(:,1)));
theta(2)=theta(2)-alpha*(1/m).*sum(((h_the-y) .* x(:,2)));

ss_new=theta;
end
hold on
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')


theta
[1 3.5]*theta'
[1 7]*theta'

You might also like