A model and its error
How do you measure how wrong a model is?
Lesson complete
If you like:
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.
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.
Review modeComment on this stepI finished the lesson
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
- 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.
- 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.
- 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.
- 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.
- 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.
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 (read “y-hat”: the prediction). The weight is the slope: if the input grows by , the prediction grows by , so , rise over run. The bias is the intercept: . In the lesson, and : with 7 hours, .
The model and the loss
With several features (lesson 2) the input is a vector and the prediction is : one weight per feature and a single bias. The ten students in the lesson are invented.
The error of a point is . With points, the two losses in the lesson are
The MSE is measured in squared points. Its root, , goes back to points: with the best line in the lesson, points of typical error. The example line (, ) has ; the flat line at the average, .
Why the square
- It is smooth. 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 to zero gives a linear system, the normal equations.
- It has a probabilistic justification. If with normal noise , 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
With and we get and , with minimum loss . The best line always passes through the mean point . In matrix form these are the normal equations, (in , a column of ones takes care of the bias).
If we keep and move only , the loss is exactly a parabola:
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
- Model A form of rule with adjustable numbers. Once trained, it is the learned rule.
- Parameter Each of the numbers a model adjusts while training and in which it stores what it learned.
- Feature One measurement of an example expressed as a number: the number of links in an email, the brightness of a pixel. The features of an example make up its vector.
- Training data Examples, each with its correct answer, from which a model adjusts its parameters.
- Weight (w) In a linear model, the number that multiplies the input: the slope of the line. It tells how much the prediction rises for each unit the input grows.
- Bias (b) The term added at the end of the model: the prediction when the input is zero, that is, the height at which the line crosses the vertical axis. It is not the bias of data or of an unfair model, which is a different concept.
- Prediction (ŷ) The number the model returns for a given input. Comparing it with the real value gives the error.
- Loss function A single number that summarizes how wrong a model is on its data. Training is the search for the parameters that make it as small as possible.
- Mean squared error (MSE) A loss that averages the squared errors. It punishes big errors far more than small ones and is measured in the units of the output, squared.
- Regression The task of predicting a number (a price, a grade, a temperature) rather than choosing a category. Linear regression uses a straight line.
Full transcript
Sources
- Legendre, A.-M. (1805). Nouvelles méthodes pour la détermination des orbites des comètes (apéndice «Sur la méthode des moindres quarrés», pp. 72–73 para la cita)
- Gauss, C. F. (1809). Theoria motus corporum coelestium in sectionibus conicis solem ambientium (libro II, sección 3, arts. 175–186; traducción inglesa de C. H. Davis, 1857)
- Plackett, R. L. (1972). Studies in the History of Probability and Statistics. XXIX: The discovery of the method of least squares
- Stigler, S. M. (1981). Gauss and the Invention of Least Squares
- Huber, P. J. (1964). Robust Estimation of a Location Parameter
- Galton, F. (1886). Regression towards mediocrity in hereditary stature
- Goodfellow, I., Bengio, Y., Courville, A. (2016). Deep Learning, cap. 5, secciones 5.1.4 (Example: Linear Regression) y 5.5.1 (Conditional Log-Likelihood and Mean Squared Error)
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