03

A model and its error

How do you measure how wrong a model is?

11 min

A model and its error

With voice. You can pause and jump to any step.

Lesson complete

Subtitles

You already know a model is a rule with adjustable numbers. Let’s build the simplest one with a made-up case: ten students, the hours each one studied, and the grade each one got.

Voice

No voice: the lesson advances on its own with subtitles.

The voice for this lesson is being recorded: for now it advances on its own with subtitles.

0:00 / 0:00

What you will achieve

  • Read a straight line through its two parameters, the weight (how much it rises per unit of input) and the bias (its height when the input is zero), and use them to compute a prediction.
  • Calculate the error of a point and explain why it is squared before averaging: signs stop canceling and big errors weigh more.
  • Calculate the loss (MSE) of a few points and recognize that learning means choosing the parameters that make it as low as possible.

Key ideas

  1. A straight line rises (or falls) at a constant pace. Its weight w, the slope, is how much the prediction rises per unit of input; its bias b is the height when the input is zero. The prediction is w·x + b.
  2. The error of a point is the real value minus the prediction: the vertical distance between the point and the line. Adding errors with their signs fails, because positives and negatives cancel.
  3. Squaring each error removes the sign and makes big errors weigh more: an error of 2 counts 4; one of 4, 16. The MSE loss is the average of those squares.
  4. Learning means choosing the weight and bias that make the loss as low as possible. A straight line has a formula (least squares, Legendre and Gauss), but even then the loss does not reach zero.
  5. Squaring is a decision: an unusual point can bend the line, whereas the absolute error barely listens to it.

What many people believe

Common belief A good model is one that passes through every point: its loss should be zero.

What is true Real data always carry noise, and a straight line cannot pass through every point: even the best one has a loss above zero. A model with zero loss on its training data has usually memorized the noise, and fails on new cases (lesson 10).

Check yourself

Four questions. No grade, no account: they just show whether the idea stuck.

ConceptA line predicts the grade with prediction = 4 · hours + 30. What does the 4 tell you?
ConceptWhy is it not enough to add up the errors with their signs to measure how bad a line is?
CalculationA model predicts 70 and 60 for two students who scored 82 and 55. What is the loss (MSE)?
ApplicationA vendor shows you a model that predicts sales with a loss (MSE) of 120. What do you need to know whether it is good?

Under the hoodFor those who want the math and the code. You do not need it to follow the course.

The line, piece by piece

A straight line is the graph of y^=wx+b\hat y = wx + b (read “y-hat”: the prediction). The weight ww is the slope: if the input grows by Δx\Delta x, the prediction grows by w Δxw\,\Delta x, so w=Δy^/Δxw = \Delta \hat y / \Delta x, rise over run. The bias bb is the intercept: y^(0)=b\hat y(0) = b. In the lesson, w=5w = 5 and b=40b = 40: with 7 hours, y^=5⋅7+40=75\hat y = 5\cdot 7 + 40 = 75.

The model and the loss

With several features (lesson 2) the input is a vector x\mathbf{x} and the prediction is y^=w⋅x+b\hat y = \mathbf{w}\cdot\mathbf{x} + b: one weight per feature and a single bias. The ten students in the lesson are invented.

The error of a point is ei=yi−y^ie_i = y_i - \hat y_i. With nn points, the two losses in the lesson are

MAE=1n∑i=1n∣ei∣L(w,b)=MSE=1n∑i=1n(yi−wxi−b)2\mathrm{MAE}=\frac1n\sum_{i=1}^{n}|e_i| \qquad\qquad L(w,b)=\mathrm{MSE}=\frac1n\sum_{i=1}^{n}\bigl(y_i-wx_i-b\bigr)^2

The MSE is measured in squared points. Its root, L\sqrt{L}, goes back to points: with the best line in the lesson, 42.5≈6.5\sqrt{42.5}\approx 6.5 points of typical error. The example line (w=5w = 5, b=40b = 40) has L=45.775L = 45.775; the flat line at the average, L=244.04L = 244.04.

Why the square

  • It is smooth. L(w,b)L(w,b) is a paraboloid: it has a single bottom and a well-defined slope everywhere, which will let us slide down it (lesson 4). The absolute value has a kink at zero.
  • It has a formula. Setting the partial derivatives of LL to zero gives a linear system, the normal equations.
  • It has a probabilistic justification. If yi=wxi+b+εiy_i = wx_i+b+\varepsilon_i with normal noise εi∼N(0,σ2)\varepsilon_i\sim\mathcal N(0,\sigma^2), the likelihood is highest exactly where the MSE is lowest (Goodfellow et al., 2016, sec. 5.5.1, which calls it a criterion introduced “more or less arbitrarily” before justifying it this way). Gauss set this out in 1809 (Theoria motus, arts. 175–179): if the errors follow the normal curve, the most probable system of values is the one with the smallest sum of squares. With Laplace noise, which has heavier tails, the matching criterion is the absolute error.
  • It is sensitive to outliers. With a single parameter (predicting a constant), the MSE is minimized by the mean and the absolute error by the median. In the lesson’s data, the mean is 64.4 and the median 59.5 (with ten data points, any value between 57 and 62 minimizes the absolute error; the midpoint is taken).

A little history

Legendre presented least squares in 1805, in an appendix, as the principle that in his judgment is the “most general, most exact and of easiest application”, and that sets up among the errors “a sort of equilibrium” that keeps the extremes from prevailing. Gauss wrote in 1809 that he had used it since 1795 (Theoria motus, art. 186) and that, among all even powers of the error, the square was “the most simple”; the priority was disputed (Plackett, 1972; Stigler, 1981).

In the same article Gauss reports that Laplace used the absolute error, proposed earlier by Boscovich. He notes that with it the line generally passes through two of the points, and that any other value could have been observed for another point without changing the solution, provided it stays on the same side: it is what you saw with the outlier, whose absolute line did not move when its grade was lowered. Between the two extremes there are hybrid losses, such as Huber’s (1964): quadratic for small errors and linear for large ones.

The best line

w∗=∑i(xi−xˉ)(yi−yˉ)∑i(xi−xˉ)2=cov⁡(x,y)var⁡(x)b∗=yˉ−w∗xˉw^*=\frac{\sum_i (x_i-\bar x)(y_i-\bar y)}{\sum_i (x_i-\bar x)^2}=\frac{\operatorname{cov}(x,y)}{\operatorname{var}(x)}\qquad\qquad b^*=\bar y-w^*\bar x

With xˉ=4.55\bar x = 4.55 and yˉ=64.4\bar y = 64.4 we get w∗≈5.26w^*\approx 5.26 and b∗≈40.45b^*\approx 40.45, with minimum loss Lmin⁡≈42.5L_{\min}\approx 42.5. The best line always passes through the mean point (xˉ,yˉ)(\bar x,\bar y). In matrix form these are the normal equations, w∗=(X⊤X)−1X⊤y\mathbf{w}^*=(X^\top X)^{-1}X^\top\mathbf{y} (in XX, a column of ones takes care of the bias).

If we keep b=b∗b=b^* and move only ww, the loss is exactly a parabola:

L(w)=Lmin⁡+x2‾ (w−w∗)2,x2‾≈28.0L(w)=L_{\min}+\overline{x^2}\,(w-w^*)^2,\qquad \overline{x^2}\approx 28.0

It is the valley in the last scene. The name “regression” comes from Galton. In his 1886 study of stature (930 adult children from 205 families) he found that the children’s height deviation is, on average, two thirds of their parents’: the children of very tall parents tend to be less tall, and those of very short parents, taller. He called it “regression towards mediocrity”, that is, towards the average.

In code

# ten invented students for the lesson
hours = [0.5, 1.5, 2, 3, 4, 5, 6, 6.5, 8, 9]
grade = [43, 49, 52, 57, 62, 72, 73, 56, 87, 93]
n = len(hours)
mx, my = sum(hours) / n, sum(grade) / n

# least squares: w = cov(x, y) / var(x),  b = mean(y) - w * mean(x)
w = sum((x - mx) * (y - my) for x, y in zip(hours, grade)) / sum((x - mx) ** 2 for x in hours)
b = my - w * mx

def loss(w, b):  # mean squared error (MSE)
    return sum((y - (w * x + b)) ** 2 for x, y in zip(hours, grade)) / n

print(round(w, 2), round(b, 2))   # 5.26 40.45   (best weight and bias)
print(round(loss(w, b), 1))       # 42.5         (minimum loss)
print(round(loss(0, my), 1))      # 244.0        (flat line: always predict the mean)
print(round(loss(5, 40), 1))      # 45.8         (the example line: weight 5, bias 40)

What comes next

The closed formula works for a straight line. In a network with billions of weights there is none, and the bottom is found step by step: that is gradient descent (lesson 4). And lowering the loss on the training data is not enough: it has to be measured on data the model has not seen (lesson 10).

Decision lens

What this idea means if your job is to decide, not to code.

  • The loss function is a business decision, not a technical detail. Squaring says that one big error costs far more than several small ones. Ask whether that reflects your real cost: being very wrong once is not the same as being slightly wrong many times.
  • Always ask for a baseline. Here, predicting the average gave a loss of 244 and the best line 42.5. A complex model is only justified if it beats the baseline by a margin that pays for its cost. And ask what units the metric is in: the MSE is squared.
  • Outliers are decided before training: are they data-entry errors, which get fixed or dropped, or real cases that matter? With a squared loss, a single odd case can bend the model. Ask for a report of how much the result changes without it.
  • A low loss does not guarantee a good model: it was measured on the same data it was fit to, and outside the range it has seen the model extrapolates (with twelve hours, this line predicts more than a hundred). Lesson 10 explains how to evaluate on new data.

Terms in this lesson

Full transcript
CommentsThis lesson’s public conversation: questions, facts to check, ideas.

Comments live in GitHub Discussions, in the course’s public repository; writing one requires a GitHub account. They load from giscus.app when you open this section. The course reviewers read them, and if a change is accepted, it is applied in both languages. Open the thread on GitHub

Sources