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.
Lesson notebook
The lesson as a Jupyter notebook: the explanations with their formulas, every example as a short cell, and the 26 solved problems.
topic-22-linear-regression.ipynb, 101 KB
Practice notebook
The 15 practice problems in Python (problems 16 to 30) as one notebook that continues from a setup cell, with a hint and a hidden solution for each.
topic-22-practice.ipynb, 24 KB
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.What linear regression is, what it does, and when it is the right model
- 2.The equation of the line: the intercept and the slope , and how to read them
- 3.Residuals: the vertical distances between the points and the line
- 4.The loss function: why the squared distances are added, SSE and MSE
- 5.The least-squares formulas for the best line, and why the best line passes through the point of the means
- 6.The idea of a gradient and of gradient descent: the learning rate, the steps, and what can go wrong
- 7.How to measure a regression model: MSE, RMSE, MAE and the R² score
- 8.Multiple linear regression: several features, the formula with a dot product and with matrices, and how to read the weights
- 9.Linear regression in Python: NumPy arrays,
LinearRegression,fit,predict,coef_,intercept_,score, and the functions ofsklearn.metrics - 10.The limits of the model: curves, outliers, predictions outside the data, and correlation without causation
| Written | Meaning |
|---|---|
| the feature (the input): hours of study, the area of a flat | |
| the target (the true answer): the mark, the price | |
| "y hat": the prediction of the model | |
| the number of samples (points) | |
| , | the means of and of |
| the intercept (also called the bias): the prediction for | |
| the slope (also called the weight or the coefficient): the change of when grows by 1 | |
| the residual of a point: | |
| SSE | the sum of the squared residuals (sum of squared errors) |
| MSE, RMSE, MAE | the mean squared error, its square root, and the mean absolute error |
| SST | the total sum of squares: the squared distances of the values from their mean |
| the R² score (coefficient of determination): the share of the variation that the model explains | |
| the learning rate of gradient descent (the Greek letter alpha) | |
| , | the matrix of the features and the vector of the weights (multiple regression) |
In Topic 20 the line was written . It is the same line with other letters: is and is . Books of statistics write and . Machine learning writes for "weight", because the same letters continue to work when there are many features: , , , 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:
| Student | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| Hours of study | 2 | 4 | 5 | 6 | 8 |
| Mark | 50 | 60 | 65 | 75 | 80 |
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.
Linear regression is the model that does exactly this:
- It takes points whose answers are known (the training data).
- It finds the straight line that fits those points best.
- 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:
- is the intercept: the value of when . It is the height at which the line crosses the vertical axis. In machine learning it is also called the bias.
- is the slope: how much changes when grows by 1. It is also called the weight or the coefficient of the feature.
- ("y hat") is the prediction. The hat separates what the model says () from what really happened ().
The two numbers and 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):
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: more marks.
- The intercept 39.75: a student who does not study at all () 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:
2.4The sign of the slope
| Slope | The line | Meaning | Example |
|---|---|---|---|
| rises | more , more | hours of study and the mark | |
| falls | more , less | the age of a car and its price | |
| is flat | tells nothing about | the shoe size and the mark |
The slope has the same sign as the correlation coefficient of Topic 20. But they are different numbers: has no units and always lies between and , while the slope has units ("marks per hour") and can be any number.
Try it yourself
Show a hint
Show the solution
Answer: (a) 39; (b) 12; (c) 15.
The slope 4 is the change for one unit, so three units give three times as much. At 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:
- : the point lies above the line. The model predicted too little.
- : the point lies below the line. The model predicted too much.
- : the point lies exactly on the line.
3.2The residuals of the five students
| Student | ||||
|---|---|---|---|---|
| 1 | 2 | 50 | 50.25 | |
| 2 | 4 | 60 | 60.75 | |
| 3 | 5 | 65 | 66 | |
| 4 | 6 | 75 | 71.25 | 3.75 |
| 5 | 8 | 80 | 81.75 | |
| Sum | 0 |
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 and want to predict . An error of the model is an error in , 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 and , and the sum would still say 0. The next part repairs this.
Try it yourself
Show a hint
Show the solution
Answer: , and .
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 stands for the sum of squared errors.
Dividing by the number of points gives the average squared residual, the mean squared error:
For the line of the five students:
| Student | ||
|---|---|---|
| 1 | 0.0625 | |
| 2 | 0.5625 | |
| 3 | 1 | |
| 4 | 3.75 | 14.0625 |
| 5 | 3.0625 | |
| Sum | 0 | 18.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?
| Line | Equation | Residuals | SSE | MSE |
|---|---|---|---|---|
| A | 25 | 5 | ||
| B | 85 | 17 | ||
| C | 18.75 | 3.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
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?
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
Show a hint
Show the solution
Answer: SSE = 18, MSE = 4.5.
The plain sum of these residuals is : it hides almost all of the error.
5Finding the best line with formulas (least squares)
5.1The idea
Among all pairs 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, and . 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:
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 .
5.2The calculation in five steps
- Calculate the two means and .
- Calculate the deviations and of every point.
- Multiply the two deviations of every point and add the products. Square the deviations of and add the squares.
- Divide: this is the slope .
- .
5.3Example: the five students
| Student | product | |||||
|---|---|---|---|---|---|---|
| 1 | 2 | 50 | 48 | 9 | ||
| 2 | 4 | 60 | 6 | 1 | ||
| 3 | 5 | 65 | 0 | 0 | 0 | |
| 4 | 6 | 75 | 1 | 9 | 9 | 1 |
| 5 | 8 | 80 | 3 | 14 | 42 | 9 |
| Sum | 0 | 0 | 105 | 20 |
5.4Three facts about the least-squares line
- It passes through the point of the means . Check: . This follows directly from .
- 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 values are not all equal, there is exactly one best line. (If all are equal, , 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:
where is the correlation coefficient and , 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
Show a hint
Show the solution
Answer: and , so .
Check: at the line gives , the mean of .
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:
- Start with any values of the parameters.
- Find the slope of the loss at the place where you stand.
- Move the parameters a small step in the direction in which the loss goes down.
- Repeat until the loss stops getting smaller.
6.3The slope of the loss: the gradient
To keep the first example small, take two points, and , and the simplest model: a line through the origin with only one parameter,
For every value of the loss can be calculated:
| 0 | 1 | 2 | 3 | 4 | |
|---|---|---|---|---|---|
| MSE | 10 | 2.5 | 0 | 2.5 | 10 |
The loss is a curve shaped like a bowl (a parabola), with its lowest point at , where the line passes through both points.
The slope of the loss curve at a value of says how the loss changes when grows a little:
- a negative slope: the curve goes down to the right. Making larger makes the loss smaller.
- a positive slope: the curve goes up to the right. Making 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:
Read it like this: for every point, take the error and multiply it by the feature ; add the products; multiply by . For our two points, with :
At the slope is : steeply downhill to the right. At it is : the bottom. At it is : 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
- The minus sign sends us downhill: a negative slope makes larger, a positive slope makes it smaller.
- (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 . 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 with the learning rate :
| Step | slope | step | new | MSE at the new | |
|---|---|---|---|---|---|
| 1 | 0 | 1 | 2.5 | ||
| 2 | 1 | 1.5 | 0.625 | ||
| 3 | 1.5 | 1.75 | 0.156 | ||
| 4 | 1.75 | 1.875 | 0.039 |
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.
6.6The learning rate
The learning rate decides whether the walk works.
| Learning rate | The values of | What happens |
|---|---|---|
| (too small) | every step is tiny; hundreds of steps are needed | |
| (good) | fast and steady | |
| (too large) | every step jumps over the bottom to the other side, for ever | |
| (much too large) | every jump lands further away: the loss grows without limit |
Too small: 0.01
eight steps, and hardly any progress
Good: 0.1
six steps, almost at the bottom
Too large: 0.5
every step lands further away
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.
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 there are two slopes, one for each parameter:
and both parameters are updated in every step, at the same time:
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:
The first equation says that the residuals add up to zero. Solving the two equations for and 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?
| The formulas (least squares) | Gradient descent | |
|---|---|---|
| Result | exact, in one calculation | approximate, after many steps |
| Settings | none | the learning rate, the number of steps, the starting values |
| Works for | linear regression | almost every model, also neural networks |
| Very many features or rows | becomes slow and needs much memory | stays usable |
| In scikit-learn | LinearRegression | SGDRegressor, 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
Show a hint
Show the solution
Answer: (a) 10; (b) 2; (c) 1.5.
Both points lie on the line , so the lowest point is . The walk starts above it, the slope is positive, and every step makes 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
It is the loss function of Part 4, used now as a measure of quality. For the five students: .
- The smaller, the better. 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
Taking the square root brings the unit back. For the students: .
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
The other repair of Part 4: absolute values in the place of squares. For the students:
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, . The squared errors of this guess add up to the total sum of squares:
For the students:
The model: predict with the line. Its squared errors add up to .
The line reduces the squared error from 570 to 18.75. R² is the share that was removed:
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.
Always the mean: SST = 570
The line: SSE = 18.75
7.5Reading R²
| Meaning | |
|---|---|
| 1 | every point lies on the line: |
| 0.9671 | the line removes 96.71 percent of the squared error of "always the mean" |
| 0 | the model is exactly as good as always predicting the mean |
| below 0 | the 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. 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 , and . 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 has on the five students, and .
- 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 .
- 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
| Measure | Formula | Unit | Best value | Use it to say |
|---|---|---|---|---|
| MSE | the unit of , squared | 0 | this is what training makes small | |
| RMSE | the unit of | 0 | "the predictions are off by about ..." | |
| MAE | the unit of | 0 | the plain average error, less moved by outliers | |
| none | 1 | "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.
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
Show a hint
Show the solution
Answer: MSE = 4, RMSE = 2, .
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:
- are the features of one sample.
- are their weights (coefficients).
- is the intercept.
Simple linear regression is the special case .
8.2Example: the price of a flat
Suppose a model has learned this equation (prices in thousands):
A flat with 80 m², 3 rooms, in a building that is 10 years old:
8.3Reading the weights
Every weight says how the prediction changes when its feature grows by 1 and the other features stay the same:
- : one more square metre adds 1.5 thousand, for flats with the same number of rooms and the same age.
- : one more room adds 10 thousand, for the same area and age.
- : 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):
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 with one row for every flat (Topic 14). To include the intercept, add a first column of ones, so that is multiplied by 1 in every row:
One matrix multiplication gives all predictions. This is the shape of the table X that scikit-learn expects (Topic 21): rows, columns.
8.6The best weights
The loss is the same as before:
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:
( is the transpose and the power the inverse, both from Topic 14.) With one feature it gives exactly the and 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: , , , .
The entries are sums: 4 is the number of points, 6 is , 14 is , 16 is and 35 is .
So . The formulas of Part 5 give the same: and .
Gradient descent works for many features too. There is one slope for every weight, and all of them fit into one line with matrices:
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.

8.8What changes, and what does not
| Simple linear regression | Multiple linear regression | |
|---|---|---|
| Features | 1 | (2 or more) |
| Equation | ||
| Parameters | 2 | |
| Picture | a line | a plane (2 features), not drawable beyond |
| A weight means | the change of per unit of | the same, with the other features held fixed |
| Loss | MSE | MSE |
| Best parameters | the formulas of Part 5 | the normal equation |
| Measures | MSE, RMSE, MAE, R² | the same |
| In scikit-learn | LinearRegression | LinearRegression, 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
Show a hint
Show the solution
Answer: (a) 16; (b) 6; (c) 4.
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 features has .
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:
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
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 is in model.intercept_ and the slope 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
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 , 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
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
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()
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:
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²:
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:
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:
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:
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:
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 and , 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:
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.
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()
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:
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.
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.
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):
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:
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:
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
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()
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
| Code | What 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 (one number) |
model.coef_ | the weights (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
Show a hint
temperature.reshape(-1, 1). Then print(round(model.intercept_, 2), round(model.coef_[0], 2)).Show the solution
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
Show a hint
root_mean_squared_error(price, model.predict(X)) and model.score(X, price).Show the solution
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 : exactly . The best line is , 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.
A curve with a line through it
Its residuals
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 to . 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.
Five students: slope 5.25
With one outlier: slope 0.55
The five students and a sixth one that you can move.
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 , 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
| Problem | Where it is solved |
|---|---|
| A model that fits the training data but not new data | Topic 23: train/test split, cross-validation, overfitting |
| Features on very different scales | Topic 24: scaling |
| Features that are categories (a city, a colour), and outliers | Topic 25: encoding and outliers |
| Too many features, unstable weights | Topic 26: Ridge and Lasso |
| A target that is a category | Topic 27: logistic regression |
Try it yourself
Show a hint
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
| Mistake | Why it is wrong | Right |
|---|---|---|
| Calculating the residual as . | The residual is defined as true minus predicted. With the other order the signs turn round: "above the line" becomes negative. | |
| 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 , and calling the SSE "MSE". | The SSE grows with the number of points; the MSE is the average. | |
| Reporting the MSE in the unit of . | The MSE has the squared unit. | Take the root: the RMSE has the unit of . |
| " 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. | is the value at , the change per unit. | In the slope is 5.25. |
| Calculating before . | needs the slope. | First , then . |
| 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:
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 to estimate the time of a delivery in minutes from the distance in kilometres. How long will a delivery over 5 km take? And over 10 km?
Idea. Put the distance into the equation (Part 2).
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 , where 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 , 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 : every year of age takes away 2.2 thousand.
Why: a negative slope means a falling line: more , less . 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 . Find the prediction and the residual of every month.
Idea. , true minus predicted (Part 3).
| 1 | 3 | 3.4 | |
|---|---|---|---|
| 2 | 5 | 4.2 | 0.8 |
| 3 | 4 | 5 | |
| 4 | 7 | 5.8 | 1.2 |
| 5 | 6 | 6.6 | |
| Sum | 0 |
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 (Part 4).
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: , , , . Compare the lines and by their SSE.
Idea. The line with the smaller SSE fits better (Part 4).
| first line | second line | ||||
|---|---|---|---|---|---|
| 1 | 3 | 3 | 0 | 2.7 | 0.3 |
| 2 | 5 | 5 | 0 | 4.9 | 0.1 |
| 3 | 6 | 7 | 7.1 | ||
| 4 | 10 | 9 | 1 | 9.3 | 0.7 |
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 , , , , .
Idea. , then (Part 5).
| product | |||||
|---|---|---|---|---|---|
| 0 | 1 | 6 | 4 | ||
| 1 | 3 | 1 | 1 | ||
| 2 | 4 | 0 | 0 | 0 | 0 |
| 3 | 4 | 1 | 0 | 0 | 1 |
| 4 | 8 | 2 | 4 | 8 | 4 |
| Sum | 15 | 10 |
Why: the slope compares how and move together (the top) with how much moves at all (the bottom). The intercept then puts the line through the point of the means .
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.
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 of Problem 6, find the MSE, the RMSE and the MAE.
Idea. The residuals first, then the three formulas of Part 7.
Why: the RMSE (0.84) is larger than the MAE (0.6) because the square gives the one large residual, , more weight. Both are in the unit of .
Problem 9: The R² score
Find R² for the line of Problem 6.
Idea. , where SST is the squared error of "always the mean" (Part 7).
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 .
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).
Why: : 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).
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).
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: and . The model is . Start at and take three steps of gradient descent with the learning rate .
Idea. , then (Part 6).
| Step | slope | new | |
|---|---|---|---|
| 1 | 1 | 2 | |
| 2 | 2 | 2.5 | |
| 3 | 2.5 | 2.75 |
Why: both points lie on the line , so the lowest point of the loss is . The slope is negative as long as is below 3, so every step makes 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 . What happens?
Idea. The same rule; watch the distance from the lowest point (Part 6).
| Step | slope | new | |
|---|---|---|---|
| 1 | 1 | 6 | |
| 2 | 6 | 15 | |
| 3 | 9.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 , 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).
(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 , 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 , , with the normal equation , and check the result with the formulas of Part 5.
Idea. gets a first column of ones; the rest is the matrix work of Topic 14 (Part 8).
Why: both ways. The entries of and are the sums , , , and : the normal equation is the formula of Part 5 in the language of matrices, and it stays the same when 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).
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.
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 , so , , , , and with the score is . 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).
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. (Part 7); score gives the same number (Part 9).
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 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).
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 and , the model , the start , the learning rate 0.1. Print and the loss after each of the first four steps, and after 20 steps.
Idea. One loop: the error, the slope, the update (Part 6).
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 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 , , learning rate 0.05, 5,000 steps. Compare with the exact answer .
Idea. Two slopes, two updates in every step (Part 6).
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, . 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).
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).
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 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).
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:
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()
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.A model is . Find the prediction for and for .
Show a hint
Put the value into the equation.Show one possible solution
Answer: 24 and 42.
- 2.The charge of a telephone battery in percent, hours after it was unplugged, follows . (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 , the slope the change per hour.Show one possible solution
Answer: (a) 98 percent; (b) 8 percent; (c) 50 percent.
At the prediction is 98: the charge when the telephone was unplugged. The slope says that every hour takes away 8 percent.
- 3.Five points: , , , , . For the line , find the residual of the first point, of the third point and of the fifth point.
Show a hint
. The predictions are 2.8, 3.4, 4, 4.6 and 5.2.Show one possible solution
Answer: , and . (All five residuals: .)
The five residuals add up to 0.
- 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.
- 5.Four points: , , , . Find the SSE of the line and the SSE of the line . 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.
- 6.Find the least-squares line for the points of Problem 3: , , , , .
Show a hint
, . Make the table of deviations.Show one possible solution
Answer: .
- 7.Find the least-squares line for the points of Problem 5: , , , . Then predict for .
Show a hint
, .Show one possible solution
Answer: ; the prediction is 7.5.
The prediction is the mean of , because 5 is the mean of .
- 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. , .Show one possible solution
Answer: ; 6 litres.
- 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.
All four errors have the same size, so the RMSE and the MAE are equal.
- 10.Find R² for the line of Problem 3. Its SSE is 2.4, and the values are 2, 4, 5, 4 and 5.
Show a hint
. SST is the sum of the squared deviations of .Show one possible solution
Answer: .
The line explains 60 percent of the variation.
- 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
, .Show one possible solution
Answer: (a) ; (b) 3.0822; (c) 0.9779; (d) 62.25.
- 12.Two points: and . The model is , and the slope of the loss is . Start at and take three steps of gradient descent with . Give after each step.
Show a hint
.Show one possible solution
Answer: .
The lowest point is , where both points lie on the line.
- 13.For the data and the model of Problem 12 (the slope of the loss is ): (a) With and the start , what is after one step, and after two steps? (b) Which learning rate reaches the lowest point in a single step from ?
Show a hint
(b) The first step has the length .Show one possible solution
Answer: (a) 8, then 0: it jumps between 8 and 0 for ever; (b) .
With 0.4 every step jumps exactly to the other side of the bowl.
- 14.A model for the price of a flat, in thousands, is , 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.
(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.Find the least-squares line for the points , , with the normal equation.
Show a hint
has the entries 3, 3, 3, 5, and has the entries 9 and 14.Show one possible solution
Answer: .
Check with Part 5: , , the sum of the products is , the sum of the squares is 2, so and .
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.
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_errorEasy
The shape of the data, a first model, predictions and residuals.
- 16.Reshape
xinto a tableXwith one column. Print the shape ofX, then its first row.Show a hint
X = x.reshape(-1, 1), thenprint(X.shape)andprint(X[0]).Show one possible solution
Python, continues from the cells abovex = np.array([3, 5, 7, 9]) X = x.reshape(-1, 1) print(X.shape) print(X[0])Output
(4, 1) [3]
- 17.Train a
LinearRegressiononxandy. 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 ismodel.intercept_, the slope ismodel.coef_[0]:print(round(model.intercept_, 2), round(model.coef_[0], 2)).Show one possible solution
Python, continues from the cells abovex = 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
- 18.Train a model on
xandy. Print its predictions forx = 6andx = 10as 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 abovex = 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]
- 19.Train a model on
xandy. 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 arey - predicted. Print each array with.round(2).Show one possible solution
Python, continues from the cells abovex = 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]
- 20.Train a model on
xandy. Calculate the MSE and the RMSE with NumPy, withoutsklearn.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 isnp.sqrt(mse).Show one possible solution
Python, continues from the cells abovex = 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.
- 21.Train a model on
xandy. Print the MAE, and on a second line R², each rounded to 4 decimals. Usemean_absolute_errorandr2_score.Show a hint
Both functions take the true values first:mean_absolute_error(y, predicted)andr2_score(y, predicted).Show one possible solution
Python, continues from the cells abovex = 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
- 22.Train a model on
xandy. Printmodel.score(X, y)andr2_score(y, predicted)on one line, each rounded to 4 decimals.Show a hint
scoregetsXandy.r2_scoregetsyand the predictionsmodel.predict(X).Show one possible solution
Python, continues from the cells abovex = 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
- 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()andy_dev = y - y.mean(). The slope is(x_dev * y_dev).sum() / (x_dev ** 2).sum(), the intercepty.mean() - w1 * x.mean().Show one possible solution
Python, continues from the cells abovex = 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
- 24.Write a function
sse(w0, w1)that returns the sum of the squared residuals of the linew0 + w1 * x. The two print lines are already there.Show a hint
Inside the function:predicted = w0 + w1 * x, thenreturn ((y - predicted) ** 2).sum().Show one possible solution
Python, continues from the cells abovex = 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
- 25.The model is
w * x. Start atw = 0.0and take 10 steps of gradient descent with the learning rate 0.1. Printw, 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 abovex = 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.
- 26.Find the line
w0 + w1 * xby gradient descent: start atw0 = 0.0,w1 = 0.0, learning rate 0.05, 5000 steps. Printw0andw1on 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 changew0andw1.Show one possible solution
Python, continues from the cells abovex = 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
- 27.Every row of
housesis 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
housesalready 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 abovehouses = 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]
- 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 abovehouses = 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
- 29.Add the point
x = 60,y = 20to 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 printround(model.coef_[0], 2)of each.Show one possible solution
Python, continues from the cells abovex = 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
- 30.The 50 points were made from the line
2 * x + 5plus 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). Thenprint(round(model.coef_[0], 2), round(model.intercept_, 2))andprint(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 aboverng = 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.
0 of 12 answered.
15Quick summary
| Idea | Formula or code | In words |
|---|---|---|
| The model | a line: intercept plus slope times the feature | |
| Residual | the vertical distance of a point from the line | |
| SSE | the sum of the squared residuals | |
| MSE | the loss that training makes small | |
| Slope | how and move together, per unit of movement of | |
| Intercept | puts the line through the point of the means | |
| Gradient descent | small steps downhill on the loss | |
| RMSE | the typical error, in the unit of | |
| MAE | the average absolute error | |
| the share of the variation that the model explains | ||
| Multiple regression | one weight for every feature | |
| Normal equation | the best weights in one formula | |
| scikit-learn | LinearRegression().fit(X, y) | then intercept_, coef_, predict, score |
Rules to keep
- Look at the points before you fit a line: a scatter plot first, a residual plot after.
- The residual is true minus predicted, and the best line makes the sum of the squared residuals as small as possible.
- First the slope, then the intercept. The line passes through the point of the means.
- Report an error in the unit of the target (RMSE or MAE) and R². R² is not a share of right answers.
- A weight is the change per unit of its feature, with the other features held fixed. It is not a cause.
- Do not predict far outside the range of the data, and watch for outliers.
- In gradient descent the loss must fall step after step. If it grows, lower the learning rate.
- In scikit-learn
Xis 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.