Visualized ML
Topics

A · One neuron

Linear Regression

Predict a number with a straight line, and pick the line whose squared errors are smallest.

Try it: A3 · Linear Regression

Intuition

You have pairs of numbers: a house's floor area and its price, an hour of study and an exam score. You want a rule that takes the first number and predicts the second. The simplest rule there is draws a straight line through the cloud of points and reads the prediction off the line.

Most lines are bad. A line is good when the points sit close to it, so we need a way to measure "close". For each point, the error (or residual) is the vertical gap between the point and the line: the true value minus the prediction. Square each error and you get the area of a square whose side is that gap. Linear regression picks the line that makes the total area of those squares as small as possible.

The line swings toward the best fit. Each square's side is one point's error, so its area is that error squared; the best line is the one with the smallest total area.

Why squares and not plain distances? Squaring makes every error positive, so errors above and below the line can't cancel. It punishes one big miss more than several small ones. And, as the math below shows, it turns the search for the best line into a problem with an exact answer.

The math

The model

With one input \(x\), the prediction is a weight times the input, plus a bias:

\[ \hat{y} = w\,x + b \]

With \(d\) inputs \(x_1, \dots, x_d\) it is the weighted sum you met in the perceptron, without the threshold:

\[ \hat{y} = w_1 x_1 + \dots + w_d x_d + b = \mathbf{w}^\top \mathbf{x} + b \]

The loss

Over \(n\) examples, the mean squared error (MSE) is the average area of the squares:

\[ L(w, b) = \frac{1}{n} \sum_{i=1}^{n} \big(y_i - (w x_i + b)\big)^2 \]

The loss is a function of the line's two numbers. Every line is a point \((w, b)\) on a plane, and the loss is a height above it. Because the errors are squared, that surface is a bowl: it has exactly one lowest point.

The exact answer

At the bottom of a bowl the slope is zero in every direction. Setting both partial derivatives to zero gives two equations whose solution is

\[ w = \frac{\sum_i (x_i - \bar{x})(y_i - \bar{y})}{\sum_i (x_i - \bar{x})^2}, \qquad b = \bar{y} - w\,\bar{x} \]

where \(\bar{x}\) and \(\bar{y}\) are the means. Read it as: the slope is how much \(x\) and \(y\) move together (their covariance) divided by how much \(x\) moves on its own (its variance). The second equation says the best line always passes through the centre of the data, \((\bar{x}, \bar{y})\).

With many inputs, stack the examples as the rows of a matrix \(X\) (with a column of ones for the bias). The same condition gives the normal equations:

\[ X^\top X\,\mathbf{w} = X^\top \mathbf{y} \quad\Rightarrow\quad \mathbf{w} = (X^\top X)^{-1} X^\top \mathbf{y} \]

Worked example. Three points: \((1, 2)\), \((2, 3)\), \((3, 5)\). The means are \(\bar{x} = 2\) and \(\bar{y} = 10/3\).

The deviations of \(x\) are \(-1, 0, 1\), and of \(y\) are \(-4/3, -1/3, 5/3\). So \(\sum (x_i - \bar x)(y_i - \bar y) = 4/3 + 0 + 5/3 = 3\) and \(\sum (x_i - \bar x)^2 = 2\).

That gives \(w = 3/2 = 1.5\) and \(b = 10/3 - 1.5 \cdot 2 = 1/3\). The predictions are \(1.83, 3.33, 4.83\), the errors \(0.17, -0.33, 0.17\), and the MSE is \((0.028 + 0.111 + 0.028)/3 \approx 0.056\). No other line does better on these three points.

Why squares: the probabilistic view

Suppose each \(y\) really is a straight line plus random noise drawn from a normal (Gaussian) distribution: \(y = w x + b + \varepsilon\), with \(\varepsilon \sim \mathcal{N}(0, \sigma^2)\). Then the probability of seeing the data is a product of bell curves, and its logarithm is, up to constants, minus the sum of squared errors. So the line with the smallest MSE is also the line that makes the data most likely: the maximum likelihood estimate. Squared error is not an arbitrary choice; it is what Gaussian noise implies. Different noise leads to different losses, which is the theme of Loss functions.

Variants & extensions

  • Polynomial and other basis features. "Linear" means linear in the weights, not in \(x\). Feed \(x, x^2, x^3\) as three inputs and the same method fits a curve. This is feature engineering.
  • Ridge and lasso. Add a penalty on the weights' size to the loss: \(\lambda \lVert\mathbf{w}\rVert^2\) (ridge) or \(\lambda \lVert\mathbf{w}\rVert_1\) (lasso). They trade a little training error for stability on new data; see Regularization.
  • Robust regression. Swap the squared error for one that grows more slowly, like absolute error or the Huber loss, so a single outlier can't drag the line.
  • Iterative fitting. Inverting \(X^\top X\) costs roughly \(d^3\) operations. With many inputs, or data that doesn't fit in memory, gradient descent walks down the same bowl instead.

When it fails

  • Outliers. One point far from the rest has a huge square, and the line bends toward it. In the Challenge you can drag one point and watch the whole line follow.
  • Curved relationships. If the truth is a curve, the best straight line is still wrong, in a systematic way: the errors form a pattern instead of random scatter. Plotting the residuals reveals it.
  • Correlated inputs. When two inputs carry nearly the same information, \(X^\top X\) is close to singular and the weights swing wildly from one dataset to the next, even though the predictions stay fine.
  • Extrapolation. The line is fitted where the data is. Far outside that range nothing guarantees the relationship continues.
  • Correlation is not cause. A good fit says \(x\) predicts \(y\), not that changing \(x\) would change \(y\).

History

Least squares was published by Adrien-Marie Legendre in 1805 to compute the orbits of comets, and Carl Friedrich Gauss claimed he had used it since 1795; in 1809 he gave the justification above, from normally distributed errors. The word "regression" is Francis Galton's: in the 1880s he noticed that the children of very tall parents tend to be less extreme, "regressing" toward the average, and the name stuck to the method he used to show it.

Connections

Builds on

Leads to

Further reading