The data given in the topic is the height of a group of 2-8-year-old boys. X is age and Y is height. Number of samples m=50.
Use gradient descent to do linear regression.
Step1: Data preparation.
Load data:
>> x=load (' Ex2x.dat ');
>> y=load (' Ex2y.dat ');
Visualize data:
Figure% Open a new figure windowplot (x, y, ' o '); Ylabel (' Height in Meters ') xlabel (' Age in Years ')
The effect is as follows:
We set the model to:
hθ (x) =θ0 +θ1x
Therefore, it is also necessary to unify the coordinates of the dataset X by 1, which is equivalent to X0=1
m = Length (y); % store the number of training examplesx = [Ones (M, 1), X]; % Add a column of ones to X
After adding this column, it is important to note that now the age variable has been moved to the second column.
Step2: Linear regression
Let's recall our computational model:
The rules for batch gradient descent (note that not the online gradient drop) are:
Title Requirements:
1, use the learning rate of the step 0.07 to perform gradient descent. The weight vector θ={θ0,θ1} is initialized to 0. Calculates the value of the weight vector θ after an iteration.
First initialize the weight vector theta
>> (Theta=zeros)
Theta = 0 0
Calculate the weight vector at the time of the iteration:
Delta= (X*theta ')-y;
Sum=delta ' *x;
delta_theta=sum*0.07/m;
Theta1=theta-delta_theta;
The result of the obtained theta1 is:
Theta1 = 0.0745 0.3800
2, iterative gradient descent, until convergence to a point.
Test the code (output a theta line every 100 steps until the end of the iteration):
function [Result] = Gradientdescent (x,y,alpha,accuracy)%gradientdescent Summary of this function goes here% Detail Ed explanation goes Hereorgx=x;plot (orgx, y, ' o '), Ylabel (' Height in Meters ') xlabel (' Age in Years ') m=length (y); X=[ones (M , 1), X];theta = zeros, hold on;times = 0;while (1) times = times + 1; Delta= (X*theta ')-y; Sum=delta ' *x; delta_theta=sum*alpha/m; Theta1=theta-delta_theta; if (All (ABS (Theta1 (:)-theta (:)) < accuracy) result = theta; break; End theta = theta1; if (mod (times,100) = = 0) plot (x (:, 2), X*theta ', '-', ' Color ', [(mod (times/100,256))/256 128/256 2/256]);% remember That X was now a matrix with 2 columns % and the second column contains the time info legend (' Training data ', ' Li Near regression '); EndEnd End
The effect is as follows:
As you can see, the line that Theta determines is slowly approaching the data set.
Clean version of the code (output only the final theta results, do not output intermediate steps):
function [Result] = Gradientdescent (x,y,alpha,accuracy)%gradientdescent Summary of this function goes here% Detail Ed explanation goes Hereorgx=x;plot (orgx, y, ' o '), Ylabel (' Height in Meters ') xlabel (' Age in Years ') m=length (y); X=[ones (M , 1), X];theta = Zeros, hold On;while (1) delta= (X*theta ')-y; Sum=delta ' *x; delta_theta=sum*alpha/m; Theta1=theta-delta_theta; if (All (ABS (Theta1 (:)-theta (:)) < accuracy) result = theta; Plot (X (:, 2), X*theta ', '-', ' color ', [200/256 128/256 2/256]); % remember that x are now a matrix with 2 columns % and the second column contains the time info legend (' Training Data ', ' Linear regression '); break; End theta = Theta1;end End
Results:
Execute code
Result=gradientdescent (x,y,0.07,0.00000001)
Where 0.07 is the step (that is, the learning rate), 0.00000001 is the similarity of two floating-point matrices (that is, in this degree, as the two floating-point matrices are equal)
The theta value at the time of convergence is:
theta = 0.7502 0.0639
3, now, we have trained the weight vector theta value, we can use it to predict the other data.
Predict the height for a, boys of age 3.5 and age 7
The code is as follows:
>> Boys=[3.5;7];
>> Boys=[ones (2,1), boys];
>> Heights=boys*theta ';
Execution Result:
Heights =
0.9737
1.1973
4. Understanding J (θ)
J (θ) is the cost function associated with a weight vector. The selection of weight vectors will affect the cost size. We want the cost to be as small as possible, which is the equivalent of looking for the minimum value. A simple way to find the minimum value of a function is to take a derivative of the function (assuming the function is a guide) and then pick the point with the derivative at 0 o'clock, which is the minimum (or possibly minimum) value of the function. The gradient descent is the method of approximating the point of the derivative to 0 after the deviation guide of J (θ).
Because the θ vector we use in this exercise has only two dimensions, you can visualize it using the plot function of Matlab. In general applications, the θ vector has a high dimension and can form a super plane, so it is not easy to visualize with plot methods.
Code:
function [] = Showjtheta (x, y)%show Summary of this function goes here% detailed explanation goes herej_vals = zeros ( (in); % initialize jvals to 100x100 matrix of 0 ' stheta0_vals = Linspace ( -3, 3,); theta1_vals = Linspace ( -1, 1, +); for i = 1 : Length (Theta0_vals) for j = 1:length (theta1_vals) t = [Theta0_vals (i); Theta1_vals (j)]; J_vals (I,J) = SUM (sum ((x*t-y). ^2,2), 1)/(2*length (y)); endend% Plot the surface plot% Because of the The-meshgrids work in the surf command, we need to% transpose j_vals before Calling surf, or else the axes would be flippedj_vals = J_vals ' Figure;surf (theta0_vals, Theta1_vals, j_vals); axis ([-3, 3, -1, 1,0,40]); Xlabel (' \theta_0 '); Ylabel (' \theta_1 ') end
Perform:
X=load (' Ex2x.dat ');
Y=load (' Ex2y.dat ');
X=[ones (Length (y), 1), X];
Showjtheta (x, y);
Results
Add contour lines to the drawing statement
Figure
% Plot The cost function with the contours spaced logarithmically
% between 0.01 and 100
Contour (theta0_vals, Theta1_vals, J_vals, Logspace (-2, 2, 15));
Xlabel (' \theta_0 '); Ylabel (' \theta_1 ');
Effect
Transferred from: http://www.cnblogs.com/elaron/archive/2013/05/21/3090724.html
Exercise:linear Regression Stanford Assignment II (EXT)