Chapter 2 // Learning from Data

Linear Regression.

If a student studies for four and a half hours, what score should we expect?

Reading time
18 min
Data

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.

StudentHours studiedExam score
A148
B466
C671
D991

Hours studied is the , the thing we know in advance. The score is the , the thing we want to predict. A table of numbers is hard to read, so plot it: one dot per student, hours across, score up.

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.

Figure

Fit the line by eye

1 hours, score 481.5 hours, score 532 hours, score 503 hours, score 603.5 hours, score 574 hours, score 665 hours, score 685.5 hours, score 756 hours, score 717 hours, score 828 hours, score 839 hours, score 91
Slope w
1.00
Bias b
63.0
Drag the two orange handles, or focus one and use the arrow keys.
Each dot is one student. Try it: drag the two orange handles until the line runs through the middle of the dots. Then read off its height above 4.5 hours.

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 ww and bb:

y^=w x+b\hat{y} = w\,x + b

predicted score = w × hours + b

Here is the input (hours), and is the prediction. The hat is there to keep it apart from , the score the student really got.

  • ww is the : how many points one extra hour is worth.
  • bb is the : the score the line gives for zero hours.

This rule, with its two adjustable numbers, is our . Different values of ww and bb give different lines, and so different predictions.

ExampleReading a prediction

Suppose someone hands us the line w=5w = 5, b=45b = 45. For a student who studied 4 hours:

y^=5×4+45=65\hat{y} = 5 \times 4 + 45 = 65

Student B studied 4 hours and scored 66, so this line is off by one point for that student.

Figure

A line turns hours into a score

1, 481.5, 532, 503, 603.5, 574, 665, 685.5, 756, 717, 828, 839, 914, 65ŷ = 65.0
Hours x
4.0
w · x + b
5 × 4.0 + 45
Predicted score ŷ
65.0
4.0
The line here is w = 5, b = 45. The faint dots are the real students. Try it: slide to 4.5 hours and read the prediction. Then slide to 0 and see what the bias means.
Checkpoint

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 is how far the line missed:

residual=y−y^\text{residual} = y - \hat{y}

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 +10+10 and a miss of −10-10 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 :

MSE=1n∑i=1n(yi−y^i)2\text{MSE} = \frac{1}{n}\sum_{i=1}^{n}\left(y_i - \hat{y}_i\right)^2

average, over all n students, of the squared miss

ExampleScoring a line on three students

Take the line w=5w = 5, b=45b = 45 and students A, B and D from the table.

StudentHoursScore yyPrediction y^\hat{y}ResidualSquared
A14850−24
B46665+11
D99190+11

The mean of the squared column is (4+1+1)/3=2(4 + 1 + 1) / 3 = 2. 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 . Lower is better. Squaring has one more effect worth noticing: a miss of 10 costs 100, while a miss of 1 costs 1. Big misses dominate.

Figure

Every miss, and their average

1 hours, score 481.5 hours, score 532 hours, score 503 hours, score 603.5 hours, score 574 hours, score 665 hours, score 685.5 hours, score 756 hours, score 717 hours, score 828 hours, score 839 hours, score 91
  • Student
  • Your line
  • Miss (residual)
Slope w
1.00
Bias b
63.0
Your error (MSE)
119.6
Best possible
?
Drag the two orange handles, or focus one and use the arrow keys.
The red dashed lines are the residuals. The error is the mean of their squares over all twelve students. Try it: get your error below 7. Then reveal the best line and see how close you came.
Checkpoint

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 : two formulas that give the best ww and bb directly. Choosing the line this way is called .

Write xˉ\bar{x} for the average of the hours and yˉ\bar{y} for the average of the scores. Then:

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

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, (xˉ,yˉ)(\bar{x}, \bar{y}).

ExampleThree points, by hand

Take the tiny dataset (1,1)(1, 1), (2,2)(2, 2), (3,2)(3, 2).

  1. Averages: xˉ=2\bar{x} = 2 and yˉ=5/3\bar{y} = 5/3.
  2. Top of the fraction: (−1)(−23)+(0)(13)+(1)(13)=1(-1)(-\tfrac{2}{3}) + (0)(\tfrac{1}{3}) + (1)(\tfrac{1}{3}) = 1.
  3. Bottom of the fraction: (−1)2+02+12=2(-1)^2 + 0^2 + 1^2 = 2.
  4. Slope: w=1/2w = 1/2. Bias: b=5/3−12×2=2/3b = 5/3 - \tfrac{1}{2}\times 2 = 2/3.

The best line is y^=0.5 x+0.67\hat{y} = 0.5\,x + 0.67.

For the twelve students the same steps give xˉ=4.625\bar{x} = 4.625, yˉ=67\bar{y} = 67, a top of 388388 and a bottom of 73.0673.06:

w=38873.06≈5.31b=67−5.31×4.625≈42.44w = \frac{388}{73.06} \approx 5.31 \qquad b = 67 - 5.31 \times 4.625 \approx 42.44

So each extra hour of study is worth about 5.3 points, and we can finally answer the opening question:

y^=5.31×4.5+42.44≈66.3\hat{y} = 5.31 \times 4.5 + 42.44 \approx 66.3
Where the formulas come from

The MSE is a function of ww and bb. Picture it as a surface: every choice of (w,b)(w, b) 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 bb direction means the derivative with respect to bb is zero:

∂ MSE∂b=−2n∑i(yi−wxi−b)=0    ⟹    b=yˉ−w xˉ\frac{\partial\,\text{MSE}}{\partial b} = -\frac{2}{n}\sum_i (y_i - w x_i - b) = 0 \;\;\Longrightarrow\;\; b = \bar{y} - w\,\bar{x}

Put that bb back into the MSE and ask for flatness in the ww direction:

∂ MSE∂w=−2n∑i(xi−xˉ)((yi−yˉ)−w(xi−xˉ))=0\frac{\partial\,\text{MSE}}{\partial w} = -\frac{2}{n}\sum_i (x_i - \bar{x})\big((y_i - \bar{y}) - w (x_i - \bar{x})\big) = 0

Solving that for ww 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.

MeasureValue hereWhat it tells you
MSE6.13The quantity we minimised. Its units are points squared, which is awkward to interpret.
RMSE2.48The square root of the MSE. A typical miss is about two and a half points.
R²0.966The line explains about 97% of the differences between students’ scores.

is the one to quote to a person, because it is in the same units as the score. Our answer to the thirteenth student is “about 66, give or take two or three points”.

compares the line with the laziest possible model: ignore the hours and predict the average score, 67, for everyone. That lazy model has an MSE of 177.8. Ours has 6.13.

R2=1−6.13177.8≈0.966R^2 = 1 - \frac{6.13}{177.8} \approx 0.966

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 5.31×12+42.44≈1065.31 \times 12 + 42.44 \approx 106, on an exam marked out of 100. Predicting outside the range of the data is called , and the line has no evidence to stand on there.

Checkpoint

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 , can pull the whole line toward themselves.

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.

Figure

Squared error chases outliers

1 hours, score 481.5 hours, score 532 hours, score 503 hours, score 603.5 hours, score 574 hours, score 665 hours, score 685.5 hours, score 756 hours, score 717 hours, score 828 hours, score 83
  • Least squares
  • Least absolute error
  • Movable student
Slope before
5.31
Least squares slope
5.31
Least absolute slope
5.38
Drag the large dark dot anywhere.
Both lines are refitted every time the point moves. The solid line minimises squared error; the dashed line minimises absolute error. Try it: drag the dark dot to the bottom right corner and watch which line follows it.

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, y^=wx+b\hat{y} = w x + b. Learning means choosing ww and bb.
  • 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 ww and bb 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.
You can now
  • 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.

Exerciseby hand

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 xˉ=2\bar{x} = 2 and yˉ=3\bar{y} = 3.

Top of the slope formula: (−2)(−2)+(0)(−1)+(2)(3)=4+0+6=10(-2)(-2) + (0)(-1) + (2)(3) = 4 + 0 + 6 = 10. Bottom: (−2)2+02+22=8(-2)^2 + 0^2 + 2^2 = 8. So w=10/8=1.25w = 10 / 8 = 1.25 and b=3−1.25×2=0.5b = 3 - 1.25 \times 2 = 0.5.

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 1.5/3=0.51.5 / 3 = 0.5 and the RMSE is 0.5≈0.71\sqrt{0.5} \approx 0.71.

Notice that the residuals add up to zero. That is always true for the best line.

Exerciseby hand

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 14/3≈4.6714 / 3 \approx 4.67.

R2=1−0.5/4.67≈0.89R^2 = 1 - 0.5 / 4.67 \approx 0.89.

The line removes about 89% of the squared error that the lazy model makes.

Exerciseby hand

The best line for the twelve students is w=5.31w = 5.31, b=42.44b = 42.44. 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 wx+bwx + b. Then look at the range of hours in the data.

Solution

For 4.5 hours: 5.31×4.5+42.44≈66.35.31 \times 4.5 + 42.44 \approx 66.3 points.

For 20 hours: 5.31×20+42.44≈148.65.31 \times 20 + 42.44 \approx 148.6 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.

Exercisein code

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.48

polyfit uses the same least-squares calculation as the formula in this chapter.

Exercisewith the figure

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: 1−6.13/177.8≈0.9661 - 6.13 / 177.8 \approx 0.966. 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, y^=w1x1+w2x2+⋯+wdxd+b\hat{y} = w_1 x_1 + w_2 x_2 + \dots + w_d x_d + b, and the “line” becomes a flat sheet in more dimensions. Stack the examples into a table XX 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:

w=(X⊤X)−1X⊤yw = (X^\top X)^{-1} X^\top y

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

Last updated Spotted a mistake? Suggest an editWhat changed

In this chapter
  1. Top of the chapter
  2. 2.1Twelve students
  3. 2.2The model is a line
  4. 2.3Measuring the miss
  5. 2.4The best line, exactly
  6. 2.5How good is the fit?
  7. 2.6One wild point
  8. 2.7In code
  9. Exercises
Search

    The Book of Machine Learning
    Search
    Reading settings
    Text size
    Colours

    Saved in this browser only.

    Keyboard shortcuts
    /
    Search the book
    ← →
    Previous and next chapter
    g
    Glossary
    c
    Table of contents
    e
    Jump to the exercises
    t
    Reading settings
    ?
    Show this list
    Esc
    Close a window or pop-in