Asiman Data School

Module 3, topic 22, week 11, Thursday

Linear Regression: theory and implementation

The first model of machine learning: a line through points, the residuals and the loss function, the best line by formulas and by gradient descent, MSE, RMSE, MAE and R², several features, and all of it again in Python with scikit-learn. Mathematics by hand and code.

Introduction: the first model

The second lesson of Module 3, and the first model. In Topic 21 you saw the map of machine learning: supervised learning, and inside it regression, the task of predicting a number. Linear regression is the oldest and simplest model for that task, and almost every idea of this module appears in it for the first time: a model with parameters, a loss function that measures how wrong the model is, an algorithm that makes the loss small, and a number that says how good the result is.

This guide starts with the mathematics. It draws dots and a line, measures the distances between them, and builds the loss function from those distances. Then it finds the best line in two ways: with the formulas of Topic 20, and with gradient descent, the method that trains almost every model of modern machine learning. It explains how to judge a line (MSE, RMSE, MAE and the R² score), moves from one feature to many (multiple linear regression), and then does everything again in Python with scikit-learn. After the theory there are 26 solved problems and 30 practice problems, half of them worked by hand and half written in code, and 12 check-yourself questions.

You need: the mean and the deviations from it (Topic 18), covariance, correlation and the first look at the regression line (Topic 20), the dot product and matrices (Topics 13 and 14), NumPy arrays (Topics 8 and 9), Matplotlib (Topic 12), and the words of Topic 21: feature, target, model, training, fit and predict.

What you will learn

  1. 1.What linear regression is, what it does, and when it is the right model
  2. 2.The equation of the line: the intercept w0w_0 and the slope w1w_1, and how to read them
  3. 3.Residuals: the vertical distances between the points and the line
  4. 4.The loss function: why the squared distances are added, SSE and MSE
  5. 5.The least-squares formulas for the best line, and why the best line passes through the point of the means
  6. 6.The idea of a gradient and of gradient descent: the learning rate, the steps, and what can go wrong
  7. 7.How to measure a regression model: MSE, RMSE, MAE and the R² score
  8. 8.Multiple linear regression: several features, the formula with a dot product and with matrices, and how to read the weights
  9. 9.Linear regression in Python: NumPy arrays, LinearRegression, fit, predict, coef_, intercept_, score, and the functions of sklearn.metrics
  10. 10.The limits of the model: curves, outliers, predictions outside the data, and correlation without causation
Notation used in this lesson
WrittenMeaning
xxthe feature (the input): hours of study, the area of a flat
yythe target (the true answer): the mark, the price
y^\hat{y}"y hat": the prediction of the model
nnthe number of samples (points)
xˉ\bar{x}, yˉ\bar{y}the means of xx and of yy
w0w_0the intercept (also called the bias): the prediction for x=0x = 0
w1w_1the slope (also called the weight or the coefficient): the change of y^\hat{y} when xx grows by 1
eethe residual of a point: e=y−y^e = y - \hat{y}
SSEthe sum of the squared residuals (sum of squared errors)
MSE, RMSE, MAEthe mean squared error, its square root, and the mean absolute error
SSTthe total sum of squares: the squared distances of the yy values from their mean
R2R^2the R² score (coefficient of determination): the share of the variation that the model explains
α\alphathe learning rate of gradient descent (the Greek letter alpha)
XX, w\mathbf{w}the matrix of the features and the vector of the weights (multiple regression)

In Topic 20 the line was written y^=a+bx\hat{y} = a + bx. It is the same line with other letters: aa is w0w_0 and bb is w1w_1. Books of statistics write β0\beta_0 and β1\beta_1. Machine learning writes ww for "weight", because the same letters continue to work when there are many features: w1w_1, w2w_2, w3w_3, and so on.

1What is linear regression?

1.1The task

Five students prepared for an exam. This is how long each one studied and the mark each one got:

The five students
Student12345
Hours of study xx24568
Mark yy5060657580

A sixth student studied 7 hours. What mark do you expect?

Nobody with 7 hours is in the table, so the answer cannot be looked up. But the table has a clear pattern: more hours, a higher mark, and the points lie almost on a straight line. If we draw that line, we can read off a mark for 7 hours, and for any other number of hours.

246850607080hours of studymark7 hours: 76.5
The five students as dots, and the line that linear regression finds from them. For a new student with 7 hours of study the prediction is read off the line: 76.5.

Linear regression is the model that does exactly this:

  1. It takes points whose answers are known (the training data).
  2. It finds the straight line that fits those points best.
  3. It uses the line to predict the answer for new points.

"Regression" means that the answer is a number (Topic 21). "Linear" means that the model is a straight line: the prediction changes by the same amount for every extra unit of the feature.

1.2Where it is used

  • the price of a flat from its area
  • the salary from the years of experience
  • the sales of a shop from the money spent on advertising
  • the time of a delivery from the distance
  • the fuel a car needs from its weight
  • the number of cold drinks a cafe sells from the temperature of the day

In every case two questions are answered at once. Prediction: what value do we expect for a new case? Explanation: how strongly does the target change when the feature changes? "Every extra square metre adds 1,500 to the price" is often as useful as the prediction itself.

1.3Why it is the first model of the module

  • It is simple: two numbers describe the whole model.
  • It can be calculated by hand, so nothing stays hidden.
  • It is easy to explain to a person who has never heard of machine learning.
  • It is fast, also with millions of rows.
  • It is the baseline: before a complicated model is tried, the question is always "how good is a simple line?" (Topic 21).
  • Its ideas return everywhere. Ridge and Lasso (Topic 26) are linear regression with one extra term. Logistic regression (Topic 27) is a line put through one more function. A neuron of a neural network (Module 5) is a linear regression followed by an activation function.

2The equation of the line

2.1Intercept and slope

A straight line is described by two numbers:

y^=w0+w1x\hat{y} = w_0 + w_1 x
  • w0w_0 is the intercept: the value of y^\hat{y} when x=0x = 0. It is the height at which the line crosses the vertical axis. In machine learning it is also called the bias.
  • w1w_1 is the slope: how much y^\hat{y} changes when xx grows by 1. It is also called the weight or the coefficient of the feature.
  • y^\hat{y} ("y hat") is the prediction. The hat separates what the model says (y^\hat{y}) from what really happened (yy).

The two numbers w0w_0 and w1w_1 are the parameters of the model (Topic 21). Training a linear regression means finding these two numbers.

For the five students the best line is (Part 5 shows where the numbers come from):

y^=39.75+5.25 x\hat{y} = 39.75 + 5.25\,x
024684050607080hours of studymarkintercept 39.75+1 hour+5.25 marks
The intercept 39.75 is the height of the line at 0 hours (the point in the second colour). The slope 5.25 is the rise of the line for one more hour: the small step drawn between 5 and 6 hours.

2.2Reading the two numbers

  • The slope 5.25: every extra hour of study goes with 5.25 more marks, on average. Two extra hours: 2×5.25=10.52 \times 5.25 = 10.5 more marks.
  • The intercept 39.75: a student who does not study at all (x=0x = 0) is predicted to get 39.75. Be careful with this number. Nobody in the data studied 0 hours, so it lies outside what the model has seen. Often the intercept is only the number that puts the line at the right height, and has no meaning of its own. (The "price of a flat with 0 square metres" means nothing.)

2.3Making a prediction

Put the value of the feature into the equation:

x=7:y^=39.75+5.25×7=39.75+36.75=76.5x=3:y^=39.75+5.25×3=39.75+15.75=55.5\begin{aligned} x = 7:\quad \hat{y} &= 39.75 + 5.25 \times 7 \\ &= 39.75 + 36.75 = 76.5 \\[6pt] x = 3:\quad \hat{y} &= 39.75 + 5.25 \times 3 \\ &= 39.75 + 15.75 = 55.5 \end{aligned}

2.4The sign of the slope

The sign of the slope
SlopeThe lineMeaningExample
w1>0w_1 > 0risesmore xx, more yyhours of study and the mark
w1<0w_1 < 0fallsmore xx, less yythe age of a car and its price
w1=0w_1 = 0is flatxx tells nothing about yythe shoe size and the mark

The slope has the same sign as the correlation coefficient rr of Topic 20. But they are different numbers: rr has no units and always lies between −1-1 and 11, while the slope has units ("marks per hour") and can be any number.

Try it yourself

A model is y^=15+4x\hat{y} = 15 + 4x. (a) Find the prediction for x=6x = 6. (b) By how much does the prediction grow when xx grows by 3? (c) What does the model predict for x=0x = 0?

Show a hint
The slope is the change for one unit of xx. The prediction at x=0x = 0 is the intercept.
Show the solution

Answer: (a) 39; (b) 12; (c) 15.

(a)y^=15+4×6=15+24=39(b)3×4=12(c)y^=15+4×0=15\begin{aligned} \text{(a)}\quad \hat{y} &= 15 + 4 \times 6 = 15 + 24 = 39 \\[4pt] \text{(b)}\quad & 3 \times 4 = 12 \\[4pt] \text{(c)}\quad \hat{y} &= 15 + 4 \times 0 = 15 \end{aligned}

The slope 4 is the change for one unit, so three units give three times as much. At x=0x = 0 only the intercept is left.

3Residuals, the distances between the points and the line

3.1No line passes through all the points

Real points never lie exactly on a line. A student who studied 6 hours got 75, although the line says 71.25. The line cannot hit every point, so the question becomes: how far is the line from the points?

For one point, the distance is measured vertically: the true value minus the predicted value. This difference is the residual (also called the error) of the point:

e=y−y^e = y - \hat{y}
  • e>0e > 0: the point lies above the line. The model predicted too little.
  • e<0e < 0: the point lies below the line. The model predicted too much.
  • e=0e = 0: the point lies exactly on the line.
246850607080hours of studymark75 − 71.25 = 3.75
The residual of a point is its vertical distance from the line. The student with 6 hours got 75 and the line says 71.25: the residual is 3.75. The other four points lie a little below the line.

3.2The residuals of the five students

The residuals of the five students
Studentxxyyy^=39.75+5.25x\hat{y} = 39.75 + 5.25xe=y−y^e = y - \hat{y}
125050.25−0.25-0.25
246060.75−0.75-0.75
356566−1-1
467571.253.75
588081.75−1.75-1.75
Sum0

Four students did a little worse than the line says, and student 4 did clearly better.

3.3Why vertical?

The distance is measured straight up and down, not at a right angle to the line. The reason is the purpose of the model: we know xx and want to predict yy. An error of the model is an error in yy, so that is what we measure.

3.4The residuals cannot simply be added

The sum of the residuals in the table is 0. The positive and the negative residuals cancel each other. This is not an accident: for the best line the sum is always 0 (Part 5). So the plain sum is useless as a measure of quality. A line could be terribly wrong, with errors of +50+50 and −50-50, and the sum would still say 0. The next part repairs this.

Try it yourself

A model is y^=10+2x\hat{y} = 10 + 2x. Find the residuals of the three points (1,13)(1, 13), (3,15)(3, 15) and (5,21)(5, 21).

Show a hint
First the prediction of every point, then true minus predicted.
Show the solution

Answer: 11, −1-1 and 11.

(1,13):y^=10+2×1=12e=13−12=1(3,15):y^=10+2×3=16e=15−16=−1(5,21):y^=10+2×5=20e=21−20=1\begin{aligned} (1, 13):\quad & \hat{y} = 10 + 2 \times 1 = 12 \\ & e = 13 - 12 = 1 \\[6pt] (3, 15):\quad & \hat{y} = 10 + 2 \times 3 = 16 \\ & e = 15 - 16 = -1 \\[6pt] (5, 21):\quad & \hat{y} = 10 + 2 \times 5 = 20 \\ & e = 21 - 20 = 1 \end{aligned}

The first and the third point lie above the line, the second below it.

4The loss function

4.1One number for the whole line

To compare two lines we need one number that says how badly a line fits all the points together. Such a number is called a loss (or a cost), and the rule that calculates it is the loss function. A small loss means a good line. Training a model means: find the parameters with the smallest loss. This sentence is true for linear regression, and it stays true for every model up to the largest neural network.

4.2Squaring the residuals

The residuals cancel when they are added. Two repairs are possible: take the absolute value of each residual, or square each residual. Linear regression squares them:

SSE=∑(y−y^)2\text{SSE} = \sum (y - \hat{y})^2

SSE stands for the sum of squared errors.

Dividing by the number of points gives the average squared residual, the mean squared error:

MSE=SSEn=1n∑(y−y^)2\text{MSE} = \frac{\text{SSE}}{n} = \frac{1}{n} \sum (y - \hat{y})^2

For the line y^=39.75+5.25x\hat{y} = 39.75 + 5.25x of the five students:

The squared residuals of the five students
Studenteee2e^2
1−0.25-0.250.0625
2−0.75-0.750.5625
3−1-11
43.7514.0625
5−1.75-1.753.0625
Sum018.75
SSE=18.75MSE=18.755=3.75\text{SSE} = 18.75 \qquad \text{MSE} = \frac{18.75}{5} = 3.75

4.3Why squares?

  • Nothing cancels. A square is never negative, so every miss adds to the loss, above or below the line.
  • Large errors count much more. An error of 1 adds 1, an error of 4 adds 16. One point that is far away matters more than several points that are slightly off. The line is pulled towards a compromise in which no point is very far away.
  • The mathematics is easy. The squared loss is a smooth curve with exactly one lowest point, shaped like a bowl. That lowest point can be found with a formula (Part 5) or by walking downhill (Part 6). With absolute values the curve has a corner, and no simple formula exists.
  • It agrees with statistics. The variance of Topic 18 is also an average of squared deviations. The MSE is the same idea, with the line in the place of the mean.

The price of squaring: one unusual point, an outlier, can pull the line strongly towards itself. Part 10 comes back to this.

4.4Comparing lines

Three people draw a line through the five points. Which one is best?

Three lines through the five points
LineEquationResidualsSSEMSE
Ay^=40+5x\hat{y} = 40 + 5x0, 0, 0, 5, 00,\ 0,\ 0,\ 5,\ 0255
By^=30+7x\hat{y} = 30 + 7x6, 2, 0, 3, −66,\ 2,\ 0,\ 3,\ -68517
Cy^=39.75+5.25x\hat{y} = 39.75 + 5.25x−0.25, −0.75, −1, 3.75, −1.75-0.25,\ -0.75,\ -1,\ 3.75,\ -1.7518.753.75

Line A: SSE = 25

40 + 5 x

Line B: SSE = 85

30 + 7 x

Line C: SSE = 18.75

39.75 + 5.25 x

Three lines through the same five points, each with its residuals. Line A passes exactly through four points and has one large residual. Line C misses every point a little, and its sum of squared residuals is the smallest.

Line B is clearly the worst. Line A is interesting: it passes exactly through four of the five points, and it is still not the best line. Its single error of 5 costs 25. Line C misses every point a little and has the smaller loss. The squared loss prefers many small errors to one large error.

Line C is the best of these three. Is it the best of all possible lines? Yes, and the next two parts show two ways of finding it.

Choose the intercept w₀ and the slope w₁ yourself. How small can you make the loss?

246850607080hours of studymark

Residuals: 6, 2, 0, 3, −6

SSE = 85, MSE = 17

The best line, 39.75 + 5.25 x, has SSE = 18.75. Yours is 66.25 above it.

Try it yourself

A line has the residuals 22, −1-1, 33 and −2-2 on four points. Find its SSE and its MSE.

Show a hint
Square every residual, add the squares, then divide by the number of points.
Show the solution

Answer: SSE = 18, MSE = 4.5.

SSE=22+(−1)2+32+(−2)2=4+1+9+4=18MSE=184=4.5\begin{aligned} \text{SSE} &= 2^2 + (-1)^2 + 3^2 + (-2)^2 \\ &= 4 + 1 + 9 + 4 = 18 \\[4pt] \text{MSE} &= \frac{18}{4} = 4.5 \end{aligned}

The plain sum of these residuals is 2−1+3−2=22 - 1 + 3 - 2 = 2: it hides almost all of the error.

5Finding the best line with formulas (least squares)

5.1The idea

Among all pairs (w0,w1)(w_0, w_1) we look for the pair with the smallest SSE. The method is called least squares (or ordinary least squares, OLS), because it makes the sum of the squares as small as possible ("least").

The loss depends on two numbers, w0w_0 and w1w_1. If you draw it over all possible pairs, you get a surface shaped like a bowl. The best line is the bottom of the bowl. At the bottom the surface is flat in every direction, and this condition can be solved exactly. (For readers who know derivatives: both partial derivatives of the SSE are set to zero. Part 6 shows these derivatives.) The result is short:

w1=∑(x−xˉ)(y−yˉ)∑(x−xˉ)2w0=yˉ−w1 xˉw_1 = \frac{\sum (x - \bar{x})(y - \bar{y})}{\sum (x - \bar{x})^2} \qquad\qquad w_0 = \bar{y} - w_1\,\bar{x}

You know both from Topic 20. The top of the first fraction is the sum of the products of the deviations, the same sum as in the covariance. The bottom is the sum of the squared deviations of xx.

5.2The calculation in five steps

  1. Calculate the two means xˉ\bar{x} and yˉ\bar{y}.
  2. Calculate the deviations x−xˉx - \bar{x} and y−yˉy - \bar{y} of every point.
  3. Multiply the two deviations of every point and add the products. Square the deviations of xx and add the squares.
  4. Divide: this is the slope w1w_1.
  5. w0=yˉ−w1 xˉw_0 = \bar{y} - w_1\,\bar{x}.

5.3Example: the five students

xˉ=2+4+5+6+85=255=5yˉ=50+60+65+75+805=3305=66\begin{aligned} \bar{x} &= \frac{2 + 4 + 5 + 6 + 8}{5} = \frac{25}{5} = 5 \\[4pt] \bar{y} &= \frac{50 + 60 + 65 + 75 + 80}{5} = \frac{330}{5} = 66 \end{aligned}
The deviations of the five students
Studentxxyyx−xˉx - \bar{x}y−yˉy - \bar{y}product(x−xˉ)2(x - \bar{x})^2
1250−3-3−16-16489
2460−1-1−6-661
35650−1-100
46751991
5880314429
Sum0010520
w1=10520=5.25w0=66−5.25×5=66−26.25=39.75y^=39.75+5.25 x\begin{aligned} w_1 &= \frac{105}{20} = 5.25 \\[4pt] w_0 &= 66 - 5.25 \times 5 = 66 - 26.25 = 39.75 \\[4pt] \hat{y} &= 39.75 + 5.25\,x \end{aligned}

5.4Three facts about the least-squares line

  • It passes through the point of the means (xˉ,yˉ)(\bar{x}, \bar{y}). Check: 39.75+5.25×5=6639.75 + 5.25 \times 5 = 66. This follows directly from w0=yˉ−w1 xˉw_0 = \bar{y} - w_1\,\bar{x}.
  • Its residuals add up to 0. The line lies "in the middle" of the points: what it predicts too much for some points, it predicts too little for others.
  • It is unique. As long as the xx values are not all equal, there is exactly one best line. (If all xx are equal, ∑(x−xˉ)2=0\sum (x - \bar{x})^2 = 0, the division is impossible, and no line can be found: the points stand in a vertical column.)

5.5The slope and the correlation

Topic 20 gave a second formula for the slope:

w1=r×sysxw_1 = r \times \frac{s_y}{s_x}

where rr is the correlation coefficient and sxs_x, sys_y are the standard deviations. It gives the same number, and it shows the connection of the two lessons: the slope is the correlation, stretched by the scales of the two variables.

Try it yourself

Find the least-squares line for the three points (1,2)(1, 2), (2,3)(2, 3) and (3,7)(3, 7).

Show a hint
xˉ=2\bar{x} = 2 and yˉ=4\bar{y} = 4. The deviations of xx are −1-1, 00 and 11.
Show the solution

Answer: w1=2.5w_1 = 2.5 and w0=−1w_0 = -1, so y^=−1+2.5x\hat{y} = -1 + 2.5x.

xˉ=1+2+33=2yˉ=2+3+73=4deviations of x: −1, 0, 1deviations of y: −2, −1, 3products: 2+0+3=5squares: 1+0+1=2w1=52=2.5w0=4−2.5×2=−1\begin{aligned} & \bar{x} = \frac{1 + 2 + 3}{3} = 2 \\[4pt] & \bar{y} = \frac{2 + 3 + 7}{3} = 4 \\[4pt] & \text{deviations of } x:\ -1,\ 0,\ 1 \\[4pt] & \text{deviations of } y:\ -2,\ -1,\ 3 \\[4pt] & \text{products: } 2 + 0 + 3 = 5 \\[4pt] & \text{squares: } 1 + 0 + 1 = 2 \\[4pt] & w_1 = \frac{5}{2} = 2.5 \\[4pt] & w_0 = 4 - 2.5 \times 2 = -1 \end{aligned}

Check: at x=2x = 2 the line gives −1+5=4-1 + 5 = 4, the mean of yy.

6Finding the best line with gradient descent

6.1Why a second method?

The formulas of Part 5 are exact, and for linear regression with a few features they are all you need. But most models of machine learning have no formula for their best parameters. A neural network has millions of parameters and a loss surface far too complicated to solve. Such models are trained by a method that works for any smooth loss: gradient descent. Linear regression is the best place to learn it, because here we can compare its result with the exact answer.

6.2The idea: walk downhill

Imagine standing on a hillside in thick fog. You want to reach the lowest point of the valley, but you cannot see it. What you can feel is the ground under your feet: in which direction it goes down, and how steeply. So you take a step downhill, feel again, take another step, and repeat until the ground is flat.

Gradient descent does the same on the loss:

  1. Start with any values of the parameters.
  2. Find the slope of the loss at the place where you stand.
  3. Move the parameters a small step in the direction in which the loss goes down.
  4. Repeat until the loss stops getting smaller.

6.3The slope of the loss: the gradient

To keep the first example small, take two points, (1,2)(1, 2) and (2,4)(2, 4), and the simplest model: a line through the origin with only one parameter,

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

For every value of ww the loss can be calculated:

MSE(w)=12[(w×1−2)2+(w×2−4)2]\text{MSE}(w) = \frac{1}{2}\left[(w \times 1 - 2)^2 + (w \times 2 - 4)^2\right]
The loss for five values of w
ww01234
MSE102.502.510

The loss is a curve shaped like a bowl (a parabola), with its lowest point at w=2w = 2, where the line y^=2x\hat{y} = 2x passes through both points.

The slope of the loss curve at a value of ww says how the loss changes when ww grows a little:

  • a negative slope: the curve goes down to the right. Making ww larger makes the loss smaller.
  • a positive slope: the curve goes up to the right. Making ww smaller makes the loss smaller.
  • a slope of zero: the bottom of the bowl. Nothing can be improved.

In mathematics the slope of a curve at a point is called the derivative. For the mean squared error it is:

slope of the loss=2n∑(y^−y) x\text{slope of the loss} = \frac{2}{n} \sum (\hat{y} - y)\,x

Read it like this: for every point, take the error y^−y\hat{y} - y and multiply it by the feature xx; add the products; multiply by 2n\dfrac{2}{n}. For our two points, with y^=w x\hat{y} = w\,x:

slope=22[(w×1−2)×1+(w×2−4)×2]=(w−2)+(4w−8)=5w−10\begin{aligned} \text{slope} &= \frac{2}{2}\left[(w \times 1 - 2) \times 1 + (w \times 2 - 4) \times 2\right] \\[4pt] &= (w - 2) + (4w - 8) \\[4pt] &= 5w - 10 \end{aligned}

At w=0w = 0 the slope is −10-10: steeply downhill to the right. At w=2w = 2 it is 00: the bottom. At w=3w = 3 it is 55: uphill to the right, so the way down is to the left.

When a model has several parameters, there is one such slope for every parameter. Written together as a vector (Topic 13), they are the gradient. The gradient points in the direction in which the loss grows fastest. To make the loss smaller, we walk in the opposite direction. That is the whole meaning of the name: gradient descent.

6.4The update rule

wnew=wold−α×slopew_{\text{new}} = w_{\text{old}} - \alpha \times \text{slope}
  • The minus sign sends us downhill: a negative slope makes ww larger, a positive slope makes it smaller.
  • α\alpha (alpha) is the learning rate: a small positive number that sets the size of the step. It is a hyperparameter (Topic 21): we choose it, the model does not learn it.
  • The step is α×slope\alpha \times \text{slope}. Far from the bottom the curve is steep and the steps are large. Near the bottom the curve is flat and the steps become small by themselves.

6.5Four steps by hand

Start at w=0w = 0 with the learning rate α=0.1\alpha = 0.1:

Four steps of gradient descent
Stepwwslope 5w−105w - 10step α×slope\alpha \times \text{slope}new wwMSE at the new ww
10−10-10−1-112.5
21−5-5−0.5-0.51.50.625
31.5−2.5-2.5−0.25-0.251.750.156
41.75−1.25-1.25−0.125-0.1251.8750.039
step 1:wnew=0−0.1×(−10)=0+1=1step 2:wnew=1−0.1×(−5)=1+0.5=1.5\begin{aligned} \text{step 1:}\quad w_{\text{new}} &= 0 - 0.1 \times (-10) = 0 + 1 = 1 \\[4pt] \text{step 2:}\quad w_{\text{new}} &= 1 - 0.1 \times (-5) = 1 + 0.5 = 1.5 \end{aligned}

The loss started at 10 and falls with every step: 2.5, 0.625, 0.156, 0.039. The parameter moves towards 2, quickly at first and then more and more slowly. It never jumps to exactly 2, but after 20 steps it is 1.999998, and that is close enough for every practical purpose.

01234
The loss of the model for every value of the parameter w: a bowl with its lowest point at w = 2. The dots are four steps of gradient descent from w = 0 with the learning rate 0.1: at 1, 1.5, 1.75 and 1.875. The steps get shorter as the curve gets flatter.

6.6The learning rate

The learning rate decides whether the walk works.

Four learning rates
Learning rateThe values of wwWhat happens
α=0.01\alpha = 0.01 (too small)0, 0.1, 0.195, 0.2853, 0.371, …0,\ 0.1,\ 0.195,\ 0.2853,\ 0.371,\ \ldotsevery step is tiny; hundreds of steps are needed
α=0.1\alpha = 0.1 (good)0, 1, 1.5, 1.75, 1.875, …0,\ 1,\ 1.5,\ 1.75,\ 1.875,\ \ldotsfast and steady
α=0.4\alpha = 0.4 (too large)0, 4, 0, 4, 0, …0,\ 4,\ 0,\ 4,\ 0,\ \ldotsevery step jumps over the bottom to the other side, for ever
α=0.5\alpha = 0.5 (much too large)0, 5, −2.5, 8.75, −8.125, …0,\ 5,\ -2.5,\ 8.75,\ -8.125,\ \ldotsevery jump lands further away: the loss grows without limit
−20246

Too small: 0.01

eight steps, and hardly any progress

−20246

Good: 0.1

six steps, almost at the bottom

−20246

Too large: 0.5

every step lands further away

The same curve and the same start, w = 0, with three learning rates. With 0.01 the steps are tiny. With 0.1 the walk reaches the bottom quickly. With 0.5 every step jumps over the bottom and lands higher on the other side: the loss grows.

There is no formula for the best learning rate. In practice people try a few values (0.1, 0.01, 0.001) and watch the loss: it must go down, step after step. A loss that jumps up and down or grows means that the learning rate is too large.

Gradient descent on the loss of the model w · x for the points (1, 2) and (2, 4). Choose the learning rate α, then walk.

−20246

Steps: 0, w = 0, slope of the loss = −10, loss = 10

The lowest point is w = 2, where the loss is 0. Below α = 0.2 the walk comes closer with every step. At α = 0.2 one step is enough. Between 0.2 and 0.4 it jumps over the bottom and still comes closer. At α = 0.4 it jumps between 0 and 4 for ever, and above that it runs away.

6.7Two parameters: the real line

For the line y^=w0+w1x\hat{y} = w_0 + w_1 x there are two slopes, one for each parameter:

slope for w0=2n∑(y^−y)slope for w1=2n∑(y^−y) x\begin{aligned} \text{slope for } w_0 &= \frac{2}{n} \sum (\hat{y} - y) \\[4pt] \text{slope for } w_1 &= \frac{2}{n} \sum (\hat{y} - y)\,x \end{aligned}

and both parameters are updated in every step, at the same time:

w0←w0−α×(slope for w0)w1←w1−α×(slope for w1)\begin{aligned} w_0 &\leftarrow w_0 - \alpha \times (\text{slope for } w_0) \\[4pt] w_1 &\leftarrow w_1 - \alpha \times (\text{slope for } w_1) \end{aligned}

The picture is now a bowl over a plane, and the walk goes down its side to the bottom. Part 9 runs these four lines in Python for the five students and arrives at 39.75 and 5.25, the numbers of the formulas.

Notice what happens at the bottom of the bowl. Both slopes are zero there:

∑(y^−y)=0and∑(y^−y) x=0\sum (\hat{y} - y) = 0 \qquad \text{and} \qquad \sum (\hat{y} - y)\,x = 0

The first equation says that the residuals add up to zero. Solving the two equations for w0w_0 and w1w_1 gives exactly the formulas of Part 5. The two methods look for the same point: the formulas jump to it, gradient descent walks to it.

6.8Formulas or gradient descent?

Formulas or gradient descent?
The formulas (least squares)Gradient descent
Resultexact, in one calculationapproximate, after many steps
Settingsnonethe learning rate, the number of steps, the starting values
Works forlinear regressionalmost every model, also neural networks
Very many features or rowsbecomes slow and needs much memorystays usable
In scikit-learnLinearRegressionSGDRegressor, and the training of neural networks

LinearRegression of scikit-learn uses the exact method. You will still meet gradient descent again and again: in logistic regression (Topic 27), in gradient boosting (Topics 37 and 38), and in every neural network of Modules 4 and 5.

Try it yourself

Two points, (1,1)(1, 1) and (2,2)(2, 2), and the model y^=w x\hat{y} = w\,x. The slope of the loss is 5w−55w - 5. Start at w=3w = 3 with the learning rate α=0.1\alpha = 0.1. (a) What is the slope at w=3w = 3? (b) What is ww after one step? (c) And after two steps?

Show a hint
wnew=wold−0.1×slopew_{\text{new}} = w_{\text{old}} - 0.1 \times \text{slope}. A positive slope makes ww smaller.
Show the solution

Answer: (a) 10; (b) 2; (c) 1.5.

(a)5×3−5=10(b)w=3−0.1×10=2(c)slope=5×2−5=5w=2−0.1×5=1.5\begin{aligned} \text{(a)}\quad & 5 \times 3 - 5 = 10 \\[4pt] \text{(b)}\quad & w = 3 - 0.1 \times 10 = 2 \\[4pt] \text{(c)}\quad & \text{slope} = 5 \times 2 - 5 = 5 \\ & w = 2 - 0.1 \times 5 = 1.5 \end{aligned}

Both points lie on the line y^=x\hat{y} = x, so the lowest point is w=1w = 1. The walk starts above it, the slope is positive, and every step makes ww smaller.

7How good is the line? MSE, RMSE, MAE and R²

The best line is not automatically a good line. If the points are a shapeless cloud, the best line through them is still useless. We need numbers that say how well the model fits. There are two kinds: measures of the size of the errors (MSE, RMSE, MAE) and a measure of the share of the variation that is explained (R²).

7.1MSE: the mean squared error

MSE=1n∑(y−y^)2\text{MSE} = \frac{1}{n} \sum (y - \hat{y})^2

It is the loss function of Part 4, used now as a measure of quality. For the five students: MSE=18.755=3.75\text{MSE} = \dfrac{18.75}{5} = 3.75.

  • The smaller, the better. MSE=0\text{MSE} = 0 means that every point lies on the line.
  • Large errors are punished strongly, because of the square.
  • Its weakness: the unit is squared. The marks are in points, the MSE is in "points squared". The number 3.75 cannot be compared directly with a mark.

7.2RMSE: the root of the MSE

RMSE=MSE\text{RMSE} = \sqrt{\text{MSE}}

Taking the square root brings the unit back. For the students: RMSE=3.75=1.9365\text{RMSE} = \sqrt{3.75} = 1.9365.

Now the sentence is easy: the predictions are off by about 1.9 marks, on a typical student. The RMSE is the number that is most often reported for a regression model. It is to the residuals what the standard deviation of Topic 18 is to the deviations from the mean.

7.3MAE: the mean absolute error

MAE=1n∑∣y−y^∣\text{MAE} = \frac{1}{n} \sum \lvert y - \hat{y} \rvert

The other repair of Part 4: absolute values in the place of squares. For the students:

MAE=0.25+0.75+1+3.75+1.755=7.55=1.5\begin{aligned} \text{MAE} &= \frac{0.25 + 0.75 + 1 + 3.75 + 1.75}{5} \\[4pt] &= \frac{7.5}{5} = 1.5 \end{aligned}

The MAE is the plain average distance between prediction and truth. It treats all errors alike, so one large error does not dominate it. The RMSE is never smaller than the MAE, and the two are equal only when all errors have the same size. A RMSE that is much larger than the MAE is a sign that a few predictions are far off.

7.4R²: the share of the variation explained

MSE, RMSE and MAE depend on the units. An RMSE of 1.9 is excellent for marks out of 100 and terrible for marks out of 5. The R² score (the coefficient of determination) has no units. It compares the model with the simplest possible competitor.

The competitor: always predict the mean. Suppose you know nothing about the hours. The best single guess for every student is then the mean mark, yˉ=66\bar{y} = 66. The squared errors of this guess add up to the total sum of squares:

SST=∑(y−yˉ)2\text{SST} = \sum (y - \bar{y})^2

For the students:

SST=(−16)2+(−6)2+(−1)2+92+142=256+36+1+81+196=570\begin{aligned} \text{SST} &= (-16)^2 + (-6)^2 + (-1)^2 + 9^2 + 14^2 \\[4pt] &= 256 + 36 + 1 + 81 + 196 = 570 \end{aligned}

The model: predict with the line. Its squared errors add up to SSE=18.75\text{SSE} = 18.75.

The line reduces the squared error from 570 to 18.75. R² is the share that was removed:

R2=1−SSESSTR^2 = 1 - \frac{\text{SSE}}{\text{SST}}
R2=1−18.75570=1−0.0329=0.9671R^2 = 1 - \frac{18.75}{570} = 1 - 0.0329 = 0.9671

The hours of study explain about 96.7 percent of the variation of the marks. The other 3.3 percent is what the line cannot explain: talent, sleep, luck.

246850607080hours of studymark

Always the mean: SST = 570

246850607080hours of studymark

The line: SSE = 18.75

Left: without a model, every prediction is the mean mark 66, and the squared distances add up to SST = 570. Right: with the line, the squared distances add up to SSE = 18.75. R² is the share of the 570 that the line removed.

7.5Reading R²

Reading R²
R2R^2Meaning
1every point lies on the line: SSE=0\text{SSE} = 0
0.9671the line removes 96.71 percent of the squared error of "always the mean"
0the model is exactly as good as always predicting the mean
below 0the model is worse than always predicting the mean

Facts to remember:

  • R² is not a percentage of right answers. A regression model has no "right" and "wrong" answers. R2=0.97R^2 = 0.97 does not mean "97 percent correct".
  • For a line with one feature, R² is the square of the correlation coefficient. In Topic 20 the students had r=0.9834r = 0.9834, and 0.98342=0.96710.9834^2 = 0.9671. That is where the name comes from.
  • R² can be negative. The least-squares line never does worse than the mean on its own training data, so there R² lies between 0 and 1. But a bad line, or a model judged on new data, can be worse than the mean. The line y^=100−5x\hat{y} = 100 - 5x has SSE=2525\text{SSE} = 2525 on the five students, and R2=1−2525570=−3.43R^2 = 1 - \dfrac{2525}{570} = -3.43.
  • What counts as a good R² depends on the subject. In physics 0.99 is normal. For human behaviour 0.3 can be a valuable result.
  • A high R² does not prove that a line is the right shape. Part 10 shows a curve with R2=0.95R^2 = 0.95.
  • Adding features never lowers R² on the training data, even when the new feature is nonsense. Topic 23 comes back to this.

7.6The four measures side by side

The four measures side by side
MeasureFormulaUnitBest valueUse it to say
MSE1n∑(y−y^)2\frac{1}{n} \sum (y - \hat{y})^2the unit of yy, squared0this is what training makes small
RMSEMSE\sqrt{\text{MSE}}the unit of yy0"the predictions are off by about ..."
MAE1n∑∣y−y^∣\frac{1}{n} \sum \lvert y - \hat{y} \rvertthe unit of yy0the plain average error, less moved by outliers
R2R^21−SSESST1 - \frac{\text{SSE}}{\text{SST}}none1"the model explains ... percent of the variation"

A good report gives one error in the unit of the target (RMSE or MAE) and R². The first says how large the mistakes are, the second how much better the model is than no model.

The five students studied 2, 4, 5, 6 and 8 hours. Move their marks and watch the line and its measures.

246850607080hours of studymark

Line: 39.75 + 5.25 x

SSE = 18.75, SST = 570, RMSE = 1.94

R² = 0.9671

Put the marks on a straight line and R² becomes 1. Mix them up, high marks for few hours and low marks for many, and R² falls towards 0.

Try it yourself

A model for three points has SSE=12\text{SSE} = 12, and the data has SST=48\text{SST} = 48. Find the MSE, the RMSE and R².

Show a hint
MSE=SSE/n\text{MSE} = \text{SSE} / n with n=3n = 3, and R2=1−SSE/SSTR^2 = 1 - \text{SSE} / \text{SST}.
Show the solution

Answer: MSE = 4, RMSE = 2, R2=0.75R^2 = 0.75.

MSE=123=4RMSE=4=2R2=1−1248=1−0.25=0.75\begin{aligned} \text{MSE} &= \frac{12}{3} = 4 \\[4pt] \text{RMSE} &= \sqrt{4} = 2 \\[4pt] R^2 &= 1 - \frac{12}{48} = 1 - 0.25 = 0.75 \end{aligned}

The predictions are off by about 2 units, and the model removes three quarters of the squared error of "always the mean".

8Multiple linear regression

8.1More than one feature

The price of a flat does not depend on its area alone. The number of rooms matters, and the age of the building, and the floor. Simple linear regression uses one feature. Multiple linear regression uses several, and gives each one its own weight:

y^=w0+w1x1+w2x2+⋯+wpxp\hat{y} = w_0 + w_1 x_1 + w_2 x_2 + \dots + w_p x_p
  • x1,x2,…,xpx_1, x_2, \dots, x_p are the pp features of one sample.
  • w1,w2,…,wpw_1, w_2, \dots, w_p are their weights (coefficients).
  • w0w_0 is the intercept.

Simple linear regression is the special case p=1p = 1.

8.2Example: the price of a flat

Suppose a model has learned this equation (prices in thousands):

price=20+1.5×area+10×rooms−0.8×age\begin{aligned} \text{price} = 20 &+ 1.5 \times \text{area} \\ &+ 10 \times \text{rooms} - 0.8 \times \text{age} \end{aligned}

A flat with 80 m², 3 rooms, in a building that is 10 years old:

price=20+1.5×80+10×3−0.8×10=20+120+30−8=162\begin{aligned} \text{price} &= 20 + 1.5 \times 80 + 10 \times 3 - 0.8 \times 10 \\[4pt] &= 20 + 120 + 30 - 8 = 162 \end{aligned}

8.3Reading the weights

Every weight says how the prediction changes when its feature grows by 1 and the other features stay the same:

  • 1.51.5: one more square metre adds 1.5 thousand, for flats with the same number of rooms and the same age.
  • 1010: one more room adds 10 thousand, for the same area and age.
  • −0.8-0.8: every year of age takes away 0.8 thousand.

The words "and the other features stay the same" matter. In a simple regression of the price on the rooms alone, the weight of the rooms would be much larger, because flats with more rooms are also bigger, and the rooms would collect the effect of the area too. In the multiple regression the area has its own weight, and the weight of the rooms shows only what a room adds beyond the area.

Two warnings:

  • The sizes of the weights cannot be compared directly. The weight 10 of the rooms is larger than the weight 1.5 of the area, but an area changes by tens of square metres and the rooms by one or two. To compare the importance of features, they must first be brought to the same scale. That is the subject of Topic 24.
  • A weight is not a cause. It describes how the price moves together with the feature in this data.

8.4With a dot product

Put the features of one flat into a vector, and the weights into another one (Topic 13):

x=(80, 3, 10)w=(1.5, 10, −0.8)y^=w0+w⋅x=20+(1.5×80+10×3+(−0.8)×10)=20+142=162\begin{aligned} \mathbf{x} &= (80,\ 3,\ 10) \qquad \mathbf{w} = (1.5,\ 10,\ -0.8) \\[4pt] \hat{y} &= w_0 + \mathbf{w} \cdot \mathbf{x} \\[4pt] &= 20 + \bigl(1.5 \times 80 + 10 \times 3 + (-0.8) \times 10\bigr) \\[4pt] &= 20 + 142 = 162 \end{aligned}

A prediction of a linear model is a dot product plus the intercept. That is the reason for the name "weights": every feature is weighted and the results are added.

8.5With matrices

For many flats at once, write the features into a matrix XX with one row for every flat (Topic 14). To include the intercept, add a first column of ones, so that w0w_0 is multiplied by 1 in every row:

X=[1x11x12⋯x1p1x21x22⋯x2p⋮⋮⋮⋮1xn1xn2⋯xnp]X = \begin{bmatrix} 1 & x_{11} & x_{12} & \cdots & x_{1p} \\ 1 & x_{21} & x_{22} & \cdots & x_{2p} \\ \vdots & \vdots & \vdots & & \vdots \\ 1 & x_{n1} & x_{n2} & \cdots & x_{np} \end{bmatrix}
w=[w0w1⋮wp]y^=Xw\mathbf{w} = \begin{bmatrix} w_0 \\ w_1 \\ \vdots \\ w_p \end{bmatrix} \qquad \hat{\mathbf{y}} = X\mathbf{w}

One matrix multiplication gives all nn predictions. This is the shape (n,p)(n, p) of the table X that scikit-learn expects (Topic 21): nn rows, pp columns.

8.6The best weights

The loss is the same as before:

MSE=1n∑(y−y^)2\text{MSE} = \frac{1}{n} \sum (y - \hat{y})^2

and the best weights are again the ones that make it smallest. The formulas of Part 5 become one formula with matrices, the normal equation:

w=(XTX)−1XTy\mathbf{w} = (X^{T} X)^{-1} X^{T} \mathbf{y}

(XTX^{T} is the transpose and the power −1-1 the inverse, both from Topic 14.) With one feature it gives exactly the w0w_0 and w1w_1 of Part 5. Nobody calculates it by hand for real data; that is the work of LinearRegression. But one small example shows that it is nothing mysterious.

Four points: (0,1)(0, 1), (1,3)(1, 3), (2,4)(2, 4), (3,8)(3, 8).

X=[10111213]y=[1348]X = \begin{bmatrix} 1 & 0 \\ 1 & 1 \\ 1 & 2 \\ 1 & 3 \end{bmatrix} \qquad \mathbf{y} = \begin{bmatrix} 1 \\ 3 \\ 4 \\ 8 \end{bmatrix}
XTX=[46614]XTy=[1635]X^{T} X = \begin{bmatrix} 4 & 6 \\ 6 & 14 \end{bmatrix} \qquad X^{T} \mathbf{y} = \begin{bmatrix} 16 \\ 35 \end{bmatrix}

The entries are sums: 4 is the number of points, 6 is ∑x\sum x, 14 is ∑x2\sum x^2, 16 is ∑y\sum y and 35 is ∑xy\sum xy.

det⁡(XTX)=4×14−6×6=20(XTX)−1=120[14−6−64]\begin{aligned} \det(X^{T} X) &= 4 \times 14 - 6 \times 6 = 20 \\[6pt] (X^{T} X)^{-1} &= \frac{1}{20} \begin{bmatrix} 14 & -6 \\ -6 & 4 \end{bmatrix} \end{aligned}
w=120[14×16−6×35−6×16+4×35]=120[1444]=[0.72.2]\begin{aligned} \mathbf{w} &= \frac{1}{20} \begin{bmatrix} 14 \times 16 - 6 \times 35 \\ -6 \times 16 + 4 \times 35 \end{bmatrix} \\[6pt] &= \frac{1}{20} \begin{bmatrix} 14 \\ 44 \end{bmatrix} = \begin{bmatrix} 0.7 \\ 2.2 \end{bmatrix} \end{aligned}

So y^=0.7+2.2x\hat{y} = 0.7 + 2.2x. The formulas of Part 5 give the same: w1=115=2.2w_1 = \dfrac{11}{5} = 2.2 and w0=4−2.2×1.5=0.7w_0 = 4 - 2.2 \times 1.5 = 0.7.

Gradient descent works for many features too. There is one slope for every weight, and all of them fit into one line with matrices:

gradient=2n XT(Xw−y)\text{gradient} = \frac{2}{n}\,X^{T}(X\mathbf{w} - \mathbf{y})

8.7From a line to a plane

With one feature the model is a line. With two features it is a flat plane above the plane of the two features, and the residuals are the vertical distances of the points from it. With three or more features the picture can no longer be drawn, but the mathematics is the same.

A tilted flat plane over the two axes area and rooms, with the price as the height. Twenty-four points lie close to the plane, each joined to it by a short vertical line.
With two features the model is a flat plane above the plane of the features. Every flat is a point, and its residual is its vertical distance from the plane.

8.8What changes, and what does not

Simple and multiple linear regression
Simple linear regressionMultiple linear regression
Features1pp (2 or more)
Equationy^=w0+w1x\hat{y} = w_0 + w_1 xy^=w0+w1x1+⋯+wpxp\hat{y} = w_0 + w_1 x_1 + \dots + w_p x_p
Parameters2p+1p + 1
Picturea linea plane (2 features), not drawable beyond
A weight meansthe change of y^\hat{y} per unit of xxthe same, with the other features held fixed
LossMSEMSE
Best parametersthe formulas of Part 5the normal equation
MeasuresMSE, RMSE, MAE, R²the same
In scikit-learnLinearRegressionLinearRegression, with more columns in X

One more word that books use: for a model with several features the measure adjusted R² lowers R² a little for every extra feature, so that a useless feature does not look like an improvement. Topic 23 shows a cleaner way to check whether a feature helps.

Try it yourself

A model is y^=5+2x1+3x2−x3\hat{y} = 5 + 2x_1 + 3x_2 - x_3. (a) Find the prediction for x1=4x_1 = 4, x2=2x_2 = 2, x3=3x_3 = 3. (b) By how much does the prediction change when x2x_2 grows by 2 and the other features stay the same? (c) How many parameters does the model have?

Show a hint
The weight of x2x_2 is 3. The intercept is a parameter too.
Show the solution

Answer: (a) 16; (b) 6; (c) 4.

(a)y^=5+2×4+3×2−3=5+8+6−3=16(b)2×3=6(c)3+1=4\begin{aligned} \text{(a)}\quad \hat{y} &= 5 + 2 \times 4 + 3 \times 2 - 3 \\ &= 5 + 8 + 6 - 3 = 16 \\[4pt] \text{(b)}\quad & 2 \times 3 = 6 \\[4pt] \text{(c)}\quad & 3 + 1 = 4 \end{aligned}

A weight is the change for one unit of its feature; two units give twice as much. Three weights and one intercept are four parameters: a model with pp features has p+1p + 1.

9Linear regression in Python

The examples of this part continue from one another, like the cells of a notebook: the arrays and the model that one example creates are used by the next. Run them in order.

9.1The data as arrays

scikit-learn wants the features as a table X with two dimensions, and the target as y with one dimension (Topic 21). A NumPy array made from a list has one dimension, so the feature must be reshaped into a column:

Python
import numpy as np

hours = np.array([2, 4, 5, 6, 8])
marks = np.array([50, 60, 65, 75, 80])

X = hours.reshape(-1, 1)
y = marks

print(X)
print(X.shape, y.shape)

Output

[[2]
 [4]
 [5]
 [6]
 [8]]
(5, 1) (5,)

Change it and run: add a sixth student to both arrays, for example 7 hours and the mark 72, and look at the two shapes.

reshape(-1, 1) means "one column, and as many rows as are needed" (Topic 9). The shape (5, 1) is a table with 5 samples and 1 feature; the shape (5,) is a plain row of 5 values.

9.2Training the model

Python, continues from the cells above
from sklearn.linear_model import LinearRegression

model = LinearRegression()
model.fit(X, y)

print(round(model.intercept_, 2))
print(model.coef_.round(2))

Output

39.75
[5.25]

fit did the whole of Part 5. The intercept w0w_0 is in model.intercept_ and the slope w1w_1 in model.coef_. The names end in an underscore because the values were learned from the data (Topic 21). coef_ is an array, because a model can have many features: one weight for each.

9.3Predicting

Python, continues from the cells above
new_hours = np.array([[7], [3], [10]])
print(model.predict(new_hours))

Output

[76.5  55.5  92.25]

Change it and run: change the values in new_hours, for example to [[1], [5]]. For 5 hours, the mean of the hours, the prediction is the mean mark.

The new values must have the same form as X: a table with one column. The double brackets [[7], [3], [10]] make three rows with one value each. The prediction for 10 hours is 39.75+52.5=92.2539.75 + 52.5 = 92.25, but 10 hours lies outside the data (2 to 8 hours): Part 10 explains why such a number should not be trusted.

9.4Predictions and residuals of the training data

Python, continues from the cells above
y_pred = model.predict(X)
residuals = y - y_pred

print(y_pred.round(2))
print(residuals.round(2))
print(abs(residuals.sum()) < 1e-9)

Output

[50.25 60.75 66.   71.25 81.75]
[-0.25 -0.75 -1.    3.75 -1.75]
True

These are the numbers of the table in Part 3. The last line checks that the residuals add up to zero. (The sum is compared with a very small number and not with 0, because the computer calculates with decimals that are not perfectly exact, as you saw in Topic 1.)

9.5Drawing the points and the line

Python, continues from the cells above
import matplotlib.pyplot as plt

plt.scatter(hours, marks, label="students")
plt.plot(hours, model.predict(X), color="orange", label="regression line")
plt.xlabel("hours of study")
plt.ylabel("mark")
plt.title("Hours of study and marks")
plt.legend()
plt.show()
Chart: Hours of study and marks

A picture is the first check of every regression: do the points really follow a line?

9.6The measures, calculated with NumPy

The errors first:

Python, continues from the cells above
sse = (residuals ** 2).sum()
mse = (residuals ** 2).mean()
rmse = np.sqrt(mse)
mae = np.abs(residuals).mean()

print(round(sse, 4), round(mse, 4))
print(round(rmse, 4), round(mae, 4))

Output

18.75 3.75
1.9365 1.5

Then the total sum of squares and R²:

Python, continues from the cells above
sst = ((y - y.mean()) ** 2).sum()
r2 = 1 - sse / sst

print(round(sst, 4), round(r2, 4))

Output

570.0 0.9671

Every line is a formula of Part 7, and every number is the one calculated by hand.

9.7The measures, with scikit-learn

You do not have to write the formulas yourself. The part sklearn.metrics has a function for each measure. All of them take the true values first and the predictions second:

Python, continues from the cells above
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score, root_mean_squared_error

print(round(mean_squared_error(y, y_pred), 4))
print(round(root_mean_squared_error(y, y_pred), 4))
print(round(mean_absolute_error(y, y_pred), 4))
print(round(r2_score(y, y_pred), 4))

Output

3.75
1.9365
1.5
0.9671

For a regression model, model.score(X, y) is the R² score too. It makes the predictions itself, so it gets X and not y_pred:

Python, continues from the cells above
print(round(model.score(X, y), 4))

Output

0.9671

The last line of the cell above and this line print the same number.

9.8The formulas of Part 5 in NumPy

To see that scikit-learn does nothing secret, calculate the slope and the intercept directly:

Python, continues from the cells above
x_dev = hours - hours.mean()
y_dev = marks - marks.mean()

w1 = (x_dev * y_dev).sum() / (x_dev ** 2).sum()
w0 = marks.mean() - w1 * hours.mean()

print(w1, w0)

Output

5.25 39.75

9.9Gradient descent in a few lines

The update rule of Part 6, for both parameters, repeated 5,000 times:

Python, continues from the cells above
w0, w1 = 0.0, 0.0
rate = 0.02
losses = []

for step in range(5000):
    error = (w0 + w1 * hours) - marks
    losses.append((error ** 2).mean())
    w0 = w0 - rate * 2 * error.mean()
    w1 = w1 - rate * 2 * (error * hours).mean()

print(round(w0, 2), round(w1, 2))

Output

39.75 5.25

Change it and run: set rate to 0.001 and run: after 5,000 steps the walk has not arrived yet. Then try 0.05: the numbers run away and the result is nan.

Starting from w0=0w_0 = 0 and w1=0w_1 = 0, the walk arrives at the line of the formulas. The list losses kept the loss of every step. Here it is at the start, after 10 steps, after 100 steps and at the end:

Python, continues from the cells above
print(round(losses[0], 2), round(losses[10], 2), round(losses[100], 2), round(losses[-1], 2))

Output

4470.0 179.93 70.74 3.75

It falls from 4,470 to 3.75, the MSE of the best line.

Python, continues from the cells above
import matplotlib.pyplot as plt

plt.plot(losses[:60])
plt.xlabel("step")
plt.ylabel("loss (MSE)")
plt.title("Gradient descent: the loss during the first 60 steps")
plt.show()
Chart: Gradient descent: the loss during the first 60 steps

A curve of the loss that falls and then flattens is the picture every trained model should show. With rate = 0.05 the same loop does not converge: the loss grows until the numbers overflow. Try it.

9.10Multiple linear regression

Nothing changes in the code except the number of columns of X. Ten flats with their area, number of rooms and age, and their prices in thousands:

Python
import numpy as np
from sklearn.linear_model import LinearRegression

flats = np.array([
    [45, 1, 20],
    [52, 2, 15],
    [60, 2, 30],
    [68, 2, 5],
    [75, 3, 12],
    [83, 3, 25],
    [90, 3, 2],
    [105, 4, 8],
    [110, 4, 18],
    [130, 4, 10],
])
prices = np.array([85, 104, 108, 133, 158, 150, 188, 208, 215, 244])

print(flats.shape, prices.shape)

Output

(10, 3) (10,)

flats already has two dimensions, 10 rows and 3 columns, so no reshape is needed.

Python, continues from the cells above
flat_model = LinearRegression()
flat_model.fit(flats, prices)

print(round(flat_model.intercept_, 2))
print(flat_model.coef_.round(2))

Output

21.74
[ 1.43 11.5  -0.79]

coef_ now holds three weights, in the order of the columns: area, rooms, age.

Python, continues from the cells above
new_flat = np.array([[80, 3, 10]])

print(flat_model.predict(new_flat).round(1))
print(round(flat_model.score(flats, prices), 4))

Output

[162.6]
0.9943

Change it and run: change the new flat to 4 rooms: the prediction grows by the weight of the rooms.

The first line is the predicted price of a flat with 80 m², 3 rooms and 10 years. The second is the R² of the model with three features.

Now a simple regression on the area alone (flats[:, [0]] keeps the first column as a table):

Python, continues from the cells above
area_only = flats[:, [0]]

area_model = LinearRegression()
area_model.fit(area_only, prices)

print(area_model.coef_.round(2), round(area_model.score(area_only, prices), 4))

Output

[1.93] 0.9753

Its R² is lower, and its weight for the area is larger than in the model with three features, because the area now also carries the effect of the rooms.

9.11More points, with noise

Five students lie almost on a line. Real data has many more points, and noise. Here are 40 generated flats: the price of each one is 20 + 1.5 * area plus a random amount. The first five areas and prices:

Python
import numpy as np

rng = np.random.default_rng(0)
area = rng.uniform(40, 120, 40).round()
price = (20 + 1.5 * area + rng.normal(0, 10, 40)).round()

print(area[:5])
print(price[:5])

Output

[ 91.  62.  43.  41. 105.]
[144. 128.  98.  89. 180.]

The same three steps as before: reshape, create, fit. Then the intercept and the slope, R², and the RMSE:

Python, continues from the cells above
from sklearn.linear_model import LinearRegression
from sklearn.metrics import root_mean_squared_error

X = area.reshape(-1, 1)
model = LinearRegression()
model.fit(X, price)

print(round(model.intercept_, 2), model.coef_.round(2))
print(round(model.score(X, price), 3))
print(round(root_mean_squared_error(price, model.predict(X)), 2))

Output

18.17 [1.56]
0.923
10.8

Change it and run: change the 10 inside rng.normal(0, 10, 40) of the cell above to 30 (more noise) and run both cells: the slope stays near 1.5, R² falls and the RMSE grows.

The prices were generated as 20 + 1.5 * area plus random noise, and the model finds a slope near 1.5 and an intercept near 20 again. It does not find them exactly, because the noise hides the true line a little. The RMSE, 10.8, is about the size of the noise that was added (a standard deviation of 10): no model can predict the random part, so this is as good as a model can be here.

9.12The residual plot

Python, continues from the cells above
import matplotlib.pyplot as plt

residuals = price - model.predict(X)

plt.scatter(area, residuals)
plt.axhline(0, color="gray")
plt.xlabel("area")
plt.ylabel("residual")
plt.title("Residual plot")
plt.show()
Chart: Residual plot

A residual plot shows the residual of every point against its feature. For a good linear model the points are scattered around the zero line without any pattern, as here. A pattern (a curve, a funnel) says that a straight line is not the right model. The next part shows such a case.

9.13The pieces of scikit-learn used in this lesson

The pieces of scikit-learn used in this lesson
CodeWhat it does
x.reshape(-1, 1)turns a row of values into a table with one column
LinearRegression()creates an empty linear regression model
model.fit(X, y)finds the best intercept and weights
model.intercept_the intercept w0w_0 (one number)
model.coef_the weights w1,…,wpw_1, \dots, w_p (an array)
model.predict(X_new)the predictions for new rows
model.score(X, y)the R² score
mean_squared_error(y, y_pred)MSE
root_mean_squared_error(y, y_pred)RMSE
mean_absolute_error(y, y_pred)MAE
r2_score(y, y_pred)R²

Try it yourself

A cafe sold 20, 24, 32, 35 and 44 cold drinks on days with 10, 15, 20, 25 and 30 degrees. Train a model and print the intercept and the slope on one line, each rounded to 2 decimals.
Show a hint
Reshape the temperatures into a column: temperature.reshape(-1, 1). Then print(round(model.intercept_, 2), round(model.coef_[0], 2)).
Show the solution
Python
import numpy as np
from sklearn.linear_model import LinearRegression

temperature = np.array([10, 15, 20, 25, 30])
drinks = np.array([20, 24, 32, 35, 44])

model = LinearRegression()
model.fit(temperature.reshape(-1, 1), drinks)

print(round(model.intercept_, 2), round(model.coef_[0], 2))

Output

7.4 1.18

Try it yourself

Five cars are 1, 2, 3, 4 and 5 years old and cost 18, 16, 15, 12 and 9 thousand. Train a model. Print the RMSE, and on a second line R², each rounded to 4 decimals.
Show a hint
root_mean_squared_error(price, model.predict(X)) and model.score(X, price).
Show the solution
Python
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import root_mean_squared_error

age = np.array([1, 2, 3, 4, 5])
price = np.array([18, 16, 15, 12, 9])

X = age.reshape(-1, 1)
model = LinearRegression()
model.fit(X, price)

print(round(root_mean_squared_error(price, model.predict(X)), 4))
print(round(model.score(X, price), 4))

Output

0.5657
0.968

10The limits of linear regression

Linear regression always gives an answer. It will draw a line through any cloud of points. Whether the line means anything is your responsibility.

10.1What the model assumes

  • The relationship is roughly a straight line. The model has no other shape to offer.
  • The points are independent of one another: one student's mark does not depend on another's.
  • The residuals have about the same spread everywhere, not small on the left and huge on the right.
  • No single point dominates. A few extreme values should not decide the line.

The first check is always a scatter plot, and the second a residual plot.

10.2A curve is not a line

Take the points (1,1),(2,4),(3,9),…,(8,64)(1, 1), (2, 4), (3, 9), \dots, (8, 64): exactly y=x2y = x^2. The best line is y^=−15+9x\hat{y} = -15 + 9x, and its R² is 0.95. A high score, and still the wrong model: the line is too low at both ends and too high in the middle, and its residuals form a clear curve.

24680204060

A curve with a line through it

2468-505

Its residuals

Left: the points of y = x² with the best line through them. R² is 0.95, and the line is still the wrong shape. Right: its residuals. They are positive at both ends and negative in the middle: a clear curve, not a cloud without a pattern.

10.3One outlier can turn the line

Add a sixth student to the five: 9 hours of study and a mark of 40 (perhaps this student was ill on the day of the exam). The line changes from y^=39.75+5.25x\hat{y} = 39.75 + 5.25x to y^=58.55+0.55x\hat{y} = 58.55 + 0.55x. One point has almost removed the slope. The reason is the square in the loss: a point far from the line costs so much that the line turns towards it. Outliers must be found and thought about before the model is trained. Topic 25 is about them.

2468406080

Five students: slope 5.25

2468406080

With one outlier: slope 0.55

Left: the five students, slope 5.25. Right: a sixth student with 9 hours and the mark 40 (in the second colour). One point turns the line almost flat: the slope falls to 0.55.

The five students and a sixth one that you can move.

246810406080hours of studymark

Five students: slope 5.25, R² = 0.9671

With the sixth at (9, 40): slope 0.55, R² = 0.0089

A sixth point near the line (7 hours, mark 75) changes almost nothing. Far from the line and far to the right, it turns the line towards itself: the squared loss makes a distant point very expensive.

10.4Predictions outside the data

The students studied between 2 and 8 hours. For 7 hours the model interpolates between points it has seen. For 20 hours it predicts 39.75+5.25×20=144.7539.75 + 5.25 \times 20 = 144.75, a mark that does not exist. The line knows nothing about what happens outside the range of its data. Using it there is called extrapolation, and it is one of the most common ways to get a confident, wrong number.

10.5A relationship is not a cause

The slope says that students who study more get higher marks. It does not prove that the hours cause the marks. Perhaps the students who study more are also the ones who attend every lesson. Topic 20 said it for the correlation, and it holds for regression in the same way.

10.6When features repeat each other

In a multiple regression, two features that say almost the same (the area in square metres and the area in square feet) make the weights unstable: the model cannot decide how to divide the effect between them. This is called multicollinearity (Topic 20). The predictions stay good, but the single weights can no longer be interpreted. Regularization (Topic 26) is one cure.

10.7What the next lessons add

What the next lessons add
ProblemWhere it is solved
A model that fits the training data but not new dataTopic 23: train/test split, cross-validation, overfitting
Features on very different scalesTopic 24: scaling
Features that are categories (a city, a colour), and outliersTopic 25: encoding and outliers
Too many features, unstable weightsTopic 26: Ridge and Lasso
A target that is a categoryTopic 27: logistic regression

Try it yourself

A model was trained on flats between 40 and 120 m². (a) Is a prediction for a flat of 90 m² inside the range of the data? (b) Is a prediction for a flat of 400 m² safe? (c) Another model has R2=0.95R^2 = 0.95, and its residual plot shows a clear curve. Is a straight line the right model? (d) One point lies very far from all the others. Can it change the slope strongly?

Show a hint
Think of the three warnings of this part: the range of the data, the shape of the residuals, and the square in the loss.
Show the solution

Answer: (a) yes; (b) no; (c) no; (d) yes.

90 m² lies between 40 and 120, so the model interpolates. 400 m² is far outside: that is extrapolation, and nobody checked the line there. A pattern in the residuals means that the line has the wrong shape, whatever R² says. And a distant point costs so much in a squared loss that the line turns towards it.

11Common mistakes

Common mistakes
MistakeWhy it is wrongRight
Calculating the residual as y^−y\hat{y} - y.The residual is defined as true minus predicted. With the other order the signs turn round: "above the line" becomes negative.e=y−y^e = y - \hat{y}
Adding the residuals to judge a line.Positive and negative residuals cancel; for the best line the sum is always 0.Add the squares (SSE) or the absolute values.
Forgetting to divide by nn, and calling the SSE "MSE".The SSE grows with the number of points; the MSE is the average.MSE=SSE/n\text{MSE} = \text{SSE} / n
Reporting the MSE in the unit of yy.The MSE has the squared unit.Take the root: the RMSE has the unit of yy.
"R2=0.97R^2 = 0.97 means that 97 percent of the predictions are correct."R² is not a share of right answers."The model explains 97 percent of the variation of the target."
"R² is always between 0 and 1."A model worse than "always the mean" has a negative R².R² is at most 1; on new data it can be negative.
"A high R² proves that the line is the right model."A curve can have a high R².Look at the scatter plot and the residual plot too.
Mixing up the slope and the intercept.w0w_0 is the value at x=0x = 0, w1w_1 the change per unit.In y^=39.75+5.25x\hat{y} = 39.75 + 5.25x the slope is 5.25.
Calculating w0w_0 before w1w_1.w0=yˉ−w1 xˉw_0 = \bar{y} - w_1\,\bar{x} needs the slope.First w1w_1, then w0w_0.
Reading the slope as a cause.The line describes how the values move together in this data."goes with", "on average", not "causes".
Predicting far outside the range of the data.The line was never checked there.Predict inside the range; say clearly when you do not.
Comparing the weights of features with different units.A weight depends on the unit of its feature.Scale the features first (Topic 24).
Passing a plain array as X: model.fit(hours, marks).scikit-learn needs a table with two dimensions.model.fit(hours.reshape(-1, 1), marks)
model.predict(7)A single number is not a table.model.predict(np.array([[7]]))
r2_score(y_pred, y)The true values come first. The result changes when the order is swapped.r2_score(y, y_pred)
model.score(X, y_pred)score makes the predictions itself; it needs the true answers.model.score(X, y)
A learning rate that is too large.The steps jump over the lowest point and the loss grows.Lower the rate until the loss falls step after step.
Stopping gradient descent after a few steps.The parameters are still far from the lowest point.Run until the loss no longer changes.

The error that scikit-learn shows for a plain array as X:

Python
import numpy as np
from sklearn.linear_model import LinearRegression

hours = np.array([2, 4, 5, 6, 8])
marks = np.array([50, 60, 65, 75, 80])

model = LinearRegression()
model.fit(hours, marks)

Error

Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

The message names the repair itself: reshape(-1, 1) for data with a single feature.

12Solved problems (from the easiest to the hardest)

Each problem has the question, the idea behind it with the part of the lesson it uses, and the solution step by step. Problems 1 to 16 are solved by hand: cover the solution and try first, with paper and a calculator. Problems 17 to 26 are solved in Python: every one runs on its own.

Level 1: The line, the residuals and the loss

Problem 1: A prediction from a line

A delivery company uses the line y^=6.5+2.3x\hat{y} = 6.5 + 2.3x to estimate the time of a delivery in minutes from the distance xx in kilometres. How long will a delivery over 5 km take? And over 10 km?

Idea. Put the distance into the equation (Part 2).

x=5:y^=6.5+2.3×5=6.5+11.5=18x=10:y^=6.5+2.3×10=6.5+23=29.5\begin{aligned} x = 5:\quad \hat{y} &= 6.5 + 2.3 \times 5 = 6.5 + 11.5 = 18 \\[4pt] x = 10:\quad \hat{y} &= 6.5 + 2.3 \times 10 = 6.5 + 23 = 29.5 \end{aligned}

Why: the model is nothing more than this equation. Twice the distance does not give twice the time, because the intercept 6.5 (the time for packing and handing over) does not grow with the distance.

Problem 2: Reading the slope and the intercept

The price of a used car of one model, in thousands, follows the line y^=20.6−2.2x\hat{y} = 20.6 - 2.2x, where xx is the age in years. (a) What do the two numbers mean? (b) What is the predicted price of a car that is 3 years old? (c) By how much does the predicted price fall in 4 years?

Idea. The intercept is the prediction at x=0x = 0, the slope the change per unit (Part 2).

(a) The intercept 20.6: the predicted price of a new car (age 0) is 20.6 thousand. The slope −2.2-2.2: every year of age takes away 2.2 thousand.

(b)y^=20.6−2.2×3=20.6−6.6=14(c)4×2.2=8.8 thousand\begin{aligned} \text{(b)}\quad \hat{y} &= 20.6 - 2.2 \times 3 = 20.6 - 6.6 = 14 \\[4pt] \text{(c)}\quad & 4 \times 2.2 = 8.8 \text{ thousand} \end{aligned}

Why: a negative slope means a falling line: more xx, less yy. The change over several units is the slope times the number of units.

Problem 3: Residuals

A company spent 1, 2, 3, 4 and 5 thousand on advertising in five months, and its sales were 3, 5, 4, 7 and 6 thousand. A line through the data is y^=2.6+0.8x\hat{y} = 2.6 + 0.8x. Find the prediction and the residual of every month.

Idea. e=y−y^e = y - \hat{y}, true minus predicted (Part 3).

Predictions and residuals of the five months
xxyyy^=2.6+0.8x\hat{y} = 2.6 + 0.8xe=y−y^e = y - \hat{y}
133.4−0.4-0.4
254.20.8
345−1-1
475.81.2
566.6−0.6-0.6
Sum0

Why: months 2 and 4 lie above the line (positive residuals), the others below. The residuals add up to 0, which is a sign that this is the least-squares line.

Problem 4: SSE and MSE

Find the SSE and the MSE of the line of Problem 3.

Idea. Square the residuals, add them, divide by nn (Part 4).

SSE=(−0.4)2+0.82+(−1)2+1.22+(−0.6)2=0.16+0.64+1+1.44+0.36=3.6MSE=3.65=0.72\begin{aligned} \text{SSE} &= (-0.4)^2 + 0.8^2 + (-1)^2 + 1.2^2 + (-0.6)^2 \\[4pt] &= 0.16 + 0.64 + 1 + 1.44 + 0.36 = 3.6 \\[4pt] \text{MSE} &= \frac{3.6}{5} = 0.72 \end{aligned}

Why: the squares remove the signs, so nothing cancels. The largest residual, 1.2, gives 1.44 of the 3.6: large errors weigh the most.

Problem 5: Which line fits better?

Four points: (1,3)(1, 3), (2,5)(2, 5), (3,6)(3, 6), (4,10)(4, 10). Compare the lines y^=1+2x\hat{y} = 1 + 2x and y^=0.5+2.2x\hat{y} = 0.5 + 2.2x by their SSE.

Idea. The line with the smaller SSE fits better (Part 4).

The two lines on the four points
xxyyfirst line y^\hat{y}eesecond line y^\hat{y}ee
13302.70.3
25504.90.1
367−1-17.1−1.1-1.1
410919.30.7
first line:SSE=02+02+(−1)2+12=2second line:SSE=0.32+0.12+(−1.1)2+0.72SSE=0.09+0.01+1.21+0.49=1.8\begin{aligned} & \text{first line:} \\ & \quad \text{SSE} = 0^2 + 0^2 + (-1)^2 + 1^2 = 2 \\[6pt] & \text{second line:} \\ & \quad \text{SSE} = 0.3^2 + 0.1^2 + (-1.1)^2 + 0.7^2 \\ & \quad \phantom{\text{SSE}} = 0.09 + 0.01 + 1.21 + 0.49 = 1.8 \end{aligned}

Why: the first line hits two points exactly, and still the second one is better: its errors are spread more evenly, and the squared loss rewards that. The second line is in fact the least-squares line of these points.

Problem 6: The best line from the formulas

Find the least-squares line for the points (0,1)(0, 1), (1,3)(1, 3), (2,4)(2, 4), (3,4)(3, 4), (4,8)(4, 8).

Idea. w1=∑(x−xˉ)(y−yˉ)∑(x−xˉ)2w_1 = \dfrac{\sum (x - \bar{x})(y - \bar{y})}{\sum (x - \bar{x})^2}, then w0=yˉ−w1 xˉw_0 = \bar{y} - w_1\,\bar{x} (Part 5).

xˉ=0+1+2+3+45=2yˉ=1+3+4+4+85=4\begin{aligned} \bar{x} &= \frac{0 + 1 + 2 + 3 + 4}{5} = 2 \\[4pt] \bar{y} &= \frac{1 + 3 + 4 + 4 + 8}{5} = 4 \end{aligned}
The deviations of the five points
xxyyx−xˉx - \bar{x}y−yˉy - \bar{y}product(x−xˉ)2(x - \bar{x})^2
01−2-2−3-364
13−1-1−1-111
240000
341001
482484
Sum1510
w1=1510=1.5w0=4−1.5×2=1y^=1+1.5 x\begin{aligned} w_1 &= \frac{15}{10} = 1.5 \\[4pt] w_0 &= 4 - 1.5 \times 2 = 1 \\[4pt] \hat{y} &= 1 + 1.5\,x \end{aligned}

Why: the slope compares how xx and yy move together (the top) with how much xx moves at all (the bottom). The intercept then puts the line through the point of the means (2,4)(2, 4).

Problem 7: A line for the deliveries

Four deliveries: distances 2, 4, 6 and 8 km, times 11, 15, 22 and 24 minutes. Find the least-squares line and predict the time for 5 km.

Idea. The five steps of Part 5.

xˉ=204=5yˉ=724=18deviations of x: −3, −1, 1, 3deviations of y: −7, −3, 4, 6products: 21+3+4+18=46squares: 9+1+1+9=20w1=4620=2.3w0=18−2.3×5=18−11.5=6.5y^=6.5+2.3 xx=5:y^=6.5+11.5=18\begin{aligned} & \bar{x} = \frac{20}{4} = 5 \qquad \bar{y} = \frac{72}{4} = 18 \\[4pt] & \text{deviations of } x:\ -3,\ -1,\ 1,\ 3 \\[4pt] & \text{deviations of } y:\ -7,\ -3,\ 4,\ 6 \\[4pt] & \text{products: } 21 + 3 + 4 + 18 = 46 \\[4pt] & \text{squares: } 9 + 1 + 1 + 9 = 20 \\[4pt] & w_1 = \frac{46}{20} = 2.3 \\[4pt] & w_0 = 18 - 2.3 \times 5 = 18 - 11.5 = 6.5 \\[4pt] & \hat{y} = 6.5 + 2.3\,x \\[4pt] & x = 5:\quad \hat{y} = 6.5 + 11.5 = 18 \end{aligned}

Why: 5 km is the mean distance, and the prediction is the mean time, 18 minutes: the least-squares line always passes through the point of the means. This is the line of Problem 1.

Problem 8: RMSE and MAE

For the line y^=1+1.5x\hat{y} = 1 + 1.5x of Problem 6, find the MSE, the RMSE and the MAE.

Idea. The residuals first, then the three formulas of Part 7.

predictions: 1, 2.5, 4, 5.5, 7residuals: 0, 0.5, 0, −1.5, 1SSE=0+0.25+0+2.25+1=3.5MSE=3.55=0.7RMSE=0.7=0.8367MAE=0+0.5+0+1.5+15=35=0.6\begin{aligned} & \text{predictions: } 1,\ 2.5,\ 4,\ 5.5,\ 7 \\[4pt] & \text{residuals: } 0,\ 0.5,\ 0,\ -1.5,\ 1 \\[4pt] & \text{SSE} = 0 + 0.25 + 0 + 2.25 + 1 = 3.5 \\[4pt] & \text{MSE} = \frac{3.5}{5} = 0.7 \\[4pt] & \text{RMSE} = \sqrt{0.7} = 0.8367 \\[4pt] & \text{MAE} = \frac{0 + 0.5 + 0 + 1.5 + 1}{5} = \frac{3}{5} = 0.6 \end{aligned}

Why: the RMSE (0.84) is larger than the MAE (0.6) because the square gives the one large residual, −1.5-1.5, more weight. Both are in the unit of yy.

Problem 9: The R² score

Find R² for the line of Problem 6.

Idea. R2=1−SSESSTR^2 = 1 - \dfrac{\text{SSE}}{\text{SST}}, where SST is the squared error of "always the mean" (Part 7).

yˉ=4SST=(−3)2+(−1)2+02+02+42=9+1+0+0+16=26SSE=3.5R2=1−3.526=1−0.1346=0.8654\begin{aligned} \bar{y} &= 4 \\[4pt] \text{SST} &= (-3)^2 + (-1)^2 + 0^2 + 0^2 + 4^2 \\[4pt] &= 9 + 1 + 0 + 0 + 16 = 26 \\[4pt] \text{SSE} &= 3.5 \\[4pt] R^2 &= 1 - \frac{3.5}{26} = 1 - 0.1346 = 0.8654 \end{aligned}

Why: without a model, the squared error is 26. The line leaves 3.5 of it. It explains about 86.5 percent of the variation of yy.

Level 2: Complete regressions, gradient descent and several features

Problem 10: A complete regression by hand

Five used cars of one model: ages 1, 2, 3, 4 and 5 years, prices 18, 16, 15, 12 and 9 thousand. Find the line, its R², and say what the result means.

Idea. Fit the line (Part 5), then the residuals, SSE, SST and R² (Part 7).

xˉ=3yˉ=705=14deviations of x: −2, −1, 0, 1, 2deviations of y: 4, 2, 1, −2, −5products: −8−2+0−2−10=−22squares: 4+1+0+1+4=10w1=−2210=−2.2w0=14−(−2.2)×3=14+6.6=20.6\begin{aligned} & \bar{x} = 3 \qquad \bar{y} = \frac{70}{5} = 14 \\[4pt] & \text{deviations of } x:\ -2,\ -1,\ 0,\ 1,\ 2 \\[4pt] & \text{deviations of } y:\ 4,\ 2,\ 1,\ -2,\ -5 \\[4pt] & \text{products: } -8 - 2 + 0 - 2 - 10 = -22 \\[4pt] & \text{squares: } 4 + 1 + 0 + 1 + 4 = 10 \\[4pt] & w_1 = \frac{-22}{10} = -2.2 \\[4pt] & w_0 = 14 - (-2.2) \times 3 = 14 + 6.6 = 20.6 \end{aligned}
predictions: 18.4, 16.2, 14, 11.8, 9.6residuals: −0.4, −0.2, 1, 0.2, −0.6SSE=0.16+0.04+1+0.04+0.36=1.6SST=16+4+1+4+25=50R2=1−1.650=0.968\begin{aligned} & \text{predictions: } 18.4,\ 16.2,\ 14,\ 11.8,\ 9.6 \\[4pt] & \text{residuals: } -0.4,\ -0.2,\ 1,\ 0.2,\ -0.6 \\[4pt] & \text{SSE} = 0.16 + 0.04 + 1 + 0.04 + 0.36 = 1.6 \\[4pt] & \text{SST} = 16 + 4 + 1 + 4 + 25 = 50 \\[4pt] & R^2 = 1 - \frac{1.6}{50} = 0.968 \end{aligned}

Why: y^=20.6−2.2x\hat{y} = 20.6 - 2.2x: a car loses about 2.2 thousand a year, and the age explains 96.8 percent of the differences in price. This is the line of Problem 2.

Problem 11: Salary and experience

Five employees have 1, 3, 5, 7 and 9 years of experience and the salaries 900, 1300, 1500, 2100 and 2200. (a) Find the line. (b) Find the RMSE. (c) Predict the salary for 6 years of experience. (d) Is a prediction for 30 years sensible?

Idea. Parts 5 and 7, and the warning about predictions outside the data (Part 10).

(a)xˉ=5yˉ=80005=1600deviations of x: −4, −2, 0, 2, 4deviations of y: −700, −300, −100, 500, 600products: 2800+600+0+1000+2400=6800squares: 16+4+0+4+16=40w1=680040=170w0=1600−170×5=750y^=750+170 x\begin{aligned} & \text{(a)} \\ & \bar{x} = 5 \qquad \bar{y} = \frac{8000}{5} = 1600 \\[4pt] & \text{deviations of } x:\ -4,\ -2,\ 0,\ 2,\ 4 \\[4pt] & \text{deviations of } y:\ -700,\ -300,\ -100,\ 500,\ 600 \\[4pt] & \text{products: } 2800 + 600 + 0 + 1000 + 2400 = 6800 \\[4pt] & \text{squares: } 16 + 4 + 0 + 4 + 16 = 40 \\[4pt] & w_1 = \frac{6800}{40} = 170 \\[4pt] & w_0 = 1600 - 170 \times 5 = 750 \\[4pt] & \hat{y} = 750 + 170\,x \end{aligned}
(b)predictions: 920, 1260, 1600, 1940, 2280residuals: −20, 40, −100, 160, −80SSE=400+1600+10000+25600+6400SSE=44000MSE=440005=8800RMSE=8800=93.81(c)y^=750+170×6=1770(d)y^=750+170×30=5850\begin{aligned} & \text{(b)} \\ & \text{predictions: } 920,\ 1260,\ 1600,\ 1940,\ 2280 \\[4pt] & \text{residuals: } -20,\ 40,\ -100,\ 160,\ -80 \\[4pt] & \text{SSE} = 400 + 1600 + 10000 + 25600 + 6400 \\ & \phantom{\text{SSE}} = 44000 \\[4pt] & \text{MSE} = \frac{44000}{5} = 8800 \\[4pt] & \text{RMSE} = \sqrt{8800} = 93.81 \\[6pt] & \text{(c)}\quad \hat{y} = 750 + 170 \times 6 = 1770 \\[6pt] & \text{(d)}\quad \hat{y} = 750 + 170 \times 30 = 5850 \end{aligned}

Why: every year of experience goes with 170 more salary, and the predictions are off by about 94 on a typical employee. The number for 30 years can be calculated, but it should not be trusted: the data ends at 9 years, and nobody knows whether salaries keep rising in a straight line for three more decades.

Problem 12: Two checks of a line

A cafe counted the cold drinks it sold on five days with the temperatures 10, 15, 20, 25 and 30 degrees: 20, 24, 32, 35 and 44 drinks. Find the line. Then check that it passes through the point of the means and that its residuals add up to 0.

Idea. The formulas, and the facts about the least-squares line (Part 5).

xˉ=20yˉ=1555=31deviations of x: −10, −5, 0, 5, 10deviations of y: −11, −7, 1, 4, 13products: 110+35+0+20+130=295squares: 100+25+0+25+100=250w1=295250=1.18w0=31−1.18×20=31−23.6=7.4\begin{aligned} & \bar{x} = 20 \qquad \bar{y} = \frac{155}{5} = 31 \\[4pt] & \text{deviations of } x:\ -10,\ -5,\ 0,\ 5,\ 10 \\[4pt] & \text{deviations of } y:\ -11,\ -7,\ 1,\ 4,\ 13 \\[4pt] & \text{products: } 110 + 35 + 0 + 20 + 130 = 295 \\[4pt] & \text{squares: } 100 + 25 + 0 + 25 + 100 = 250 \\[4pt] & w_1 = \frac{295}{250} = 1.18 \\[4pt] & w_0 = 31 - 1.18 \times 20 = 31 - 23.6 = 7.4 \end{aligned}
check 1: 7.4+1.18×20=7.4+23.6=31=yˉpredictions: 19.2, 25.1, 31, 36.9, 42.8residuals: 0.8, −1.1, 1, −1.9, 1.2check 2: 0.8−1.1+1−1.9+1.2=0\begin{aligned} & \text{check 1: } 7.4 + 1.18 \times 20 = 7.4 + 23.6 = 31 = \bar{y} \\[4pt] & \text{predictions: } 19.2,\ 25.1,\ 31,\ 36.9,\ 42.8 \\[4pt] & \text{residuals: } 0.8,\ -1.1,\ 1,\ -1.9,\ 1.2 \\[4pt] & \text{check 2: } 0.8 - 1.1 + 1 - 1.9 + 1.2 = 0 \end{aligned}

Why: both checks hold for every least-squares line. They are a quick way to find a mistake in a calculation by hand: if the residuals do not add up to 0, something went wrong.

Problem 13: Gradient descent by hand

Two points: (1,3)(1, 3) and (2,6)(2, 6). The model is y^=w x\hat{y} = w\,x. Start at w=1w = 1 and take three steps of gradient descent with the learning rate α=0.1\alpha = 0.1.

Idea. slope=2n∑(y^−y) x\text{slope} = \dfrac{2}{n} \sum (\hat{y} - y)\,x, then wnew=wold−α×slopew_{\text{new}} = w_{\text{old}} - \alpha \times \text{slope} (Part 6).

slope=22[(w×1−3)×1+(w×2−6)×2]=(w−3)+(4w−12)=5w−15\begin{aligned} \text{slope} &= \frac{2}{2}\left[(w \times 1 - 3) \times 1 + (w \times 2 - 6) \times 2\right] \\[4pt] &= (w - 3) + (4w - 12) = 5w - 15 \end{aligned}
Three steps with the learning rate 0.1
Stepwwslope 5w−155w - 15new ww
11−10-102
22−5-52.5
32.5−2.5-2.52.75

Why: both points lie on the line y^=3x\hat{y} = 3x, so the lowest point of the loss is w=3w = 3. The slope is negative as long as ww is below 3, so every step makes ww larger, and the steps shrink as the slope gets flatter: 1, 0.5, 0.25.

Problem 14: A learning rate that is too large

Repeat Problem 13 with the learning rate α=0.5\alpha = 0.5. What happens?

Idea. The same rule; watch the distance from the lowest point w=3w = 3 (Part 6).

Three steps with the learning rate 0.5
Stepwwslope 5w−155w - 15new ww
11−10-106
2615−1.5-1.5
3−1.5-1.5−22.5-22.59.75

Why: the distance from 3 was 2 at the start, then 3, then 4.5, then 6.75. Every step jumps over the lowest point and lands further away on the other side. The loss grows, and the method diverges. The cure is a smaller learning rate.

Problem 15: A model with three features

A company describes the salaries of its employees with the model salary=400+120×experience+150×level+2×projects\text{salary} = 400 + 120 \times \text{experience} + 150 \times \text{level} + 2 \times \text{projects}, where the experience is in years, the level is the level of education (1, 2 or 3) and projects is the number of finished projects. (a) Predict the salary of an employee with 5 years of experience, level 2 and 30 projects. (b) What does the weight 150 mean? (c) Is the number of projects the least important feature, because its weight is the smallest?

Idea. A prediction is the intercept plus a dot product; a weight is the change per unit with the other features held fixed (Part 8).

(a)salary=400+120×5+150×2+2×30=400+600+300+60=1360\begin{aligned} \text{(a)}\quad \text{salary} &= 400 + 120 \times 5 + 150 \times 2 + 2 \times 30 \\[4pt] &= 400 + 600 + 300 + 60 = 1360 \end{aligned}

(b) For two employees with the same experience and the same number of projects, the one whose level of education is one step higher is predicted to earn 150 more.

(c) No. A weight depends on the unit of its feature. The level changes by 1 or 2 in the whole company, the number of projects by dozens: 50 more projects add 2×50=1002 \times 50 = 100, almost as much as one level of education.

Why: weights of features with different scales cannot be compared. Topic 24 shows how scaling makes them comparable.

Problem 16: The normal equation by hand

Find the least-squares line for the points (0,2)(0, 2), (1,3)(1, 3), (2,7)(2, 7) with the normal equation w=(XTX)−1XTy\mathbf{w} = (X^{T} X)^{-1} X^{T} \mathbf{y}, and check the result with the formulas of Part 5.

Idea. XX gets a first column of ones; the rest is the matrix work of Topic 14 (Part 8).

X=[101112]y=[237]X = \begin{bmatrix} 1 & 0 \\ 1 & 1 \\ 1 & 2 \end{bmatrix} \qquad \mathbf{y} = \begin{bmatrix} 2 \\ 3 \\ 7 \end{bmatrix}
XTX=[3335]XTy=[1217]X^{T} X = \begin{bmatrix} 3 & 3 \\ 3 & 5 \end{bmatrix} \qquad X^{T} \mathbf{y} = \begin{bmatrix} 12 \\ 17 \end{bmatrix}
det⁡(XTX)=3×5−3×3=6(XTX)−1=16[5−3−33]\begin{aligned} \det(X^{T} X) &= 3 \times 5 - 3 \times 3 = 6 \\[6pt] (X^{T} X)^{-1} &= \frac{1}{6} \begin{bmatrix} 5 & -3 \\ -3 & 3 \end{bmatrix} \end{aligned}
w=16[5×12−3×17−3×12+3×17]=16[915]=[1.52.5]\begin{aligned} \mathbf{w} &= \frac{1}{6} \begin{bmatrix} 5 \times 12 - 3 \times 17 \\ -3 \times 12 + 3 \times 17 \end{bmatrix} \\[6pt] &= \frac{1}{6} \begin{bmatrix} 9 \\ 15 \end{bmatrix} = \begin{bmatrix} 1.5 \\ 2.5 \end{bmatrix} \end{aligned}
check: xˉ=1,yˉ=4products: 2+0+3=5squares: 2w1=52=2.5w0=4−2.5×1=1.5\begin{aligned} & \text{check: } \bar{x} = 1, \quad \bar{y} = 4 \\[4pt] & \text{products: } 2 + 0 + 3 = 5 \qquad \text{squares: } 2 \\[4pt] & w_1 = \frac{5}{2} = 2.5 \qquad w_0 = 4 - 2.5 \times 1 = 1.5 \end{aligned}

Why: y^=1.5+2.5x\hat{y} = 1.5 + 2.5x both ways. The entries of XTXX^{T} X and XTyX^{T} \mathbf{y} are the sums nn, ∑x\sum x, ∑x2\sum x^2, ∑y\sum y and ∑xy\sum xy: the normal equation is the formula of Part 5 in the language of matrices, and it stays the same when XX gets more columns.

Problem 17: The deliveries with scikit-learn

Train a linear regression on the four deliveries of Problem 7 with scikit-learn. Print the intercept, the slope and the prediction for 5 km.

Idea. Reshape the feature into a column, then create, fit, predict (Part 9).

Python
import numpy as np
from sklearn.linear_model import LinearRegression

distance = np.array([2, 4, 6, 8])
minutes = np.array([11, 15, 22, 24])

X = distance.reshape(-1, 1)
model = LinearRegression()
model.fit(X, minutes)

print(round(model.intercept_, 2), model.coef_.round(2))
print(model.predict(np.array([[5]])).round(2))

Output

6.5 [2.3]
[18.]

Why: the same numbers as by hand: 6.5, 2.3 and 18 minutes. predict needs a table, so even one value is written with double brackets.

Problem 18: The measures with scikit-learn

For the model of Problem 17, print the MSE, the RMSE, the MAE and R².

Idea. The functions of sklearn.metrics take the true values first, then the predictions (Part 9). This cell continues from the cell of Problem 17.

Python, continues from the cells above
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score, root_mean_squared_error

predicted = model.predict(X)

print(round(mean_squared_error(minutes, predicted), 4))
print(round(root_mean_squared_error(minutes, predicted), 4))
print(round(mean_absolute_error(minutes, predicted), 4))
print(round(r2_score(minutes, predicted), 4))

Output

1.05
1.0247
0.85
0.9618

Why: by hand: the residuals are −0.1, −0.7, 1.7, −0.9-0.1,\ -0.7,\ 1.7,\ -0.9, so SSE=4.2\text{SSE} = 4.2, MSE=1.05\text{MSE} = 1.05, RMSE=1.0247\text{RMSE} = 1.0247, MAE=0.85\text{MAE} = 0.85, and with SST=110\text{SST} = 110 the score is R2=0.9618R^2 = 0.9618. The predictions are off by about one minute.

Level 3: Regression in code

Problem 19: The formulas in NumPy

For the cafe of Problem 12, calculate the slope and the intercept with the formulas of Part 5 in NumPy, without scikit-learn.

Idea. Deviations are one subtraction for a whole array (Topic 9).

Python
import numpy as np

temperature = np.array([10, 15, 20, 25, 30])
drinks = np.array([20, 24, 32, 35, 44])

x_dev = temperature - temperature.mean()
y_dev = drinks - drinks.mean()

w1 = (x_dev * y_dev).sum() / (x_dev ** 2).sum()
w0 = drinks.mean() - w1 * temperature.mean()

print(round(w1, 2), round(w0, 2))
print(round(w0 + w1 * 22, 2))

Output

1.18 7.4
33.36

Why: the two lines with sum() are the two sums of the table in Problem 12. The last line is the prediction for a day with 22 degrees.

Problem 20: R² in two ways

For the cars of Problem 10, calculate R² from its definition with NumPy and compare it with model.score.

Idea. R2=1−SSESSTR^2 = 1 - \dfrac{\text{SSE}}{\text{SST}} (Part 7); score gives the same number (Part 9).

Python
import numpy as np
from sklearn.linear_model import LinearRegression

age = np.array([1, 2, 3, 4, 5])
price = np.array([18, 16, 15, 12, 9])
X = age.reshape(-1, 1)

model = LinearRegression()
model.fit(X, price)
predicted = model.predict(X)

sse = ((price - predicted) ** 2).sum()
sst = ((price - price.mean()) ** 2).sum()

print(round(sse, 2), round(sst, 2))
print(round(1 - sse / sst, 4))
print(round(model.score(X, price), 4))

Output

1.6 50.0
0.968
0.968

Why: the SSE 1.6, the SST 50 and the score 0.968 of the calculation by hand. score is only a shorter way of writing the same formula.

Problem 21: A function for the loss

Write a function mse(w0, w1) that returns the mean squared error of the line y^=w0+w1x\hat{y} = w_0 + w_1 x on the five students. Use it to compare the three lines of Part 4.

Idea. The loss is a function of the parameters: the data stays the same, the line changes (Part 4).

Python
import numpy as np

hours = np.array([2, 4, 5, 6, 8])
marks = np.array([50, 60, 65, 75, 80])

def mse(w0, w1):
    predicted = w0 + w1 * hours
    return ((marks - predicted) ** 2).mean()

print(mse(40, 5))
print(mse(30, 7))
print(mse(39.75, 5.25))

Output

5.0
17.0
3.75

Why: the values 5, 17 and 3.75 of the table in Part 4. Training a model is the search for the inputs of this function that give the smallest output.

Problem 22: Gradient descent with one parameter

Repeat the table of Part 6 in code: the points (1,2)(1, 2) and (2,4)(2, 4), the model y^=w x\hat{y} = w\,x, the start w=0w = 0, the learning rate 0.1. Print ww and the loss after each of the first four steps, and ww after 20 steps.

Idea. One loop: the error, the slope, the update (Part 6).

Python
import numpy as np

x = np.array([1, 2])
y = np.array([2, 4])

w = 0.0
rate = 0.1

for step in range(1, 21):
    error = w * x - y
    slope = 2 * (error * x).mean()
    w = w - rate * slope
    if step <= 4:
        print(step, round(w, 4), round(((w * x - y) ** 2).mean(), 4))

print(round(w, 6))

Output

1 1.0 2.5
2 1.5 0.625
3 1.75 0.1562
4 1.875 0.0391
1.999998

Why: the values 1, 1.5, 1.75 and 1.875 of the table by hand, with the losses 2.5, 0.625, 0.1562 and 0.0391. After 20 steps ww differs from 2 only in the sixth decimal.

Problem 23: Gradient descent for a whole line

Train the line for the cars of Problem 10 by gradient descent: start at w0=0w_0 = 0, w1=0w_1 = 0, learning rate 0.05, 5,000 steps. Compare with the exact answer y^=20.6−2.2x\hat{y} = 20.6 - 2.2x.

Idea. Two slopes, two updates in every step (Part 6).

Python
import numpy as np

age = np.array([1, 2, 3, 4, 5])
price = np.array([18, 16, 15, 12, 9])

w0, w1 = 0.0, 0.0
rate = 0.05

for step in range(5000):
    error = (w0 + w1 * age) - price
    slope0 = 2 * error.mean()
    slope1 = 2 * (error * age).mean()
    w0 = w0 - rate * slope0
    w1 = w1 - rate * slope1

print(round(w0, 2), round(w1, 2))
print(round((((w0 + w1 * age) - price) ** 2).mean(), 4))

Output

20.6 -2.2
0.32

Why: the walk ends at the numbers of the formulas, and the loss at the end is the MSE of the best line, 1.6/5=0.321.6 / 5 = 0.32. Both slopes are calculated from the same error before either parameter is changed: the two updates belong to one step.

Problem 24: Several features

Eight employees are described by their years of experience and their years of education; the target is the salary. Train a multiple linear regression, print the intercept and the weights, predict the salary of a person with 6 years of experience and 16 years of education, and print R².

Idea. X is a table with two columns; everything else is unchanged (Parts 8 and 9).

Python
import numpy as np
from sklearn.linear_model import LinearRegression

people = np.array([
    [1, 12],
    [2, 16],
    [3, 12],
    [5, 16],
    [6, 14],
    [8, 12],
    [9, 16],
    [10, 18],
])
salary = np.array([820, 1190, 1060, 1540, 1490, 1620, 2010, 2290])

model = LinearRegression()
model.fit(people, salary)

print(round(model.intercept_, 1))
print(model.coef_.round(1))
print(model.predict(np.array([[6, 16]])).round(0))
print(round(model.score(people, salary), 4))

Output

-131.2
[116.4  68.5]
[1663.]
0.9984

Why: coef_ has one weight for each column, in the order of the columns: the first is the change per year of experience with the education held fixed, the second the change per year of education with the experience held fixed. The intercept is negative. It is the prediction for a person with 0 years of experience and 0 years of education, far outside the data, and has no meaning of its own: it only puts the plane at the right height.

Problem 25: The effect of one outlier

Train a line on the five students, and a second line on the same students plus one more with 9 hours and a mark of 40. Print the slope and R² of both models.

Idea. The squared loss lets one distant point pull the line (Part 10).

Python
import numpy as np
from sklearn.linear_model import LinearRegression

hours = np.array([2, 4, 5, 6, 8])
marks = np.array([50, 60, 65, 75, 80])

hours_more = np.append(hours, 9)
marks_more = np.append(marks, 40)

for x, y in [(hours, marks), (hours_more, marks_more)]:
    X = x.reshape(-1, 1)
    model = LinearRegression()
    model.fit(X, y)
    print(model.coef_.round(2), round(model.intercept_, 2), round(model.score(X, y), 4))

Output

[5.25] 39.75 0.9671
[0.55] 58.55 0.0089

Why: one extra point turns a slope of 5.25 into a slope near half a mark per hour, and the R² falls from 0.97 to almost nothing. Always look at the points before trusting a line.

Problem 26: A line through noisy data

Generate 60 points with y=3x+10y = 3x + 10 plus random noise and train a line on them. Print the intercept and the slope, R² and the RMSE. Draw the points and the line.

Idea. With noise in the data the model finds the true line only approximately, and the RMSE shows the size of the noise (Parts 7 and 9).

Python
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import root_mean_squared_error

rng = np.random.default_rng(1)
x = rng.uniform(0, 20, 60).round(1)
y = (3 * x + 10 + rng.normal(0, 5, 60)).round(1)

X = x.reshape(-1, 1)
model = LinearRegression()
model.fit(X, y)

print(round(model.intercept_, 2), model.coef_.round(2))
print(round(model.score(X, y), 3))
print(round(root_mean_squared_error(y, model.predict(X)), 2))

Output

8.84 [3.08]
0.947
4.09

The chart, in a second cell:

Python, continues from the cells above
import matplotlib.pyplot as plt

plt.scatter(x, y, label="the 60 points")
plt.plot(x, model.predict(X), color="orange", label="regression line")
plt.xlabel("x")
plt.ylabel("y")
plt.title("A line through noisy data")
plt.legend()
plt.show()
Chart: A line through noisy data

Why: the model recovers numbers close to the 10 and the 3 that generated the data. The noise had a standard deviation of 5, and the RMSE is about that size: the model cannot predict the noise, so this is as good as any model can be here.

13Practice problems

Thirty problems in two groups. Problems 1 to 15 are solved on paper with a calculator; problems 16 to 30 are written in Python. Under every problem there is a hint and a full solution: look at the hint only when you are stuck, and at the solution only after you have an answer of your own.

13.1Group A: by hand

  1. 1.A model is y^=12+3x\hat{y} = 12 + 3x. Find the prediction for x=4x = 4 and for x=10x = 10.

    Show a hint
    Put the value into the equation.
    Show one possible solution

    Answer: 24 and 42.

    x=4:y^=12+3×4=24x=10:y^=12+3×10=42\begin{aligned} x = 4:\quad \hat{y} &= 12 + 3 \times 4 = 24 \\[4pt] x = 10:\quad \hat{y} &= 12 + 3 \times 10 = 42 \end{aligned}
  2. 2.The charge of a telephone battery in percent, xx hours after it was unplugged, follows y^=98−8x\hat{y} = 98 - 8x. (a) What was the charge at the start? (b) How many percent are lost every hour? (c) What is the predicted charge after 6 hours?

    Show a hint
    The intercept is the value at x=0x = 0, the slope the change per hour.
    Show one possible solution

    Answer: (a) 98 percent; (b) 8 percent; (c) 50 percent.

    At x=0x = 0 the prediction is 98: the charge when the telephone was unplugged. The slope −8-8 says that every hour takes away 8 percent.

    y^=98−8×6=98−48=50\hat{y} = 98 - 8 \times 6 = 98 - 48 = 50
  3. 3.Five points: (1,2)(1, 2), (2,4)(2, 4), (3,5)(3, 5), (4,4)(4, 4), (5,5)(5, 5). For the line y^=2.2+0.6x\hat{y} = 2.2 + 0.6x, find the residual of the first point, of the third point and of the fifth point.

    Show a hint
    e=y−y^e = y - \hat{y}. The predictions are 2.8, 3.4, 4, 4.6 and 5.2.
    Show one possible solution

    Answer: −0.8-0.8, 11 and −0.2-0.2. (All five residuals: −0.8, 0.6, 1, −0.6, −0.2-0.8,\ 0.6,\ 1,\ -0.6,\ -0.2.)

    predictions: 2.8, 3.4, 4, 4.6, 5.22−2.8=−0.84−3.4=0.65−4=14−4.6=−0.65−5.2=−0.2\begin{aligned} & \text{predictions: } 2.8,\ 3.4,\ 4,\ 4.6,\ 5.2 \\[4pt] & 2 - 2.8 = -0.8 \qquad 4 - 3.4 = 0.6 \\[4pt] & 5 - 4 = 1 \qquad 4 - 4.6 = -0.6 \\[4pt] & 5 - 5.2 = -0.2 \end{aligned}

    The five residuals add up to 0.

  4. 4.Find the SSE and the MSE of the line of Problem 3.

    Show a hint
    Square the five residuals and add them; then divide by 5.
    Show one possible solution

    Answer: SSE = 2.4, MSE = 0.48.

    SSE=0.64+0.36+1+0.36+0.04=2.4MSE=2.45=0.48\begin{aligned} \text{SSE} &= 0.64 + 0.36 + 1 + 0.36 + 0.04 = 2.4 \\[4pt] \text{MSE} &= \frac{2.4}{5} = 0.48 \end{aligned}
  5. 5.Four points: (2,3)(2, 3), (4,7)(4, 7), (6,8)(6, 8), (8,12)(8, 12). Find the SSE of the line y^=1+1.3x\hat{y} = 1 + 1.3x and the SSE of the line y^=0.5+1.4x\hat{y} = 0.5 + 1.4x. Which line fits better?

    Show a hint
    Four residuals for each line.
    Show one possible solution

    Answer: 2 and 1.8; the second line fits better.

    first line, predictions: 3.6, 6.2, 8.8, 11.4residuals: −0.6, 0.8, −0.8, 0.6SSE=0.36+0.64+0.64+0.36=2second line, predictions: 3.3, 6.1, 8.9, 11.7residuals: −0.3, 0.9, −0.9, 0.3SSE=0.09+0.81+0.81+0.09=1.8\begin{aligned} & \text{first line, predictions: } 3.6,\ 6.2,\ 8.8,\ 11.4 \\[4pt] & \text{residuals: } -0.6,\ 0.8,\ -0.8,\ 0.6 \\[4pt] & \text{SSE} = 0.36 + 0.64 + 0.64 + 0.36 = 2 \\[8pt] & \text{second line, predictions: } 3.3,\ 6.1,\ 8.9,\ 11.7 \\[4pt] & \text{residuals: } -0.3,\ 0.9,\ -0.9,\ 0.3 \\[4pt] & \text{SSE} = 0.09 + 0.81 + 0.81 + 0.09 = 1.8 \end{aligned}
  6. 6.Find the least-squares line for the points of Problem 3: (1,2)(1, 2), (2,4)(2, 4), (3,5)(3, 5), (4,4)(4, 4), (5,5)(5, 5).

    Show a hint
    xˉ=3\bar{x} = 3, yˉ=4\bar{y} = 4. Make the table of deviations.
    Show one possible solution

    Answer: y^=2.2+0.6x\hat{y} = 2.2 + 0.6x.

    deviations of x: −2, −1, 0, 1, 2deviations of y: −2, 0, 1, 0, 1products: 4+0+0+0+2=6squares: 4+1+0+1+4=10w1=610=0.6w0=4−0.6×3=2.2\begin{aligned} & \text{deviations of } x:\ -2,\ -1,\ 0,\ 1,\ 2 \\[4pt] & \text{deviations of } y:\ -2,\ 0,\ 1,\ 0,\ 1 \\[4pt] & \text{products: } 4 + 0 + 0 + 0 + 2 = 6 \\[4pt] & \text{squares: } 4 + 1 + 0 + 1 + 4 = 10 \\[4pt] & w_1 = \frac{6}{10} = 0.6 \\[4pt] & w_0 = 4 - 0.6 \times 3 = 2.2 \end{aligned}
  7. 7.Find the least-squares line for the points of Problem 5: (2,3)(2, 3), (4,7)(4, 7), (6,8)(6, 8), (8,12)(8, 12). Then predict yy for x=5x = 5.

    Show a hint
    xˉ=5\bar{x} = 5, yˉ=7.5\bar{y} = 7.5.
    Show one possible solution

    Answer: y^=0.5+1.4x\hat{y} = 0.5 + 1.4x; the prediction is 7.5.

    deviations of x: −3, −1, 1, 3deviations of y: −4.5, −0.5, 0.5, 4.5products: 13.5+0.5+0.5+13.5=28squares: 9+1+1+9=20w1=2820=1.4w0=7.5−1.4×5=0.5x=5:y^=0.5+7=7.5\begin{aligned} & \text{deviations of } x:\ -3,\ -1,\ 1,\ 3 \\[4pt] & \text{deviations of } y:\ -4.5,\ -0.5,\ 0.5,\ 4.5 \\[4pt] & \text{products: } 13.5 + 0.5 + 0.5 + 13.5 = 28 \\[4pt] & \text{squares: } 9 + 1 + 1 + 9 = 20 \\[4pt] & w_1 = \frac{28}{20} = 1.4 \\[4pt] & w_0 = 7.5 - 1.4 \times 5 = 0.5 \\[4pt] & x = 5:\quad \hat{y} = 0.5 + 7 = 7.5 \end{aligned}

    The prediction is the mean of yy, because 5 is the mean of xx.

  8. 8.A tank loses water. After 0, 2, 4 and 6 hours it holds 10, 8, 5 and 1 litres. Find the least-squares line and predict the amount after 3 hours.

    Show a hint
    The slope will be negative. xˉ=3\bar{x} = 3, yˉ=6\bar{y} = 6.
    Show one possible solution

    Answer: y^=10.5−1.5x\hat{y} = 10.5 - 1.5x; 6 litres.

    deviations of x: −3, −1, 1, 3deviations of y: 4, 2, −1, −5products: −12−2−1−15=−30squares: 9+1+1+9=20w1=−3020=−1.5w0=6−(−1.5)×3=10.5x=3:y^=10.5−4.5=6\begin{aligned} & \text{deviations of } x:\ -3,\ -1,\ 1,\ 3 \\[4pt] & \text{deviations of } y:\ 4,\ 2,\ -1,\ -5 \\[4pt] & \text{products: } -12 - 2 - 1 - 15 = -30 \\[4pt] & \text{squares: } 9 + 1 + 1 + 9 = 20 \\[4pt] & w_1 = \frac{-30}{20} = -1.5 \\[4pt] & w_0 = 6 - (-1.5) \times 3 = 10.5 \\[4pt] & x = 3:\quad \hat{y} = 10.5 - 4.5 = 6 \end{aligned}
  9. 9.For the line of Problem 8, find the MSE, the RMSE and the MAE.

    Show a hint
    The predictions are 10.5, 7.5, 4.5 and 1.5.
    Show one possible solution

    Answer: MSE = 0.25, RMSE = 0.5, MAE = 0.5.

    residuals: −0.5, 0.5, 0.5, −0.5SSE=0.25+0.25+0.25+0.25=1MSE=14=0.25RMSE=0.25=0.5MAE=0.5+0.5+0.5+0.54=0.5\begin{aligned} & \text{residuals: } -0.5,\ 0.5,\ 0.5,\ -0.5 \\[4pt] & \text{SSE} = 0.25 + 0.25 + 0.25 + 0.25 = 1 \\[4pt] & \text{MSE} = \frac{1}{4} = 0.25 \\[4pt] & \text{RMSE} = \sqrt{0.25} = 0.5 \\[4pt] & \text{MAE} = \frac{0.5 + 0.5 + 0.5 + 0.5}{4} = 0.5 \end{aligned}

    All four errors have the same size, so the RMSE and the MAE are equal.

  10. 10.Find R² for the line of Problem 3. Its SSE is 2.4, and the yy values are 2, 4, 5, 4 and 5.

    Show a hint
    yˉ=4\bar{y} = 4. SST is the sum of the squared deviations of yy.
    Show one possible solution

    Answer: R2=0.6R^2 = 0.6.

    SST=4+0+1+0+1=6R2=1−2.46=1−0.4=0.6\begin{aligned} \text{SST} &= 4 + 0 + 1 + 0 + 1 = 6 \\[4pt] R^2 &= 1 - \frac{2.4}{6} = 1 - 0.4 = 0.6 \end{aligned}

    The line explains 60 percent of the variation.

  11. 11.A shop spent 10, 20, 30, 40 and 50 on advertising in five weeks and sold 25, 45, 50, 70 and 85 units. (a) Find the least-squares line. (b) Find the RMSE. (c) Find R². (d) Predict the sales for 35.

    Show a hint
    xˉ=30\bar{x} = 30, yˉ=55\bar{y} = 55.
    Show one possible solution

    Answer: (a) y^=11.5+1.45x\hat{y} = 11.5 + 1.45x; (b) 3.0822; (c) 0.9779; (d) 62.25.

    (a)deviations of x: −20, −10, 0, 10, 20deviations of y: −30, −10, −5, 15, 30products: 600+100+0+150+600=1450squares: 400+100+0+100+400=1000w1=14501000=1.45w0=55−1.45×30=11.5\begin{aligned} & \text{(a)} \\ & \text{deviations of } x:\ -20,\ -10,\ 0,\ 10,\ 20 \\[4pt] & \text{deviations of } y:\ -30,\ -10,\ -5,\ 15,\ 30 \\[4pt] & \text{products: } 600 + 100 + 0 + 150 + 600 = 1450 \\[4pt] & \text{squares: } 400 + 100 + 0 + 100 + 400 = 1000 \\[4pt] & w_1 = \frac{1450}{1000} = 1.45 \\[4pt] & w_0 = 55 - 1.45 \times 30 = 11.5 \end{aligned}
    (b)predictions: 26, 40.5, 55, 69.5, 84residuals: −1, 4.5, −5, 0.5, 1SSE=1+20.25+25+0.25+1=47.5MSE=47.55=9.5RMSE=9.5=3.0822(c)SST=900+100+25+225+900=2150R2=1−47.52150=0.9779(d)y^=11.5+1.45×35=11.5+50.75=62.25\begin{aligned} & \text{(b)} \\ & \text{predictions: } 26,\ 40.5,\ 55,\ 69.5,\ 84 \\[4pt] & \text{residuals: } -1,\ 4.5,\ -5,\ 0.5,\ 1 \\[4pt] & \text{SSE} = 1 + 20.25 + 25 + 0.25 + 1 = 47.5 \\[4pt] & \text{MSE} = \frac{47.5}{5} = 9.5 \\[4pt] & \text{RMSE} = \sqrt{9.5} = 3.0822 \\[6pt] & \text{(c)} \\ & \text{SST} = 900 + 100 + 25 + 225 + 900 = 2150 \\[4pt] & R^2 = 1 - \frac{47.5}{2150} = 0.9779 \\[6pt] & \text{(d)} \\ & \hat{y} = 11.5 + 1.45 \times 35 = 11.5 + 50.75 = 62.25 \end{aligned}
  12. 12.Two points: (1,4)(1, 4) and (2,8)(2, 8). The model is y^=w x\hat{y} = w\,x, and the slope of the loss is 5w−205w - 20. Start at w=0w = 0 and take three steps of gradient descent with α=0.1\alpha = 0.1. Give ww after each step.

    Show a hint
    wnew=wold−0.1×(5w−20)w_{\text{new}} = w_{\text{old}} - 0.1 \times (5w - 20).
    Show one possible solution

    Answer: 2, 3, 3.52,\ 3,\ 3.5.

    step 1:slope=−20w=0−0.1×(−20)=2step 2:slope=5×2−20=−10w=2+1=3step 3:slope=5×3−20=−5w=3+0.5=3.5\begin{aligned} \text{step 1:}\quad & \text{slope} = -20 \\ & w = 0 - 0.1 \times (-20) = 2 \\[6pt] \text{step 2:}\quad & \text{slope} = 5 \times 2 - 20 = -10 \\ & w = 2 + 1 = 3 \\[6pt] \text{step 3:}\quad & \text{slope} = 5 \times 3 - 20 = -5 \\ & w = 3 + 0.5 = 3.5 \end{aligned}

    The lowest point is w=4w = 4, where both points lie on the line.

  13. 13.For the data and the model of Problem 12 (the slope of the loss is 5w−205w - 20): (a) With α=0.4\alpha = 0.4 and the start w=0w = 0, what is ww after one step, and after two steps? (b) Which learning rate reaches the lowest point w=4w = 4 in a single step from w=0w = 0?

    Show a hint
    (b) The first step has the length α×20\alpha \times 20.
    Show one possible solution

    Answer: (a) 8, then 0: it jumps between 8 and 0 for ever; (b) α=0.2\alpha = 0.2.

    (a)w=0−0.4×(−20)=8slope=5×8−20=20w=8−0.4×20=0(b)α×20=4,α=0.2check: w=0−0.2×(−20)=4\begin{aligned} \text{(a)}\quad & w = 0 - 0.4 \times (-20) = 8 \\[4pt] & \text{slope} = 5 \times 8 - 20 = 20 \\[4pt] & w = 8 - 0.4 \times 20 = 0 \\[6pt] \text{(b)}\quad & \alpha \times 20 = 4, \quad \alpha = 0.2 \\[4pt] & \text{check: } w = 0 - 0.2 \times (-20) = 4 \end{aligned}

    With 0.4 every step jumps exactly to the other side of the bowl.

  14. 14.A model for the price of a flat, in thousands, is price=30+2×area+8×rooms−1.5×distance\text{price} = 30 + 2 \times \text{area} + 8 \times \text{rooms} - 1.5 \times \text{distance}, with the area in m² and the distance to the centre in km. (a) Predict the price of a flat with 70 m², 2 rooms, 6 km from the centre. (b) What is the predicted price of a flat that differs only by having 3 rooms? (c) By how much does the predicted price fall for every kilometre further from the centre?

    Show a hint
    (b) Only one feature changes, by 1.
    Show one possible solution

    Answer: (a) 177; (b) 185; (c) 1.5 thousand, for the same area and number of rooms.

    (a)30+2×70+8×2−1.5×6=30+140+16−9=177(b)177+8=185\begin{aligned} \text{(a)}\quad & 30 + 2 \times 70 + 8 \times 2 - 1.5 \times 6 \\ & = 30 + 140 + 16 - 9 = 177 \\[4pt] \text{(b)}\quad & 177 + 8 = 185 \end{aligned}

    (c) The weight of a feature is the change of the prediction per unit of that feature while the other features stay the same: every kilometre takes away 1.5 thousand.

  15. 15.Find the least-squares line for the points (0,1)(0, 1), (1,2)(1, 2), (2,6)(2, 6) with the normal equation.

    Show a hint
    XTXX^{T} X has the entries 3, 3, 3, 5, and XTyX^{T} \mathbf{y} has the entries 9 and 14.
    Show one possible solution

    Answer: y^=0.5+2.5x\hat{y} = 0.5 + 2.5x.

    det⁡(XTX)=3×5−3×3=6(XTX)−1=16[5−3−33]w0=5×9−3×146=36=0.5w1=−3×9+3×146=156=2.5\begin{aligned} \det(X^{T} X) &= 3 \times 5 - 3 \times 3 = 6 \\[6pt] (X^{T} X)^{-1} &= \frac{1}{6} \begin{bmatrix} 5 & -3 \\ -3 & 3 \end{bmatrix} \\[6pt] w_0 &= \frac{5 \times 9 - 3 \times 14}{6} = \frac{3}{6} = 0.5 \\[6pt] w_1 &= \frac{-3 \times 9 + 3 \times 14}{6} = \frac{15}{6} = 2.5 \end{aligned}

    Check with Part 5: xˉ=1\bar{x} = 1, yˉ=3\bar{y} = 3, the sum of the products is 2+0+3=52 + 0 + 3 = 5, the sum of the squares is 2, so w1=2.5w_1 = 2.5 and w0=3−2.5=0.5w_0 = 3 - 2.5 = 0.5.

13.2Group B: in Python

The fifteen Python problems are one notebook. This first cell imports everything they need, and every problem continues from it, so you do not have to type the imports again. The data of a problem is already in its editor.

Python
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score, root_mean_squared_error

Easy

The shape of the data, a first model, predictions and residuals.

  1. 16.Reshape x into a table X with one column. Print the shape of X, then its first row.
    Show a hint
    X = x.reshape(-1, 1), then print(X.shape) and print(X[0]).
    Show one possible solution
    Python, continues from the cells above
    x = np.array([3, 5, 7, 9])
    
    X = x.reshape(-1, 1)
    
    print(X.shape)
    print(X[0])

    Output

    (4, 1)
    [3]
  2. 17.Train a LinearRegression on x and y. Print the intercept and the slope on one line, each rounded to 2 decimals.
    Show a hint
    model.fit(x.reshape(-1, 1), y). The intercept is model.intercept_, the slope is model.coef_[0]: print(round(model.intercept_, 2), round(model.coef_[0], 2)).
    Show one possible solution
    Python, continues from the cells above
    x = np.array([3, 5, 7, 9])
    y = np.array([4, 7, 8, 13])
    
    model = LinearRegression()
    model.fit(x.reshape(-1, 1), y)
    
    print(round(model.intercept_, 2), round(model.coef_[0], 2))

    Output

    -0.4 1.4
  3. 18.Train a model on x and y. Print its predictions for x = 6 and x = 10 as one array, rounded to 2 decimals.
    Show a hint
    The new values must be a table with one column: model.predict(np.array([[6], [10]])).round(2).
    Show one possible solution
    Python, continues from the cells above
    x = np.array([3, 5, 7, 9])
    y = np.array([4, 7, 8, 13])
    
    model = LinearRegression()
    model.fit(x.reshape(-1, 1), y)
    
    print(model.predict(np.array([[6], [10]])).round(2))

    Output

    [ 8.  13.6]
  4. 19.Train a model on x and y. Print the predictions for the four points, and on a second line the residuals, both rounded to 2 decimals.
    Show a hint
    predicted = model.predict(X), and the residuals are y - predicted. Print each array with .round(2).
    Show one possible solution
    Python, continues from the cells above
    x = np.array([2, 4, 6, 8])
    y = np.array([3, 7, 8, 12])
    
    X = x.reshape(-1, 1)
    model = LinearRegression()
    model.fit(X, y)
    
    predicted = model.predict(X)
    print(predicted.round(2))
    print((y - predicted).round(2))

    Output

    [ 3.3  6.1  8.9 11.7]
    [-0.3  0.9 -0.9  0.3]
  5. 20.Train a model on x and y. Calculate the MSE and the RMSE with NumPy, without sklearn.metrics. Print both on one line, rounded to 4 decimals.
    Show a hint
    The MSE is the mean of the squared residuals: mse = (residuals ** 2).mean(). The RMSE is np.sqrt(mse).
    Show one possible solution
    Python, continues from the cells above
    x = np.array([1, 2, 3, 4, 5])
    y = np.array([2, 4, 5, 4, 5])
    
    X = x.reshape(-1, 1)
    model = LinearRegression()
    model.fit(X, y)
    
    residuals = y - model.predict(X)
    mse = (residuals ** 2).mean()
    
    print(round(mse, 4), round(np.sqrt(mse), 4))

    Output

    0.48 0.6928

Medium

The measures, the formulas in NumPy and a first gradient descent.

  1. 21.Train a model on x and y. Print the MAE, and on a second line R², each rounded to 4 decimals. Use mean_absolute_error and r2_score.
    Show a hint
    Both functions take the true values first: mean_absolute_error(y, predicted) and r2_score(y, predicted).
    Show one possible solution
    Python, continues from the cells above
    x = np.array([10, 20, 30, 40, 50])
    y = np.array([25, 45, 50, 70, 85])
    
    X = x.reshape(-1, 1)
    model = LinearRegression()
    model.fit(X, y)
    predicted = model.predict(X)
    
    print(round(mean_absolute_error(y, predicted), 4))
    print(round(r2_score(y, predicted), 4))

    Output

    2.4
    0.9779
  2. 22.Train a model on x and y. Print model.score(X, y) and r2_score(y, predicted) on one line, each rounded to 4 decimals.
    Show a hint
    score gets X and y. r2_score gets y and the predictions model.predict(X).
    Show one possible solution
    Python, continues from the cells above
    x = np.array([0, 2, 4, 6])
    y = np.array([10, 8, 5, 1])
    
    X = x.reshape(-1, 1)
    model = LinearRegression()
    model.fit(X, y)
    
    print(round(model.score(X, y), 4), round(r2_score(y, model.predict(X)), 4))

    Output

    0.9783 0.9783
  3. 23.Calculate the slope and the intercept with the formulas of Part 5, without scikit-learn. Print the slope and the intercept on one line, each rounded to 2 decimals.
    Show a hint
    x_dev = x - x.mean() and y_dev = y - y.mean(). The slope is (x_dev * y_dev).sum() / (x_dev ** 2).sum(), the intercept y.mean() - w1 * x.mean().
    Show one possible solution
    Python, continues from the cells above
    x = np.array([10, 20, 30, 40, 50])
    y = np.array([25, 45, 50, 70, 85])
    
    x_dev = x - x.mean()
    y_dev = y - y.mean()
    w1 = (x_dev * y_dev).sum() / (x_dev ** 2).sum()
    w0 = y.mean() - w1 * x.mean()
    
    print(round(w1, 2), round(w0, 2))

    Output

    1.45 11.5
  4. 24.Write a function sse(w0, w1) that returns the sum of the squared residuals of the line w0 + w1 * x. The two print lines are already there.
    Show a hint
    Inside the function: predicted = w0 + w1 * x, then return ((y - predicted) ** 2).sum().
    Show one possible solution
    Python, continues from the cells above
    x = np.array([2, 4, 6, 8])
    y = np.array([3, 7, 8, 12])
    
    def sse(w0, w1):
        predicted = w0 + w1 * x
        return ((y - predicted) ** 2).sum()
    
    print(round(sse(1, 1.3), 2))
    print(round(sse(0.5, 1.4), 2))

    Output

    2.0
    1.8
  5. 25.The model is w * x. Start at w = 0.0 and take 10 steps of gradient descent with the learning rate 0.1. Print w, rounded to 4 decimals.
    Show a hint
    In every step: error = w * x - y, slope = 2 * (error * x).mean(), w = w - 0.1 * slope.
    Show one possible solution
    Python, continues from the cells above
    x = np.array([1, 2])
    y = np.array([4, 8])
    
    w = 0.0
    rate = 0.1
    for step in range(10):
        error = w * x - y
        slope = 2 * (error * x).mean()
        w = w - rate * slope
    
    print(round(w, 4))

    Output

    3.9961

Medium-Hard

Gradient descent for a whole line, several features, an outlier and data with noise.

  1. 26.Find the line w0 + w1 * x by gradient descent: start at w0 = 0.0, w1 = 0.0, learning rate 0.05, 5000 steps. Print w0 and w1 on one line, each rounded to 2 decimals.
    Show a hint
    In every step: error = (w0 + w1 * x) - y, slope0 = 2 * error.mean(), slope1 = 2 * (error * x).mean(). Calculate both slopes before you change w0 and w1.
    Show one possible solution
    Python, continues from the cells above
    x = np.array([1, 2, 3, 4, 5])
    y = np.array([2, 4, 5, 4, 5])
    
    w0, w1 = 0.0, 0.0
    rate = 0.05
    for step in range(5000):
        error = (w0 + w1 * x) - y
        slope0 = 2 * error.mean()
        slope1 = 2 * (error * x).mean()
        w0 = w0 - rate * slope0
        w1 = w1 - rate * slope1
    
    print(round(w0, 2), round(w1, 2))

    Output

    2.2 0.6
  2. 27.Every row of houses is an area and a number of rooms. Train a model. Print the two weights (rounded to 2 decimals), then the intercept (2 decimals), then the prediction for 100 m² and 3 rooms (1 decimal), on three lines.
    Show a hint
    houses already has two dimensions: no reshape. print(model.coef_.round(2)), print(round(model.intercept_, 2)), print(model.predict(np.array([[100, 3]])).round(1)).
    Show one possible solution
    Python, continues from the cells above
    houses = np.array([[50, 2], [65, 2], [80, 3], [95, 3], [110, 4], [140, 5]])
    price = np.array([110, 135, 172, 196, 235, 300])
    
    model = LinearRegression()
    model.fit(houses, price)
    
    print(model.coef_.round(2))
    print(round(model.intercept_, 2))
    print(model.predict(np.array([[100, 3]])).round(1))

    Output

    [ 1.62 14.41]
    -0.34
    [205.2]
  3. 28.Train one model on the area alone and one on both features. Print the R² of both on one line, each rounded to 4 decimals.
    Show a hint
    houses[:, [0]] is the first column as a table. Each model is scored on the features it was trained on. The R² with two features is at least as high: on the training data an extra feature can never lower it.
    Show one possible solution
    Python, continues from the cells above
    houses = np.array([[50, 2], [65, 2], [80, 3], [95, 3], [110, 4], [140, 5]])
    price = np.array([110, 135, 172, 196, 235, 300])
    
    area = houses[:, [0]]
    one = LinearRegression().fit(area, price)
    two = LinearRegression().fit(houses, price)
    
    print(round(one.score(area, price), 4), round(two.score(houses, price), 4))

    Output

    0.9971 0.9998
  4. 29.Add the point x = 60, y = 20 to the data. Print the slope without the extra point, and on a second line the slope with it, each rounded to 2 decimals.
    Show a hint
    np.append(x, 60) gives a new array with one more value. Train two models and print round(model.coef_[0], 2) of each.
    Show one possible solution
    Python, continues from the cells above
    x = np.array([10, 20, 30, 40, 50])
    y = np.array([25, 45, 50, 70, 85])
    
    x_more = np.append(x, 60)
    y_more = np.append(y, 20)
    
    first = LinearRegression().fit(x.reshape(-1, 1), y)
    second = LinearRegression().fit(x_more.reshape(-1, 1), y_more)
    
    print(round(first.coef_[0], 2))
    print(round(second.coef_[0], 2))

    Output

    1.45
    0.33
  5. 30.The 50 points were made from the line 2 * x + 5 plus random noise. Train a model on them. Print the slope and the intercept on one line (each rounded to 2 decimals), then R² (3 decimals).
    Show a hint
    X = x.reshape(-1, 1). Then print(round(model.coef_[0], 2), round(model.intercept_, 2)) and print(round(model.score(X, y), 3)). The model finds numbers close to 2 and 5, not exactly: the noise hides the true line a little.
    Show one possible solution
    Python, continues from the cells above
    rng = np.random.default_rng(7)
    x = rng.uniform(0, 10, 50).round(1)
    y = (2 * x + 5 + rng.normal(0, 2, 50)).round(1)
    
    X = x.reshape(-1, 1)
    model = LinearRegression()
    model.fit(X, y)
    
    print(round(model.coef_[0], 2), round(model.intercept_, 2))
    print(round(model.score(X, y), 3))

    Output

    1.92 5.47
    0.917

14Check yourself

Twelve questions. Every question has one right answer. Try to answer before you read the explanation.

Question 1

1.Which line does linear regression choose?

Question 2

2.In the model y^=12+3x\hat{y} = 12 + 3x, what is the slope?

Question 3

3.The model is y^=12+3x\hat{y} = 12 + 3x. What is the residual of the point (4,20)(4, 20)?

Question 4

4.Why are the residuals squared before they are added?

Question 5

5.Through which point does the least-squares line always pass?

Question 6

6.In gradient descent, the slope of the loss at the current value of ww is positive. What does the next step do?

Question 7

7.What happens when the learning rate is much too large?

Question 8

8.A model has the residuals 11, −1-1, 22 and −2-2. What is its MSE?

Question 9

9.A regression model has R2=0.85R^2 = 0.85. What does this mean?

Question 10

10.A model has SSE=20\text{SSE} = 20, and the data has SST=100\text{SST} = 100. What is R²?

Question 11

11.A model is price=20+1.5×area+10×rooms\text{price} = 20 + 1.5 \times \text{area} + 10 \times \text{rooms}. What does the weight 10 mean?

Question 12

12.After model.fit(X, y), where is the slope of a LinearRegression model stored?

0 of 12 answered.

15Quick summary

Quick summary
IdeaFormula or codeIn words
The modely^=w0+w1x\hat{y} = w_0 + w_1 xa line: intercept plus slope times the feature
Residuale=y−y^e = y - \hat{y}the vertical distance of a point from the line
SSE∑(y−y^)2\sum (y - \hat{y})^2the sum of the squared residuals
MSESSE/n\text{SSE} / nthe loss that training makes small
Slopew1=∑(x−xˉ)(y−yˉ)∑(x−xˉ)2w_1 = \frac{\sum (x - \bar{x})(y - \bar{y})}{\sum (x - \bar{x})^2}how xx and yy move together, per unit of movement of xx
Interceptw0=yˉ−w1 xˉw_0 = \bar{y} - w_1\,\bar{x}puts the line through the point of the means
Gradient descentwnew=wold−α×slopew_{\text{new}} = w_{\text{old}} - \alpha \times \text{slope}small steps downhill on the loss
RMSEMSE\sqrt{\text{MSE}}the typical error, in the unit of yy
MAE1n∑∣y−y^∣\frac{1}{n} \sum \lvert y - \hat{y} \rvertthe average absolute error
R2R^21−SSESST1 - \frac{\text{SSE}}{\text{SST}}the share of the variation that the model explains
Multiple regressiony^=w0+w1x1+⋯+wpxp\hat{y} = w_0 + w_1 x_1 + \dots + w_p x_pone weight for every feature
Normal equationw=(XTX)−1XTy\mathbf{w} = (X^{T} X)^{-1} X^{T} \mathbf{y}the best weights in one formula
scikit-learnLinearRegression().fit(X, y)then intercept_, coef_, predict, score

Rules to keep

  1. Look at the points before you fit a line: a scatter plot first, a residual plot after.
  2. The residual is true minus predicted, and the best line makes the sum of the squared residuals as small as possible.
  3. First the slope, then the intercept. The line passes through the point of the means.
  4. Report an error in the unit of the target (RMSE or MAE) and R². R² is not a share of right answers.
  5. A weight is the change per unit of its feature, with the other features held fixed. It is not a cause.
  6. Do not predict far outside the range of the data, and watch for outliers.
  7. In gradient descent the loss must fall step after step. If it grows, lower the learning rate.
  8. In scikit-learn X is a table with two dimensions: reshape(-1, 1) for a single feature.

What comes next

Every model of this lesson was measured on the same points it had learned from. Is that a fair measure? Topic 23 answers the question: it teaches the train/test split and cross-validation, and what overfitting, underfitting and the bias-variance tradeoff are. After that, Topics 24 and 25 prepare the features of a model: scaling numerical values, encoding categories and handling outliers.