Gradient Descent

Gradient Descent

Gradient descent is an iterative algorithm that aims to find values for the parameters of a function of interest which minimizes the output of a cost function with respect to a given dataset. Gradient descent is often used in machine learning to quickly find an approximative solution to complex, multi-variable problems.

In my last article, Introduction to Linear Regression, I mentioned gradient descent as a possible solution to simple linear regression. While there exists an optimal analytical solution to simple linear regression, the simplicity of this problem makes it an excellent candidate to demonstrate the inner workings of the gradient descent algorithm.

Cost function

Lets look back at the cost function outlined in Introduction to Linear Regression. This function represents the error observed while fitting our model onto the data. This is the error we would like to minimize. In this example, it corresponds to the mean of the vertical distance between our observations and the regression line squared (see Least Squares). In order to keep the size of the error manageable and to ensure that it won’t be affected by the size of our dataset, we divide by the number of observations (in essence calculating the mean of the errors).

$ Cost = \dfrac{\sum_{i=1}^n(y_i-(m x_i + b))^2}{N} $

Gradient

The gradient (the slope of our cost function at a given coordinate) represents the direction and the rate of change of our cost function. By following the negative gradient we are able to quickly minimize the cost function and arrive at a solution more rapidly. In order to obtain the gradient, our function must be differentiable with respect to the parameters we are trying to optimize. By taking the square of the distance we are guaranteed to have a positive output and a differentiable function.

The gradient is obtained by calculating the partial derivatives of our cost function with respect to the parameters $m$ and $b$ :

In gradient descent, two parameters must be fixed : the learning rate (the rate of change at each iteration) and the number of epochs (number of iterations/updates made during the gradient descent algorithm) during training. For this example, we will let gradient descent run during 10,000 iterations (epochs) with a learning rate (lr) of 0.001.