Twelve students sat the same exam. Before it, each one wrote down how many hours they had studied. We have both numbers for all twelve, and a thirteenth student who studied for four and a half hours and wants to know what to expect.
By the end of this chapter you will be able to answer that with a number, say how far off the answer is likely to be, and explain exactly where the number came from.
Twelve students
Here are four of the twelve rows. The full table has the same two columns.
| Student | Hours studied | Exam score |
|---|---|---|
| A | 1 | 48 |
| B | 4 | 66 |
| C | 6 | 71 |
| D | 9 | 91 |
Hours studied is the
The dots drift upward from left to right. More hours, higher score, roughly in a straight band. That suggests a simple plan: draw a straight line through the band, and read predictions off the line.
Fit the line by eye
- Slope w
- 1.00
- Bias b
- 63.0
You probably landed on something sensible within a few seconds. The rest of this chapter turns what your eye just did into a procedure a computer can follow.
The model is a line
A straight line is fixed by two numbers. Call them and :
predicted score = w × hours + b
Here
- is the
: how many points one extra hour is worth. - is the
: the score the line gives for zero hours.
This rule, with its two adjustable numbers, is our
Suppose someone hands us the line , . For a student who studied 4 hours:
Student B studied 4 hours and scored 66, so this line is off by one point for that student.
A line turns hours into a score
- Hours x
- 4.0
- w · x + b
- 5 × 4.0 + 45
- Predicted score ŷ
- 65.0
With w = 5 and b = 45, a student studies two more hours than a classmate. How much higher is their predicted score?
Measuring the miss
Many lines look reasonable. To pick one we need a way to score a line, so that “better” means something exact.
Start with one student. The
A positive residual means the student did better than the line said. A negative one means worse.
To score the whole line we need to combine twelve residuals into one number. Simply adding them fails, because a miss of and a miss of would cancel to zero and a terrible line could look perfect. So we square each residual first, then take the average. The result is the
average, over all n students, of the squared miss
Take the line , and students A, B and D from the table.
| Student | Hours | Score | Prediction | Residual | Squared |
|---|---|---|---|---|---|
| A | 1 | 48 | 50 | −2 | 4 |
| B | 4 | 66 | 65 | +1 | 1 |
| D | 9 | 91 | 90 | +1 | 1 |
The mean of the squared column is . On these three students, this line has an MSE of 2.
A number like this, which says how wrong a model is, is called a
Every miss, and their average
- Student
- Your line
- Miss (residual)
- Slope w
- 1.00
- Bias b
- 63.0
- Your error (MSE)
- 119.6
- Best possible
- ?
A line predicts 70 for a student who scored 64. What does this student add to the sum of squared residuals?
The best line, exactly
In the last figure you searched for the lowest error by hand. For a straight line and squared error there is no need to search. There is a
Write for the average of the hours and for the average of the scores. Then:
slope = how x and y vary together, divided by how much x varies on its own
The second formula says something useful in plain words: the best line always passes through the point of averages, .
Take the tiny dataset , , .
- Averages: and .
- Top of the fraction: .
- Bottom of the fraction: .
- Slope: . Bias: .
The best line is .
For the twelve students the same steps give , , a top of and a bottom of :
So each extra hour of study is worth about 5.3 points, and we can finally answer the opening question:
Where the formulas come from
The MSE is a function of and . Picture it as a surface: every choice of has a height, the error of that line. For squared error this surface is a smooth bowl, so its lowest point is where it is flat in both directions.
Flat in the direction means the derivative with respect to is zero:
Put that back into the MSE and ask for flatness in the direction:
Solving that for gives the fraction above. If derivatives are new to you, the toolkit chapter on derivatives covers everything used here.
How good is the fit?
The best line is still not a perfect line. Three numbers describe how well it does, each answering a slightly different question.
| Measure | Value here | What it tells you |
|---|---|---|
| MSE | 6.13 | The quantity we minimised. Its units are points squared, which is awkward to interpret. |
| RMSE | 2.48 | The square root of the MSE. A typical miss is about two and a half points. |
| R² | 0.966 | The line explains about 97% of the differences between students’ scores. |
An R² of 1 means a perfect fit and 0 means no better than the average. It can even be negative, when a model does worse than the average.
One warning before trusting the line too far. Our students studied between 1 and 9 hours. For 12 hours the line predicts , on an exam marked out of 100. Predicting outside the range of the data is called
A different model for the same exam has an RMSE of 9 points. What does that mean?
One wild point
Squaring makes big misses count much more than small ones. That has a cost. A single student far from the pattern, an
Imagine the student who studied 9 hours fell ill on the day and scored 35. Least squares will tilt the line a long way to reduce that one enormous squared miss, and every other prediction gets worse to pay for it.
One alternative is to average the absolute misses instead of the squared ones. A miss of 10 then costs 10, not 100, so no single student can dominate.
Squared error chases outliers
- Least squares
- Least absolute error
- Movable student
- Slope before
- 5.31
- Least squares slope
- 5.31
- Least absolute slope
- 5.38
Neither choice is always right. Squared error is smooth and has an exact formula, which is why it is the default. Absolute error is sturdier when the data contains mistakes or freak results. The first thing to do with a surprising fit is to plot the data and look for a point like this.
In code
In practice nobody computes the two formulas by hand. Here is the whole chapter in a few lines of Python, using the scikit-learn library.
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
hours = np.array([1, 1.5, 2, 3, 3.5, 4, 5, 5.5, 6, 7, 8, 9])
score = np.array([48, 53, 50, 60, 57, 66, 68, 75, 71, 82, 83, 91])
X = hours.reshape(-1, 1) # one row per student, one column per feature
model = LinearRegression().fit(X, score)
print(model.coef_[0], model.intercept_) # 5.31 42.44
pred = model.predict(X)
print(mean_squared_error(score, pred)) # 6.13
print(r2_score(score, pred)) # 0.966
print(model.predict([[4.5]])) # [66.34]
The numbers match the ones we worked out, because fit is doing exactly the calculation from this chapter.
Key Takeaways
- A linear model predicts with a straight line, . Learning means choosing and .
- A residual is one miss. The mean squared error combines all the misses into a single loss.
- For a line and squared error, the best and come from a formula. No searching is needed.
- Report RMSE for a typical miss in real units, and R² for how much better the line is than guessing the average.
- Squared error is sensitive to outliers, and no line should be trusted outside the range of its data.
- Turn an input into a prediction with a line, and say what the slope and bias mean.
- Work out residuals and the mean squared error by hand.
- Find the best line for a small dataset with the formula.
- Report how good a fit is with RMSE and R², and say what each number means.
Exercises
Try each one before opening its solution. Getting stuck for a few minutes is where most of the learning happens.
Three points: (0, 1), (2, 2) and (4, 6). Use the formula to find the best line. Then work out its three residuals, its MSE and its RMSE.
Hint
Start with the two averages. The slope is the sum of products of distances, divided by the sum of squared x distances.
Solution
The averages are and .
Top of the slope formula: . Bottom: . So and .
The line predicts 0.5, 3 and 5.5. The residuals (true minus predicted) are 0.5, −1 and 0.5. Squared: 0.25, 1 and 0.25. The MSE is and the RMSE is .
Notice that the residuals add up to zero. That is always true for the best line.
For the same three points, work out R². Start with the MSE of the lazy model that predicts the average for everyone.
Hint
R² is 1 minus the line’s MSE divided by the lazy model’s MSE.
Solution
The lazy model predicts 3 every time. Its misses are −2, −1 and 3, which squared are 4, 1 and 9. Its MSE is .
.
The line removes about 89% of the squared error that the lazy model makes.
The best line for the twelve students is , . What does it predict for 4.5 hours of study? For 20 hours? What is wrong with the second answer?
Hint
Put each number of hours into . Then look at the range of hours in the data.
Solution
For 4.5 hours: points.
For 20 hours: points, on an exam marked out of 100.
Nobody in the data studied for more than 9 hours, so the line has no evidence about what happens at 20. It keeps climbing because a line is all it knows how to be. Real scores level off as they approach 100. This is extrapolation, and the model gives no warning when you do it.
Fit a line to the twelve students with NumPy and check that you get the numbers from the chapter. Hours: 1, 1.5, 2, 3, 3.5, 4, 5, 5.5, 6, 7, 8, 9. Scores: 48, 53, 50, 60, 57, 66, 68, 75, 71, 82, 83, 91.
Hint
np.polyfit(hours, scores, 1) returns the slope and then the bias.
Solution
import numpy as np
hours = np.array([1, 1.5, 2, 3, 3.5, 4, 5, 5.5, 6, 7, 8, 9])
scores = np.array([48, 53, 50, 60, 57, 66, 68, 75, 71, 82, 83, 91])
w, b = np.polyfit(hours, scores, 1) # a polynomial of degree 1 is a line
print(round(w, 2), round(b, 2)) # 5.31 42.44
predicted = w * hours + b
rmse = np.sqrt(np.mean((scores - predicted) ** 2))
print(round(rmse, 2)) # 2.48polyfit uses the same least-squares calculation as the formula in this chapter.
In the figure “Every miss, and their average”, make the line flat at the average score, about 67. Read the error. Then tilt the line until the error is as low as you can get it, and reveal the best line. How do your three numbers compare with the R² of 0.966 in the chapter?
Hint
A flat line at the average is the “lazy model” that R² measures against.
Solution
The flat line at 67 has an error of about 178. That is the lazy model’s MSE. The best line has an error of about 6.1.
R² is one minus the ratio of the two: . You have just measured both halves of that formula by hand. Any line you set by eye lands between the two, usually much nearer the best, because the eye is good at this.
Going further
More than one feature
Real problems have several features: hours studied, hours slept, previous grade. The model gets one weight per feature, , and the “line” becomes a flat sheet in more dimensions. Stack the examples into a table with one row per student (the toolkit chapter on vectors and matrices explains this notation), and the best weights still have a closed form, called the normal equation:
It is the same idea as the two formulas above, written for any number of features.
Why squares, really?
Squaring is convenient, but there is a deeper reason. If the scores are a straight line plus random bell-shaped noise, then the least-squares line is also the most probable line given the data. The probability toolkit chapter has the background.
What the line assumes
A straight line is the right tool when the relationship really is straight, when the scatter around it is about the same everywhere, and when the examples do not influence each other. Plotting the residuals against the input is the quickest check: they should look like a shapeless cloud around zero.
References and further reading
- G. James, D. Witten, T. Hastie and R. Tibshirani, An Introduction to Statistical Learning, chapter 3. Free at statlearning.com.
- T. Ma and A. Ng, CS229 Lecture Notes, part I, cs229.stanford.edu.
- MLU-Explain, Linear Regression, an interactive article.