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: ๐‘ฅ1๐‘– 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: โ„Ž๐œƒ(๐‘ฅ๐‘–)=๐œƒ1+๐œƒ2๐‘ฅ2๐‘–+โ‹ฏ+๐œƒ๐‘›๐‘ฅ๐‘›๐‘–=๐œƒ1๐‘ฅ1๐‘–+๐œƒ2๐‘ฅ2๐‘–+โ‹ฏ+๐œƒ๐‘›๐‘ฅ๐‘›๐‘–

๐œƒ : 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;