gradient descent vectorization
In linear regression problem, we often use gradient descent algorithm to minimize the cost function .
This is my derive for vectorize gradient descent algorithm, and Iโll use 1-index in this article.
Symbols๏ผ
m : number of training example.
n : number of features plus 1.
X : input of training set, X is a [n x m] dimension matrix.
: the input of the training example.
PS: is always 1 for any i in [1:m].
Y : output of training set, Y is a [1 x m] dimension matrix.
: the output of the training example.
: linear hypothesis function. In linear regression problem, is often as follow:
: parameters of hypothesis function, is a [n x 1] dimension matrix or n dimension column vector.
: cost function of hypothesis function, in gradient descent without regularization,cost function is often defined as follow:
Gradient descent algorithm can be described as the psuedocode below.
do:
(for j in [1:n])
until convergence
This algorithm actually need to update all the parameters simultaneously, so i didnโt put the update operation in a for loop.
is the learning rate, which controls how large a step our algorithm takes.
we actually need 4 nested loop to do this without vectorization. Not only will this implementation be complicated, but also slow. So we need to vectorize.
As we assumed, X is as follow:
Y is:
is :
so
here is the column training data.
so
which is J()=1/2/m .* sum((โ .* X - Y) .^ 2) in octave.
Now letโs see the partial derivative term,
Keep going, we get:
Finally we get our update rules:
In octave, it looks like this:
update = 1 / col * input * (theta' * input - output)';
theta = theta - step * update;And here is the code:
function parameters = gd(input, output, theta, step, eps)
% function that implement gradient descent algorithm
col = length(output);
do
% j = 1 / 2 / col * sum((theta' * input - output) .^ 2);
% ไธ่กๆณจ้่ฎก็ฎcostfunction
update = 1 / col * input * (theta' * input - output)';
theta = theta - step * update;
until max(abs(update)) <= eps
parameters = theta;