
When it comes to machine learning, a popular starting place is linear regression using gradient descent. It is a simple optimization problem that is easy to understand, and it gradually introduces ideas that show up everywhere in machine learning.
Many of you are probably familiar with linear regression: the process of fitting a line to scattered data. It is useful in a huge range of applications. Whether you are trying to predict price increases at the supermarket, or how high a person can jump based on their height, the usefulness of linear regression spans seemingly endless domains.
As a gradual introduction to machine learning, we will discuss how to perform a linear regression (a line-fitting approximation) on a set of 2-D data (X & Y) using a gradient descent algorithm. To make every step concrete, the figures in this post come from actually running the algorithm on a small dataset of 40 points.
What is linear regression?
For us to make use of this technique, we must understand two fundamental things. First, what is linear regression? Second, what is gradient descent? Most of you are probably familiar with the former, so I will speed through that portion and focus on the lesser-known gradient descent portion.
Simply put, linear regression is a technique for fitting a line onto scattered data. The goal is to create a line-based model that can be used to predict one value from one or more other values. In the 2-D case, it uses the classic equation for a line:
ŷ = m·x + b
Here m is the slope of the line, b is the y-intercept, and ŷ (“y-hat”) is the value the line predicts for a given x. The goal of linear regression is to find the values of m and b that make the line fit the scattered data as closely as possible.
What is gradient descent?
Gradient descent is an iterative optimization algorithm used to find the minimum of a function. To picture it, imagine a hiker walking down a hill to reach the bottom. At first the hiker takes large steps; as they get close to the goal, they take smaller and smaller steps so they don't overshoot it.
The loss function
For the hiker, the value being minimized is the distance to the bottom of the hill. For linear regression, the value we minimize is the error between each data point’s actual y-value and the y-value our line predicts. We measure it with a loss function, here the mean squared error over all n points:
E(m, b) = (1/n) · Σᵢ (yᵢ − (m·xᵢ + b))²
Squaring each error makes every term positive and penalizes large misses more than small ones. Because E depends on both m and b, it forms a surface, and the best line sits at the lowest point of that surface.
Walking downhill: the update rules
Now that we know what we are minimizing, we can introduce our iterative approach. Since the loss has two variables (m and b), we adjust both on every step, moving each one against its own slope (its partial derivative):
m ← m − L · ∂E/∂m
b ← b − L · ∂E/∂b
L is the learning rate, a small constant that sets the step size. It controls how fast and how accurately the algorithm converges: too small and it crawls, too large and it overshoots and diverges. Taking the partial derivatives of our loss function gives:
∂E/∂m = −(2/n) · Σᵢ xᵢ · (yᵢ − (m·xᵢ + b))
∂E/∂b = −(2/n) · Σᵢ (yᵢ − (m·xᵢ + b))
To get a feel for the learning rate, drag the slider below. It runs gradient descent on a simpler one-variable loss, f(w) = (w − 3)², starting at w = −2; the slider calls the learning rate η rather than L.
With the update w ← w − η · f′(w), each step shrinks the distance to the minimum by a factor of |1 − 2η|, so it converges for η below 1 and diverges for η above 1.
The algorithm, step by step
Now that we have derived all of our equations, we can perform a gradient descent linear regression with the following steps:
- Set m and b to 0 and choose a small learning rate. For the 40-point dataset above, 0.01 works well; the right value depends on the scale of your data, so if the loss grows instead of shrinking, make it smaller.
- Calculate the partial derivatives ∂E/∂m and ∂E/∂b.
- Update m and b with the update rules.
- Calculate the loss. Repeat steps 2–4 until the loss stops changing (or changes by less than some tiny amount). The final values of m and b give you the equation of your regression line.
The whole thing fits in a few lines of Python:
def fit_line(xs, ys, learning_rate=0.01, iterations=1500):
m, b = 0.0, 0.0
n = len(xs)
for _ in range(iterations):
errors = [y - (m * x + b) for x, y in zip(xs, ys)]
dm = -2 / n * sum(x * e for x, e in zip(xs, errors))
db = -2 / n * sum(errors)
m -= learning_rate * dm
b -= learning_rate * db
return m, b
What the loss looks like
Note that the loss will not reach zero unless every point lies exactly on a line. Real data has noise, so the loss levels off at the smallest error any straight line can achieve. On our dataset, the loss drops from 279 to under 10 in the first five iterations, then slowly approaches its floor of 4.64.
After 1500 iterations, gradient descent finds m = 2.28 and b = 4.32, matching the exact least-squares solution to two decimal places. For a simple line, that solution can also be computed directly, but gradient descent is worth learning because the same idea of following the slope of a loss function downhill is what trains neural networks, where no direct solution exists.