linear regression with one variable Gradient descent - machine-learning

I want to ask how this equation
can be written at octave by this way
predictions = X * theta;
delta = (1/m) * X' * (predictions - y);
theta = theta - alpha * delta;
I dont understand from where transpose come and how this equation converted to ve by this way?

The scalar product X.Y is mathematically sum (xi * yi) and can be written as X' * Y in octave when X and Y are vectors.
There are other ways to write a scalar product in octave, cf
https://octave.sourceforge.io/octave/function/dot.html

The question seems to be, given an example where:
X = randn(m, k); % m 'input' horizontal-vectors of dimensionality k
y = randn(m, n); % m 'target' horizontal-vectors of dimensionality n
theta = randn(k, n); % a (right) transformation from k to n dimensional
% horizontal-vectors
h = X * theta; % creates m rows of n-dimensional horizontal vectors
how is it that the following code
delta = zeros(k,n)
for j = 1 : k % iterating over all dimensions of the input
for l = 1 : n % iterating over all dimensions of the output
for i = 1 : m % iterating over all observations for that j,l pair
delta(j, l) += (1/m) * (h(i, l) - y(i, l)) * x(i,j);
end
theta(j, l) = theta(j, l) - alpha * delta(j, l);
end
end
can be vectorised as:
h = X * theta ;
delta = (1/ m) * X' * (h - y);
theta = theta - alpha * delta;
To confirm such a vectorised formulation makes sense, it always helps to note (e.g. below each line) the dimensions of the objects involved in the matrix / vectorised operations:
h = X * theta ;
% [m, n] [m, k] [k, n]
delta = (1/ m) * X' * (h - y);
% [k, n] [1, 1] [k, m] [m, n]
theta = theta - alpha * delta;
% [k, n] [k,n] [1, 1] [k, n]
Hopefully now it will become more obvious that they are equivalent.
W.r.t the X' * D calculation (where D = predictions - y) you can see that:
performing matrix multiplication with the 1st row of X' and the 1st column of D is equal to summing for k=1 and n=1 over all m observations, and placing that result at position [k=1, n=1] in the resulting matrix output. Then moving along the columns of D and still multiplying by the 1st row of X', you can see that we are simply moving along the n dimensions in D, and placing the result accordingly in the output. Similarly, moving along the rows of X', you move along the k dimensions of X', performing the same process for all n in that D, and placing the results accordingly, until you've finished matrix multiplications over all rows of X and columns in D.
If you follow the logic above, you will see that the summations involved are exactly the same as in the for loop formulation, but we managed to avoid using a for loop and use matrix operations instead.

Related

Gradient Descent produces incorrect Thetas in octave

I'm trying out a prediction algorithm using polynomial regression of the form h(x) = theta0 + theta1 * x1 + theta2 * x2, where x2=x1^2
I'm calculating the thetas with two methods, to compare the results: Normal Equation Vs. Gradient Decent. Then I plot the regression line for both methods for scores from 65 to 100, to see how it fits with my data.
When calculating thetas using Normal Equation, all seems to be working as expected. In the graph below, "x" is the actual scores, and "o" is the predicted scores.
However when calculating thetas using Gradient Decent, the resulting regression line does not fit my data. It looks like this:
While minimizing my Cost Function, I'm plotting the Gradient Descent iterations over J, to confirm that values converge. This seems to be working correctly:
Here's my code:
function [theta_normalEq, theta_gradientDesc] = a1_LinearRegression()
clear();
% suppose you want to fit a model of the form h(x) = theta0 + theta1 * x1 + theta2 * x2
% where x1 is the midterm score and x2 is (midterm score)^2
midTerm = [89; 72; 94; 69]; % mid-term Exam scores
midTerm2 = midTerm .^2; % same as above but each element squared (. refers to "each element". If 'dot' was not there, ^2 alone would mean matrix multiplications
X = [midTerm midTerm2]; % concatinate the two vectors into a single matrix
y = [96; 74; 87; 78]; %final Exam scores
% Method A:
% calculate theta (bias for each independent variable) using Normal Equation
% This works in some cases only (see comments in corresponding function below)
theta_normalEq = normalEquation(X, y);
% Method B:
% Use Gradient Descent
theta_gradientDesc = gradientDescent(X, y, 1.3, 60);
% plot regression line to see visually how it fits with our data
plotRegressionLine(midTerm, y, X, theta_gradientDesc);
% clear unneeded variables for a tidy output window
clear ('midTerm', 'midTerm2');
endfunction
% plots a regression line to see visually how it fits with our data
function plotRegressionLine(midTerm, y, X, theta)
% Our X matrix is n-long, but our theta is n+1 (remember we are modeling h(x) = theta0 + theta1 * x1 + theta2 * x2)
% Therefore we will introduce an X0 and set it to x0 = 1 for all values of i, so that we can do matrix operations with theta and X.
% This makes the two vectors 'theta' and x(i) match each other element-wise (that is, have the same number of elements: n+1).
X0 = ones(rows(X),1);
X = [X0 X]; % concatination; X had 2 columns, now it has 3. The very first column now consists of 'ones'
clear ('X0'); % just clears the variable
% with our thetas calculated, we can now plug them in our original model to make predictions
% model form: h(x) = theta0 + theta1 * x1 + theta2 * x2
% vectorized version: h(x) = X * theta
y_predicted = X * theta;
% let's also calculate the poits for all possible scores, to draw a regression line
scoreMin = 65;
scoreMax = 100;
step = 0.1;
scores = (scoreMin: step: scoreMax)';
scoresX = [ones(rows(scores),1) scores scores.^2];
scoresY_predicted = scoresX * theta;
% plot
figure 2;
clf;
hold on;
plot(midTerm, y, "x"); % draws our actual data points
plot(midTerm, y_predicted, "or"); % draws our predicted data points
plot(scores, scoresY_predicted, "r"); % draws our calculated regression line
hold off;
endfunction
% Performs gradient descent to learn theta. Updates theta by taking num_iters
%
% X = matrix of independent variables (e.g., size of house, number of bedrooms, number of bathrooms, etc)
% y = vector of dependent variables (e.g., cost of house)
% alpha = the rate of learning
% number of iterations to try finding the optimum theta
%
% Start by trying out a random alpha, like 0.1 or 1.
% If alpha is too small, it will take too long to minimize J and see values converging (too many iterations)
% If alpha is too large, we will overshoot the function minimum and values will start increasing again
% Ideally we want as large an alpha to get enough resolution to discover the function minimum with as few iterations as possible, without overshooting the minimum
%
% We also want a numner of iterations that are enough, but not too many. Depending on our problem and data, this can be from 30 to 300 to 3000 to 3 million, or more.
% In practice, we plot J against number of iterations as we go along the loop, to discover experimentally the optimal values for 'alpha' and 'num_iters'
% The graph we are looking for looks like a hokey stick of reducing values, that flattens horizontally. The J no longer reduces (the flat horizontal part), we have converged.
%
function theta = gradientDescent(X, y, alpha, num_iters)
% NORMALIZE FEATURES
% We can speed up gradient descent by having each of our input values in roughly the same range
% This is because θ will descend quickly on small ranges and slowly on large ranges, and so will oscillate inefficiently down to the optimum when the variables are very uneven.
% The way to prevent this is to modify the ranges of our input variables so that they are all roughly the same
% zscore() normalizes each feature (each column) independently, which is what we want: (value - mean of values for that column) / standard deviation of that column
X = zscore(X);
y = zscore(y);
% Our X matrix is n-long, but our theta is n+1 (remember we are modeling h(x) = theta0 + theta1 * x1 + theta2 * x2)
% Therefore we will introduce an X0 and set it to x0 = 1 for all values of i, so that we can do matrix operations with theta and X.
% This makes the two vectors 'theta' and x(i) match each other element-wise (that is, have the same number of elements: n+1).
X0 = ones(rows(X),1);
X = [X0 X]; % concatination; X had 2 columns, now it has 3. The very first column now consists of 'ones'
clear ('X0'); % just clears the variable
% number of training examples
m = length(y);
% save the cost J in every iteration in order to plot J vs. num_iters and check for convergence
J_history = zeros(num_iters, 1);
% We start with a random set of thetas.
% Gradient Descent improves them at each iteration until values converge
% NOTE: do not use randomMatrix() to initialize. Rather, hard code random values so that they are identical at each run attempt,
% to help us experiment with different sets of 'alpha' & 'num_iters' until we discover their optimal values.
%theta = randomMatrix(columns(X), 1, 0, 1);
theta = [0;0;0];
for iter = 1:num_iters
h = X * theta;
stderr = h - y;
theta = theta - (alpha/m) * X' * stderr;
J_history(iter) = computeCost(X, y, theta);
endfor
% plot J vs. num_iters and check for convergence
xAxis = 1:1:num_iters; % create vector from 1 to num_iters with step 1
figure 1;
clf;
plot(xAxis, J_history);
endfunction
% These two functions give identical results, but maybe one runs faster than another
function J = computeCost(X, y, theta)
m = length(y); % number of training examples
J = 1/(2*m) * sum( ( X*theta - y) .^ 2);
endfunction
%
function J = computeCostVectorized(X, y, theta)
m = length(y); % number of training examples
J = 1/(2*m) * (X*theta - y)' * (X*theta - y);
endfunction
% alternative way of finding the optimum theta without iteration and without having to try different alphas (rate of learning)
% however this method can be slow in situations with a lot of features + large training set combos
% There is no need to do feature scaling with the normal equation!!!
%
% WARNING:
% X'* X may be noninvertible. The common causes are:
% > Redundant features, where two features are very closely related (i.e. they are linearly dependent)
% > Too many features (e.g. m ≤ n). In this case, delete some features or use "regularization" (to be explained in a later lesson)
%
% Solutions to the above problems include deleting a feature that is linearly dependent with another or deleting one or more features when there are too many features
function theta = normalEquation(X, y)
% Our X matrix is n-long, but our theta is n+1 (remember we are modeling h(x) = theta0 + theta1 * x1 + theta2 * x2)
% Therefore we will introduce an X0 and set it to x0 = 1 for all values of i, so that we can do matrix operations with theta and X.
% This makes the two vectors 'theta' and x(i) match each other element-wise (that is, have the same number of elements: n+1).
X0 = ones(rows(X),1);
X = [X0 X]; % concatination; X had 2 columns, now it has 3. The very first column now consists of 'ones'
clear ('X0'); % just clears the variable
Xt = X';
theta = pinv(Xt * X) * Xt * y;
endfunction
% returns a random matrix of the specified size
% if you don't care to specify mean and variance, just use 0 and 1 respectively (or just call 'randn(rows, columns)' directly)
function retVal = randomMatrix(rows, columns, mean, variance)
retVal = mean + sqrt(variance)*(randn(rows,columns));
endfunction

Gradient Descent Octave Code

need help in completing this function. Getting an error while trying to find out derJ :
error: X(0,_): subscripts must be either integers 1 to (2^63)-1 or logicals
My code:
function [theta, J_history] = gradientDescent (X, y, theta, alpha, num_iters)
m = length (y); % number of training examples
J_history = zeros (num_iters, 1);
for iter = 1 : num_iters
predictions = X * theta; % hypothesis
% derivative term for cost function
derJ = (1 / m) * sum ( (predictions - y) * X(iter-1, 2) );
% updating theta values
theta = theta - (alpha * derJ);
J_history(iter) = computeCost (X, y, theta);
end
end
Your code states X(iter - 1, 2), but in your for loop iter starts from 1.
Therefore in the very first iteration, X(iter - 1, 2) will evaluate to X(0,2), and 0 is not a valid index in matlab.

In case of logistic regression, how should I interpret this learning curve between cost and number of examples?

I have obtained the following learning curve on plotting the learning curves for training and cross validation sets between the error cost, and number of training examples (in 100s in the graph). Can someone please tell me if this learning curve is ever possible? Because I am of the impression that the Cross validation error should decrease as the number of training examples increase.
Learning Curve. Note that the x axis denotes the number of training examples in 100s.
EDIT :
This is the code which I use to calculate the 9 values for plotting the learning curves.
X is the 2D matrix of the training set examples. It is of dimensions m x (n+1). y is of dimensions m x 1, and each element has value 1 or 0.
for j=1:9
disp(j)
[theta,J] = trainClassifier(X(1:(j*100),:),y(1:(j*100)),lambda);
[error_train(j), grad] = costprediciton_train(theta , X(1:(j*100),:), y(1:(j*100)));
[error_cv(j), grad] = costfunction_test2(theta , Xcv(1:(j*100),:),ycv(1:(j*100)));
end
The code I use for finding the optimal value of Theta from the training set.
% Train the classifer. Return theta
function [optTheta, J] = trainClassifier(X,y,lambda)
[m,n]=size(X);
initialTheta = zeros(n, 1);
options=optimset('GradObj','on','MaxIter',100);
[optTheta, J, Exit_flag ] = fminunc(#(t)(regularizedCostFunction(t, X, y, lambda)), initialTheta, options);
end
%regularized cost
function [J, grad] = regularizedCostFunction(theta, X, y,lambda)
[m,n]=size(X);
h=sigmoid( X * theta);
temp1 = -1 * (y .* log(h));
temp2 = (1 - y) .* log(1 - h);
thetaT = theta;
thetaT(1) = 0;
correction = sum(thetaT .^ 2) * (lambda / (2 * m));
J = sum(temp1 - temp2) / m + correction;
grad = (X' * (h - y)) * (1/m) + thetaT * (lambda / m);
end
The code I use for calculating the error cost for prediction of results for training set: (similar is the code for error cost of CV set)
Theta is of dimensions (n+1) x 1 and consists of the coefficients of the features in the hypothesis function.
function [J,grad] = costprediciton_train(theta , X, y)
[m,n]=size(X);
h=sigmoid(X * theta);
temp1 = y .* log(h);
temp2 = (1-y) .* log(1- h);
J = -sum (temp1 + temp2)/m;
t=h-y;
grad=(X'*t)*(1/m);
end
function [J,grad] = costfunction_test2(theta , X, y)
m= length(y);
h=sigmoid(X*theta);
temp1 = y .* log(h);
temp2 = (1-y) .* log(1- h);
J = -sum (temp1 + temp2)/m ;
grad = (X' * (h - y)) * (1/m) ;
end
The Sigmoid function:
function g = sigmoid(z)
g= zeros(size(z));
den=1 + exp(-1*z);
g = 1 ./ den;
end

Cost Function, Linear Regression, trying to avoid hard coding theta. Octave.

I'm in the second week of Professor Andrew Ng's Machine Learning course through Coursera. We're working on linear regression and right now I'm dealing with coding the cost function.
The code I've written solves the problem correctly but does not pass the submission process and fails the unit test because I have hard coded the values of theta and not allowed for more than two values for theta.
Here's the code I've got so far
function J = computeCost(X, y, theta)
m = length(y);
J = 0;
for i = 1:m,
h = theta(1) + theta(2) * X(i)
a = h - y(i);
b = a^2;
J = J + b;
end;
J = J * (1 / (2 * m));
end
the unit test is
computeCost( [1 2 3; 1 3 4; 1 4 5; 1 5 6], [7;6;5;4], [0.1;0.2;0.3])
and should produce ans = 7.0175
So I need to add another for loop to iterate over theta, therefore allowing for any number of values for theta, but I'll be damned if I can wrap my head around how/where.
Can anyone suggest a way I can allow for any number of values for theta within this function?
If you need more information to understand what I'm trying to ask, I will try my best to provide it.
You can use vectorize of operations in Octave/Matlab.
Iterate over entire vector - it is really bad idea, if your programm language let you vectorize operations.
R, Octave, Matlab, Python (numpy) allow this operation.
For example, you can get scalar production, if theta = (t0, t1, t2, t3) and X = (x0, x1, x2, x3) in the next way:
theta * X' = (t0, t1, t2, t3) * (x0, x1, x2, x3)' = t0*x0 + t1*x1 + t2*x2 + t3*x3
Result will be scalar.
For example, you can vectorize h in your code in the next way:
H = (theta'*X')';
S = sum((H - y) .^ 2);
J = S / (2*m);
Above answer is perfect but you can also do
H = (X*theta);
S = sum((H - y) .^ 2);
J = S / (2*m);
Rather than computing
(theta' * X')'
and then taking the transpose you can directly calculate
(X * theta)
It works perfectly.
The below line return the required 32.07 cost value while we run computeCost once using θ initialized to zeros:
J = (1/(2*m)) * (sum(((X * theta) - y).^2));
and is similar to the original formulas that is given below.
It can be also done in a line-
m- # training sets
J=(1/(2*m)) * ((((X * theta) - y).^2)'* ones(m,1));
J = sum(((X*theta)-y).^2)/(2*m);
ans = 32.073
Above answer is perfect,I thought the problem deeply for a day and still unfamiliar with Octave,so,Just study together!
If you want to use only matrix, so:
temp = (X * theta - y); % h(x) - y
J = ((temp')*temp)/(2 * m);
clear temp;
This would work just fine for you -
J = sum((X*theta - y).^2)*(1/(2*m))
This directly follows from the Cost Function Equation
Python code for the same :
def computeCost(X, y, theta):
m = y.size # number of training examples
J = 0
H = (X.dot(theta))
S = sum((H - y)**2);
J = S / (2*m);
return J
function J = computeCost(X, y, theta)
m = length(y);
J = 0;
% Hypothesis h(x)
h = X * theta;
% Error function (h(x) - y) ^ 2
squaredError = (h-y).^2;
% Cost function
J = sum(squaredError)/(2*m);
end
I think we needed to use iteration for much general solution for cost rather one iteration, also the result shows in the PDF 32.07 may not be correct answer that grader is looking for reason being its a one case out of many training data.
I think it should loop through like this
for i in 1:iteration
theta = theta - alpha*(1/m)(theta'*x-y)*x
j = (1/(2*m))(theta'*x-y)^2

gradient descent seems to fail

I implemented a gradient descent algorithm to minimize a cost function in order to gain a hypothesis for determining whether an image has a good quality. I did that in Octave. The idea is somehow based on the algorithm from the machine learning class by Andrew Ng
Therefore I have 880 values "y" that contains values from 0.5 to ~12. And I have 880 values from 50 to 300 in "X" that should predict the image's quality.
Sadly the algorithm seems to fail, after some iterations the value for theta is so small, that theta0 and theta1 become "NaN". And my linear regression curve has strange values...
here is the code for the gradient descent algorithm:
(theta = zeros(2, 1);, alpha= 0.01, iterations=1500)
function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)
m = length(y); % number of training examples
J_history = zeros(num_iters, 1);
for iter = 1:num_iters
tmp_j1=0;
for i=1:m,
tmp_j1 = tmp_j1+ ((theta (1,1) + theta (2,1)*X(i,2)) - y(i));
end
tmp_j2=0;
for i=1:m,
tmp_j2 = tmp_j2+ (((theta (1,1) + theta (2,1)*X(i,2)) - y(i)) *X(i,2));
end
tmp1= theta(1,1) - (alpha * ((1/m) * tmp_j1))
tmp2= theta(2,1) - (alpha * ((1/m) * tmp_j2))
theta(1,1)=tmp1
theta(2,1)=tmp2
% ============================================================
% Save the cost J in every iteration
J_history(iter) = computeCost(X, y, theta);
end
end
And here is the computation for the costfunction:
function J = computeCost(X, y, theta) %
m = length(y); % number of training examples
J = 0;
tmp=0;
for i=1:m,
tmp = tmp+ (theta (1,1) + theta (2,1)*X(i,2) - y(i))^2; %differenzberechnung
end
J= (1/(2*m)) * tmp
end
If you are wondering how the seemingly complex looking for loop can be vectorized and cramped into a single one line expression, then please read on. The vectorized form is:
theta = theta - (alpha/m) * (X' * (X * theta - y))
Given below is a detailed explanation for how we arrive at this vectorized expression using gradient descent algorithm:
This is the gradient descent algorithm to fine tune the value of θ:
Assume that the following values of X, y and θ are given:
m = number of training examples
n = number of features + 1
Here
m = 5 (training examples)
n = 4 (features+1)
X = m x n matrix
y = m x 1 vector matrix
θ = n x 1 vector matrix
xi is the ith training example
xj is the jth feature in a given training example
Further,
h(x) = ([X] * [θ]) (m x 1 matrix of predicted values for our training set)
h(x)-y = ([X] * [θ] - [y]) (m x 1 matrix of Errors in our predictions)
whole objective of machine learning is to minimize Errors in predictions. Based on the above corollary, our Errors matrix is m x 1 vector matrix as follows:
To calculate new value of θj, we have to get a summation of all errors (m rows) multiplied by jth feature value of the training set X. That is, take all the values in E, individually multiply them with jth feature of the corresponding training example, and add them all together. This will help us in getting the new (and hopefully better) value of θj. Repeat this process for all j or the number of features. In matrix form, this can be written as:
This can be simplified as:
[E]' x [X] will give us a row vector matrix, since E' is 1 x m matrix and X is m x n matrix. But we are interested in getting a column matrix, hence we transpose the resultant matrix.
More succinctly, it can be written as:
Since (A * B)' = (B' * A'), and A'' = A, we can also write the above as
This is the original expression we started out with:
theta = theta - (alpha/m) * (X' * (X * theta - y))
i vectorized the theta thing...
may could help somebody
theta = theta - (alpha/m * (X * theta-y)' * X)';
I think that your computeCost function is wrong.
I attended NG's class last year and I have the following implementation (vectorized):
m = length(y);
J = 0;
predictions = X * theta;
sqrErrors = (predictions-y).^2;
J = 1/(2*m) * sum(sqrErrors);
The rest of the implementation seems fine to me, although you could also vectorize them.
theta_1 = theta(1) - alpha * (1/m) * sum((X*theta-y).*X(:,1));
theta_2 = theta(2) - alpha * (1/m) * sum((X*theta-y).*X(:,2));
Afterwards you are setting the temporary thetas (here called theta_1 and theta_2) correctly back to the "real" theta.
Generally it is more useful to vectorize instead of loops, it is less annoying to read and to debug.
If you are OK with using a least-squares cost function, then you could try using the normal equation instead of gradient descent. It's much simpler -- only one line -- and computationally faster.
Here is the normal equation:
http://mathworld.wolfram.com/NormalEquation.html
And in octave form:
theta = (pinv(X' * X )) * X' * y
Here is a tutorial that explains how to use the normal equation: http://www.lauradhamilton.com/tutorial-linear-regression-with-octave
While not scalable like a vectorized version, a loop-based computation of a gradient descent should generate the same results. In the example above, the most probably case of the gradient descent failing to compute the correct theta is the value of alpha.
With a verified set of cost and gradient descent functions and a set of data similar with the one described in the question, theta ends up with NaN values just after a few iterations if alpha = 0.01. However, when set as alpha = 0.000001, the gradient descent works as expected, even after 100 iterations.
Using only vectors here is the compact implementation of LR with Gradient Descent in Mathematica:
Theta = {0, 0}
alpha = 0.0001;
iteration = 1500;
Jhist = Table[0, {i, iteration}];
Table[
Theta = Theta -
alpha * Dot[Transpose[X], (Dot[X, Theta] - Y)]/m;
Jhist[[k]] =
Total[ (Dot[X, Theta] - Y[[All]])^2]/(2*m); Theta, {k, iteration}]
Note: Of course one assumes that X is a n * 2 matrix, with X[[,1]] containing only 1s'
This should work:-
theta(1,1) = theta(1,1) - (alpha*(1/m))*((X*theta - y)'* X(:,1) );
theta(2,1) = theta(2,1) - (alpha*(1/m))*((X*theta - y)'* X(:,2) );
its cleaner this way, and vectorized also
predictions = X * theta;
errorsVector = predictions - y;
theta = theta - (alpha/m) * (X' * errorsVector);
If you remember the first Pdf file for Gradient Descent form machine Learning course, you would take care of learning rate. Here is the note from the mentioned pdf.
Implementation Note: If your learning rate is too large, J(theta) can di-
verge and blow up', resulting in values which are too large for computer
calculations. In these situations, Octave/MATLAB will tend to return
NaNs. NaN stands fornot a number' and is often caused by undened
operations that involve - infinity and +infinity.

Resources