{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 22: Linear Regression: theory and implementation\n",
    "\n",
    "Asiman Data School, Module 3: Comprehensive Machine Learning. Week 11, Thursday.\n",
    "\n",
    "This notebook follows the lesson page. Read the text, run the cell under it with Shift + Enter, then change the values in the cell and run it again. Seeing the output change is how the rules become clear.\n",
    "\n",
    "Run the cells from top to bottom. A cell that draws a chart shows it under the cell when you run it. The practice problems are in a separate notebook, topic-22-practice.ipynb.\n",
    "\n",
    "Inside a part the cells continue from each other: a cell uses the variables of the cells above it. To start in the middle, run the part from its first cell.\n",
    "\n",
    "Contents\n",
    "\n",
    "1. What is linear regression?\n",
    "2. The equation of the line\n",
    "3. Residuals, the distances between the points and the line\n",
    "4. The loss function\n",
    "5. Finding the best line with formulas (least squares)\n",
    "6. Finding the best line with gradient descent\n",
    "7. How good is the line? MSE, RMSE, MAE and R²\n",
    "8. Multiple linear regression\n",
    "9. Linear regression in Python\n",
    "10. The limits of linear regression\n",
    "11. Common mistakes\n",
    "12. Solved problems (from the easiest to the hardest)\n",
    "13. Practice problems (in topic-22-practice.ipynb)\n",
    "14. Check yourself (on the website)\n",
    "15. Quick summary"
   ],
   "id": "t22-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction: the first model\n",
    "\n",
    "What matters most in this lesson. Five things matter most today. First, the model: a line $\\hat{y} = w_0 + w_1 x$ with an intercept and a slope, and what the two numbers mean. Second, the loss: the residual of a point is true minus predicted, and the best line is the one with the smallest sum of squared residuals. Third, the two ways of finding that line: the formulas of least squares, and gradient descent, which walks downhill on the loss in small steps. Fourth, how a line is judged: the RMSE says how large the errors are, and R² says how much better the line is than always predicting the mean. Fifth, the three lines of code that train every model of this module: create the model, `fit`, `predict`.\n",
    "\n",
    "The normal equation with matrices and the adjusted R² are a first look: know what each one is for. There are 26 solved problems. Start with Level 1 and come back to the others when you repeat the topic.\n",
    "\n",
    "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.\n",
    "\n",
    "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.\n",
    "\n",
    "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`.\n",
    "\n",
    "| Written | Meaning |\n",
    "| --- | --- |\n",
    "| $x$ | the feature (the input): hours of study, the area of a flat |\n",
    "| $y$ | the target (the true answer): the mark, the price |\n",
    "| $\\hat{y}$ | \"y hat\": the prediction of the model |\n",
    "| $n$ | the number of samples (points) |\n",
    "| $\\bar{x}$, $\\bar{y}$ | the means of $x$ and of $y$ |\n",
    "| $w_0$ | the intercept (also called the bias): the prediction for $x = 0$ |\n",
    "| $w_1$ | the slope (also called the weight or the coefficient): the change of $\\hat{y}$ when $x$ grows by 1 |\n",
    "| $e$ | the residual of a point: $e = y - \\hat{y}$ |\n",
    "| SSE | the sum of the squared residuals (sum of squared errors) |\n",
    "| MSE, RMSE, MAE | the mean squared error, its square root, and the mean absolute error |\n",
    "| SST | the total sum of squares: the squared distances of the $y$ values from their mean |\n",
    "| $R^2$ | the R² score (coefficient of determination): the share of the variation that the model explains |\n",
    "| $\\alpha$ | the learning rate of gradient descent (the Greek letter alpha) |\n",
    "| $X$, $\\mathbf{w}$ | the matrix of the features and the vector of the weights (multiple regression) |\n",
    "\n",
    "In Topic 20 the line was written $\\hat{y} = a + bx$. It is the same line with other letters: $a$ is $w_0$ and $b$ is $w_1$. Books of statistics write $\\beta_0$ and $\\beta_1$. Machine learning writes $w$ for \"weight\", because the same letters continue to work when there are many features: $w_1$, $w_2$, $w_3$, and so on.\n",
    "\n",
    "## 1. What is linear regression?\n",
    "\n",
    "### 1.1 The task\n",
    "\n",
    "Five students prepared for an exam. This is how long each one studied and the mark each one got:\n",
    "\n",
    "| Student | 1 | 2 | 3 | 4 | 5 |\n",
    "| --- | --- | --- | --- | --- | --- |\n",
    "| Hours of study $x$ | 2 | 4 | 5 | 6 | 8 |\n",
    "| Mark $y$ | 50 | 60 | 65 | 75 | 80 |\n",
    "\n",
    "A sixth student studied 7 hours. What mark do you expect?\n",
    "\n",
    "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.\n",
    "\n",
    "Linear regression is the model that does exactly this:\n",
    "\n",
    "1. It takes points whose answers are known (the training data).\n",
    "2. It finds the straight line that fits those points best.\n",
    "3. It uses the line to predict the answer for new points.\n",
    "\n",
    "\"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.\n",
    "\n",
    "### 1.2 Where it is used\n",
    "\n",
    "- the price of a flat from its area\n",
    "- the salary from the years of experience\n",
    "- the sales of a shop from the money spent on advertising\n",
    "- the time of a delivery from the distance\n",
    "- the fuel a car needs from its weight\n",
    "- the number of cold drinks a cafe sells from the temperature of the day\n",
    "\n",
    "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.\n",
    "\n",
    "### 1.3 Why it is the first model of the module\n",
    "\n",
    "- It is simple: two numbers describe the whole model.\n",
    "- It can be calculated by hand, so nothing stays hidden.\n",
    "- It is easy to explain to a person who has never heard of machine learning.\n",
    "- It is fast, also with millions of rows.\n",
    "- It is the baseline: before a complicated model is tried, the question is always \"how good is a simple line?\" (Topic 21).\n",
    "- 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.\n",
    "\n",
    "## 2. The equation of the line\n",
    "\n",
    "### 2.1 Intercept and slope\n",
    "\n",
    "A straight line is described by two numbers:\n",
    "\n",
    "$$\n",
    "\\hat{y} = w_0 + w_1 x\n",
    "$$\n",
    "\n",
    "- $w_0$ is the intercept: the value of $\\hat{y}$ when $x = 0$. It is the height at which the line crosses the vertical axis. In machine learning it is also called the bias.\n",
    "- $w_1$ is the slope: how much $\\hat{y}$ changes when $x$ grows by 1. It is also called the weight or the coefficient of the feature.\n",
    "- $\\hat{y}$ (\"y hat\") is the prediction. The hat separates what the model says ($\\hat{y}$) from what really happened ($y$).\n",
    "\n",
    "The two numbers $w_0$ and $w_1$ are the parameters of the model (Topic 21). Training a linear regression means finding these two numbers.\n",
    "\n",
    "For the five students the best line is (Part 5 shows where the numbers come from):\n",
    "\n",
    "$$\n",
    "\\hat{y} = 39.75 + 5.25\\,x\n",
    "$$\n",
    "\n",
    "### 2.2 Reading the two numbers\n",
    "\n",
    "- The slope 5.25: every extra hour of study goes with 5.25 more marks, on average. Two extra hours: $2 \\times 5.25 = 10.5$ more marks.\n",
    "- The intercept 39.75: a student who does not study at all ($x = 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.)\n",
    "\n",
    "### 2.3 Making a prediction\n",
    "\n",
    "Put the value of the feature into the equation:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "x = 7:\\quad \\hat{y} &= 39.75 + 5.25 \\times 7 \\\\\n",
    "&= 39.75 + 36.75 = 76.5 \\\\[6pt]\n",
    "x = 3:\\quad \\hat{y} &= 39.75 + 5.25 \\times 3 \\\\\n",
    "&= 39.75 + 15.75 = 55.5\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "### 2.4 The sign of the slope\n",
    "\n",
    "| Slope | The line | Meaning | Example |\n",
    "| --- | --- | --- | --- |\n",
    "| $w_1 > 0$ | rises | more $x$, more $y$ | hours of study and the mark |\n",
    "| $w_1 < 0$ | falls | more $x$, less $y$ | the age of a car and its price |\n",
    "| $w_1 = 0$ | is flat | $x$ tells nothing about $y$ | the shoe size and the mark |\n",
    "\n",
    "The slope has the same sign as the correlation coefficient $r$ of Topic 20. But they are different numbers: $r$ has no units and always lies between $-1$ and $1$, while the slope has units (\"marks per hour\") and can be any number.\n",
    "\n",
    "## 3. Residuals, the distances between the points and the line\n",
    "\n",
    "### 3.1 No line passes through all the points\n",
    "\n",
    "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?\n",
    "\n",
    "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:\n",
    "\n",
    "$$\n",
    "e = y - \\hat{y}\n",
    "$$\n",
    "\n",
    "- $e > 0$: the point lies above the line. The model predicted too little.\n",
    "- $e < 0$: the point lies below the line. The model predicted too much.\n",
    "- $e = 0$: the point lies exactly on the line.\n",
    "\n",
    "### 3.2 The residuals of the five students\n",
    "\n",
    "| Student | $x$ | $y$ | $\\hat{y} = 39.75 + 5.25x$ | $e = y - \\hat{y}$ |\n",
    "| --- | --- | --- | --- | --- |\n",
    "| 1 | 2 | 50 | 50.25 | $-0.25$ |\n",
    "| 2 | 4 | 60 | 60.75 | $-0.75$ |\n",
    "| 3 | 5 | 65 | 66 | $-1$ |\n",
    "| 4 | 6 | 75 | 71.25 | 3.75 |\n",
    "| 5 | 8 | 80 | 81.75 | $-1.75$ |\n",
    "| Sum |  |  |  | 0 |\n",
    "\n",
    "Four students did a little worse than the line says, and student 4 did clearly better.\n",
    "\n",
    "### 3.3 Why vertical?\n",
    "\n",
    "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 $x$ and want to predict $y$. An error of the model is an error in $y$, so that is what we measure.\n",
    "\n",
    "### 3.4 The residuals cannot simply be added\n",
    "\n",
    "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$ and $-50$, and the sum would still say 0. The next part repairs this.\n",
    "\n",
    "## 4. The loss function\n",
    "\n",
    "### 4.1 One number for the whole line\n",
    "\n",
    "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.\n",
    "\n",
    "### 4.2 Squaring the residuals\n",
    "\n",
    "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:\n",
    "\n",
    "$$\n",
    "\\text{SSE} = \\sum (y - \\hat{y})^2\n",
    "$$\n",
    "\n",
    "SSE stands for the sum of squared errors.\n",
    "\n",
    "Dividing by the number of points gives the average squared residual, the mean squared error:\n",
    "\n",
    "$$\n",
    "\\text{MSE} = \\frac{\\text{SSE}}{n} = \\frac{1}{n} \\sum (y - \\hat{y})^2\n",
    "$$\n",
    "\n",
    "For the line $\\hat{y} = 39.75 + 5.25x$ of the five students:\n",
    "\n",
    "| Student | $e$ | $e^2$ |\n",
    "| --- | --- | --- |\n",
    "| 1 | $-0.25$ | 0.0625 |\n",
    "| 2 | $-0.75$ | 0.5625 |\n",
    "| 3 | $-1$ | 1 |\n",
    "| 4 | 3.75 | 14.0625 |\n",
    "| 5 | $-1.75$ | 3.0625 |\n",
    "| Sum | 0 | 18.75 |\n",
    "\n",
    "$$\n",
    "\\text{SSE} = 18.75 \\qquad \\text{MSE} = \\frac{18.75}{5} = 3.75\n",
    "$$\n",
    "\n",
    "### 4.3 Why squares?\n",
    "\n",
    "- Nothing cancels. A square is never negative, so every miss adds to the loss, above or below the line.\n",
    "- 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.\n",
    "- 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.\n",
    "- 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.\n",
    "\n",
    "The price of squaring: one unusual point, an outlier, can pull the line strongly towards itself. Part 10 comes back to this.\n",
    "\n",
    "### 4.4 Comparing lines\n",
    "\n",
    "Three people draw a line through the five points. Which one is best?\n",
    "\n",
    "| Line | Equation | Residuals | SSE | MSE |\n",
    "| --- | --- | --- | --- | --- |\n",
    "| A | $\\hat{y} = 40 + 5x$ | $0,\\ 0,\\ 0,\\ 5,\\ 0$ | 25 | 5 |\n",
    "| B | $\\hat{y} = 30 + 7x$ | $6,\\ 2,\\ 0,\\ 3,\\ -6$ | 85 | 17 |\n",
    "| C | $\\hat{y} = 39.75 + 5.25x$ | $-0.25,\\ -0.75,\\ -1,\\ 3.75,\\ -1.75$ | 18.75 | 3.75 |\n",
    "\n",
    "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.\n",
    "\n",
    "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.\n",
    "\n",
    "## 5. Finding the best line with formulas (least squares)\n",
    "\n",
    "### 5.1 The idea\n",
    "\n",
    "Among all pairs $(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\").\n",
    "\n",
    "The loss depends on two numbers, $w_0$ and $w_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:\n",
    "\n",
    "$$\n",
    "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}\n",
    "$$\n",
    "\n",
    "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 $x$.\n",
    "\n",
    "### 5.2 The calculation in five steps\n",
    "\n",
    "1. Calculate the two means $\\bar{x}$ and $\\bar{y}$.\n",
    "2. Calculate the deviations $x - \\bar{x}$ and $y - \\bar{y}$ of every point.\n",
    "3. Multiply the two deviations of every point and add the products. Square the deviations of $x$ and add the squares.\n",
    "4. Divide: this is the slope $w_1$.\n",
    "5. $w_0 = \\bar{y} - w_1\\,\\bar{x}$.\n",
    "\n",
    "### 5.3 Example: the five students\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\bar{x} &= \\frac{2 + 4 + 5 + 6 + 8}{5} = \\frac{25}{5} = 5 \\\\[4pt]\n",
    "\\bar{y} &= \\frac{50 + 60 + 65 + 75 + 80}{5} = \\frac{330}{5} = 66\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "| Student | $x$ | $y$ | $x - \\bar{x}$ | $y - \\bar{y}$ | product | $(x - \\bar{x})^2$ |\n",
    "| --- | --- | --- | --- | --- | --- | --- |\n",
    "| 1 | 2 | 50 | $-3$ | $-16$ | 48 | 9 |\n",
    "| 2 | 4 | 60 | $-1$ | $-6$ | 6 | 1 |\n",
    "| 3 | 5 | 65 | 0 | $-1$ | 0 | 0 |\n",
    "| 4 | 6 | 75 | 1 | 9 | 9 | 1 |\n",
    "| 5 | 8 | 80 | 3 | 14 | 42 | 9 |\n",
    "| Sum |  |  | 0 | 0 | 105 | 20 |\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "w_1 &= \\frac{105}{20} = 5.25 \\\\[4pt]\n",
    "w_0 &= 66 - 5.25 \\times 5 = 66 - 26.25 = 39.75 \\\\[4pt]\n",
    "\\hat{y} &= 39.75 + 5.25\\,x\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "### 5.4 Three facts about the least-squares line\n",
    "\n",
    "- It passes through the point of the means $(\\bar{x}, \\bar{y})$. Check: $39.75 + 5.25 \\times 5 = 66$. This follows directly from $w_0 = \\bar{y} - w_1\\,\\bar{x}$.\n",
    "- 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.\n",
    "- It is unique. As long as the $x$ values are not all equal, there is exactly one best line. (If all $x$ are equal, $\\sum (x - \\bar{x})^2 = 0$, the division is impossible, and no line can be found: the points stand in a vertical column.)\n",
    "\n",
    "### 5.5 The slope and the correlation\n",
    "\n",
    "Topic 20 gave a second formula for the slope:\n",
    "\n",
    "$$\n",
    "w_1 = r \\times \\frac{s_y}{s_x}\n",
    "$$\n",
    "\n",
    "where $r$ is the correlation coefficient and $s_x$, $s_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.\n",
    "\n",
    "## 6. Finding the best line with gradient descent\n",
    "\n",
    "### 6.1 Why a second method?\n",
    "\n",
    "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.\n",
    "\n",
    "### 6.2 The idea: walk downhill\n",
    "\n",
    "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.\n",
    "\n",
    "Gradient descent does the same on the loss:\n",
    "\n",
    "1. Start with any values of the parameters.\n",
    "2. Find the slope of the loss at the place where you stand.\n",
    "3. Move the parameters a small step in the direction in which the loss goes down.\n",
    "4. Repeat until the loss stops getting smaller.\n",
    "\n",
    "### 6.3 The slope of the loss: the gradient\n",
    "\n",
    "To keep the first example small, take two points, $(1, 2)$ and $(2, 4)$, and the simplest model: a line through the origin with only one parameter,\n",
    "\n",
    "$$\n",
    "\\hat{y} = w\\,x\n",
    "$$\n",
    "\n",
    "For every value of $w$ the loss can be calculated:\n",
    "\n",
    "$$\n",
    "\\text{MSE}(w) = \\frac{1}{2}\\left[(w \\times 1 - 2)^2 + (w \\times 2 - 4)^2\\right]\n",
    "$$\n",
    "\n",
    "| $w$ | 0 | 1 | 2 | 3 | 4 |\n",
    "| --- | --- | --- | --- | --- | --- |\n",
    "| MSE | 10 | 2.5 | 0 | 2.5 | 10 |\n",
    "\n",
    "The loss is a curve shaped like a bowl (a parabola), with its lowest point at $w = 2$, where the line $\\hat{y} = 2x$ passes through both points.\n",
    "\n",
    "The slope of the loss curve at a value of $w$ says how the loss changes when $w$ grows a little:\n",
    "\n",
    "- a negative slope: the curve goes down to the right. Making $w$ larger makes the loss smaller.\n",
    "- a positive slope: the curve goes up to the right. Making $w$ smaller makes the loss smaller.\n",
    "- a slope of zero: the bottom of the bowl. Nothing can be improved.\n",
    "\n",
    "In mathematics the slope of a curve at a point is called the derivative. For the mean squared error it is:\n",
    "\n",
    "$$\n",
    "\\text{slope of the loss} = \\frac{2}{n} \\sum (\\hat{y} - y)\\,x\n",
    "$$\n",
    "\n",
    "Read it like this: for every point, take the error $\\hat{y} - y$ and multiply it by the feature $x$; add the products; multiply by $\\dfrac{2}{n}$. For our two points, with $\\hat{y} = w\\,x$:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{slope} &= \\frac{2}{2}\\left[(w \\times 1 - 2) \\times 1 + (w \\times 2 - 4) \\times 2\\right] \\\\[4pt]\n",
    "&= (w - 2) + (4w - 8) \\\\[4pt]\n",
    "&= 5w - 10\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "At $w = 0$ the slope is $-10$: steeply downhill to the right. At $w = 2$ it is $0$: the bottom. At $w = 3$ it is $5$: uphill to the right, so the way down is to the left.\n",
    "\n",
    "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.\n",
    "\n",
    "### 6.4 The update rule\n",
    "\n",
    "$$\n",
    "w_{\\text{new}} = w_{\\text{old}} - \\alpha \\times \\text{slope}\n",
    "$$\n",
    "\n",
    "- The minus sign sends us downhill: a negative slope makes $w$ larger, a positive slope makes it smaller.\n",
    "- $\\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.\n",
    "- The step is $\\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.\n",
    "\n",
    "### 6.5 Four steps by hand\n",
    "\n",
    "Start at $w = 0$ with the learning rate $\\alpha = 0.1$:\n",
    "\n",
    "| Step | $w$ | slope $5w - 10$ | step $\\alpha \\times \\text{slope}$ | new $w$ | MSE at the new $w$ |\n",
    "| --- | --- | --- | --- | --- | --- |\n",
    "| 1 | 0 | $-10$ | $-1$ | 1 | 2.5 |\n",
    "| 2 | 1 | $-5$ | $-0.5$ | 1.5 | 0.625 |\n",
    "| 3 | 1.5 | $-2.5$ | $-0.25$ | 1.75 | 0.156 |\n",
    "| 4 | 1.75 | $-1.25$ | $-0.125$ | 1.875 | 0.039 |\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{step 1:}\\quad w_{\\text{new}} &= 0 - 0.1 \\times (-10) = 0 + 1 = 1 \\\\[4pt]\n",
    "\\text{step 2:}\\quad w_{\\text{new}} &= 1 - 0.1 \\times (-5) = 1 + 0.5 = 1.5\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "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.\n",
    "\n",
    "### 6.6 The learning rate\n",
    "\n",
    "The learning rate decides whether the walk works.\n",
    "\n",
    "| Learning rate | The values of $w$ | What happens |\n",
    "| --- | --- | --- |\n",
    "| $\\alpha = 0.01$ (too small) | $0,\\ 0.1,\\ 0.195,\\ 0.2853,\\ 0.371,\\ \\ldots$ | every step is tiny; hundreds of steps are needed |\n",
    "| $\\alpha = 0.1$ (good) | $0,\\ 1,\\ 1.5,\\ 1.75,\\ 1.875,\\ \\ldots$ | fast and steady |\n",
    "| $\\alpha = 0.4$ (too large) | $0,\\ 4,\\ 0,\\ 4,\\ 0,\\ \\ldots$ | every step jumps over the bottom to the other side, for ever |\n",
    "| $\\alpha = 0.5$ (much too large) | $0,\\ 5,\\ -2.5,\\ 8.75,\\ -8.125,\\ \\ldots$ | every jump lands further away: the loss grows without limit |\n",
    "\n",
    "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.\n",
    "\n",
    "### 6.7 Two parameters: the real line\n",
    "\n",
    "For the line $\\hat{y} = w_0 + w_1 x$ there are two slopes, one for each parameter:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{slope for } w_0 &= \\frac{2}{n} \\sum (\\hat{y} - y) \\\\[4pt]\n",
    "\\text{slope for } w_1 &= \\frac{2}{n} \\sum (\\hat{y} - y)\\,x\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "and both parameters are updated in every step, at the same time:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "w_0 &\\leftarrow w_0 - \\alpha \\times (\\text{slope for } w_0) \\\\[4pt]\n",
    "w_1 &\\leftarrow w_1 - \\alpha \\times (\\text{slope for } w_1)\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "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.\n",
    "\n",
    "Notice what happens at the bottom of the bowl. Both slopes are zero there:\n",
    "\n",
    "$$\n",
    "\\sum (\\hat{y} - y) = 0 \\qquad \\text{and} \\qquad \\sum (\\hat{y} - y)\\,x = 0\n",
    "$$\n",
    "\n",
    "The first equation says that the residuals add up to zero. Solving the two equations for $w_0$ and $w_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.\n",
    "\n",
    "### 6.8 Formulas or gradient descent?\n",
    "\n",
    "|  | The formulas (least squares) | Gradient descent |\n",
    "| --- | --- | --- |\n",
    "| Result | exact, in one calculation | approximate, after many steps |\n",
    "| Settings | none | the learning rate, the number of steps, the starting values |\n",
    "| Works for | linear regression | almost every model, also neural networks |\n",
    "| Very many features or rows | becomes slow and needs much memory | stays usable |\n",
    "| In scikit-learn | `LinearRegression` | `SGDRegressor`, and the training of neural networks |\n",
    "\n",
    "`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.\n",
    "\n",
    "## 7. How good is the line? MSE, RMSE, MAE and R²\n",
    "\n",
    "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²).\n",
    "\n",
    "### 7.1 MSE: the mean squared error\n",
    "\n",
    "$$\n",
    "\\text{MSE} = \\frac{1}{n} \\sum (y - \\hat{y})^2\n",
    "$$\n",
    "\n",
    "It is the loss function of Part 4, used now as a measure of quality. For the five students: $\\text{MSE} = \\dfrac{18.75}{5} = 3.75$.\n",
    "\n",
    "- The smaller, the better. $\\text{MSE} = 0$ means that every point lies on the line.\n",
    "- Large errors are punished strongly, because of the square.\n",
    "- 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.\n",
    "\n",
    "### 7.2 RMSE: the root of the MSE\n",
    "\n",
    "$$\n",
    "\\text{RMSE} = \\sqrt{\\text{MSE}}\n",
    "$$\n",
    "\n",
    "Taking the square root brings the unit back. For the students: $\\text{RMSE} = \\sqrt{3.75} = 1.9365$.\n",
    "\n",
    "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.\n",
    "\n",
    "### 7.3 MAE: the mean absolute error\n",
    "\n",
    "$$\n",
    "\\text{MAE} = \\frac{1}{n} \\sum \\lvert y - \\hat{y} \\rvert\n",
    "$$\n",
    "\n",
    "The other repair of Part 4: absolute values in the place of squares. For the students:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{MAE} &= \\frac{0.25 + 0.75 + 1 + 3.75 + 1.75}{5} \\\\[4pt]\n",
    "&= \\frac{7.5}{5} = 1.5\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "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.\n",
    "\n",
    "### 7.4 R²: the share of the variation explained\n",
    "\n",
    "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.\n",
    "\n",
    "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, $\\bar{y} = 66$. The squared errors of this guess add up to the total sum of squares:\n",
    "\n",
    "$$\n",
    "\\text{SST} = \\sum (y - \\bar{y})^2\n",
    "$$\n",
    "\n",
    "For the students:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{SST} &= (-16)^2 + (-6)^2 + (-1)^2 + 9^2 + 14^2 \\\\[4pt]\n",
    "&= 256 + 36 + 1 + 81 + 196 = 570\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "The model: predict with the line. Its squared errors add up to $\\text{SSE} = 18.75$.\n",
    "\n",
    "The line reduces the squared error from 570 to 18.75. R² is the share that was removed:\n",
    "\n",
    "$$\n",
    "R^2 = 1 - \\frac{\\text{SSE}}{\\text{SST}}\n",
    "$$\n",
    "\n",
    "$$\n",
    "R^2 = 1 - \\frac{18.75}{570} = 1 - 0.0329 = 0.9671\n",
    "$$\n",
    "\n",
    "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.\n",
    "\n",
    "### 7.5 Reading R²\n",
    "\n",
    "| $R^2$ | Meaning |\n",
    "| --- | --- |\n",
    "| 1 | every point lies on the line: $\\text{SSE} = 0$ |\n",
    "| 0.9671 | the line removes 96.71 percent of the squared error of \"always the mean\" |\n",
    "| 0 | the model is exactly as good as always predicting the mean |\n",
    "| below 0 | the model is worse than always predicting the mean |\n",
    "\n",
    "Facts to remember:\n",
    "\n",
    "- R² is not a percentage of right answers. A regression model has no \"right\" and \"wrong\" answers. $R^2 = 0.97$ does not mean \"97 percent correct\".\n",
    "- For a line with one feature, R² is the square of the correlation coefficient. In Topic 20 the students had $r = 0.9834$, and $0.9834^2 = 0.9671$. That is where the name comes from.\n",
    "- 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 $\\hat{y} = 100 - 5x$ has $\\text{SSE} = 2525$ on the five students, and $R^2 = 1 - \\dfrac{2525}{570} = -3.43$.\n",
    "- 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.\n",
    "- A high R² does not prove that a line is the right shape. Part 10 shows a curve with $R^2 = 0.95$.\n",
    "- Adding features never lowers R² on the training data, even when the new feature is nonsense. Topic 23 comes back to this.\n",
    "\n",
    "### 7.6 The four measures side by side\n",
    "\n",
    "| Measure | Formula | Unit | Best value | Use it to say |\n",
    "| --- | --- | --- | --- | --- |\n",
    "| MSE | $\\frac{1}{n} \\sum (y - \\hat{y})^2$ | the unit of $y$, squared | 0 | this is what training makes small |\n",
    "| RMSE | $\\sqrt{\\text{MSE}}$ | the unit of $y$ | 0 | \"the predictions are off by about ...\" |\n",
    "| MAE | $\\frac{1}{n} \\sum \\lvert y - \\hat{y} \\rvert$ | the unit of $y$ | 0 | the plain average error, less moved by outliers |\n",
    "| $R^2$ | $1 - \\frac{\\text{SSE}}{\\text{SST}}$ | none | 1 | \"the model explains ... percent of the variation\" |\n",
    "\n",
    "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.\n",
    "\n",
    "## 8. Multiple linear regression\n",
    "\n",
    "### 8.1 More than one feature\n",
    "\n",
    "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:\n",
    "\n",
    "$$\n",
    "\\hat{y} = w_0 + w_1 x_1 + w_2 x_2 + \\dots + w_p x_p\n",
    "$$\n",
    "\n",
    "- $x_1, x_2, \\dots, x_p$ are the $p$ features of one sample.\n",
    "- $w_1, w_2, \\dots, w_p$ are their weights (coefficients).\n",
    "- $w_0$ is the intercept.\n",
    "\n",
    "Simple linear regression is the special case $p = 1$.\n",
    "\n",
    "### 8.2 Example: the price of a flat\n",
    "\n",
    "Suppose a model has learned this equation (prices in thousands):\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{price} = 20 &+ 1.5 \\times \\text{area} \\\\\n",
    "&+ 10 \\times \\text{rooms} - 0.8 \\times \\text{age}\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "A flat with 80 m², 3 rooms, in a building that is 10 years old:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{price} &= 20 + 1.5 \\times 80 + 10 \\times 3 - 0.8 \\times 10 \\\\[4pt]\n",
    "&= 20 + 120 + 30 - 8 = 162\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "### 8.3 Reading the weights\n",
    "\n",
    "Every weight says how the prediction changes when its feature grows by 1 and the other features stay the same:\n",
    "\n",
    "- $1.5$: one more square metre adds 1.5 thousand, for flats with the same number of rooms and the same age.\n",
    "- $10$: one more room adds 10 thousand, for the same area and age.\n",
    "- $-0.8$: every year of age takes away 0.8 thousand.\n",
    "\n",
    "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.\n",
    "\n",
    "Two warnings:\n",
    "\n",
    "- 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.\n",
    "- A weight is not a cause. It describes how the price moves together with the feature in this data.\n",
    "\n",
    "### 8.4 With a dot product\n",
    "\n",
    "Put the features of one flat into a vector, and the weights into another one (Topic 13):\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\mathbf{x} &= (80,\\ 3,\\ 10) \\qquad \\mathbf{w} = (1.5,\\ 10,\\ -0.8) \\\\[4pt]\n",
    "\\hat{y} &= w_0 + \\mathbf{w} \\cdot \\mathbf{x} \\\\[4pt]\n",
    "&= 20 + \\bigl(1.5 \\times 80 + 10 \\times 3 + (-0.8) \\times 10\\bigr) \\\\[4pt]\n",
    "&= 20 + 142 = 162\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "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.\n",
    "\n",
    "### 8.5 With matrices\n",
    "\n",
    "For many flats at once, write the features into a matrix $X$ with one row for every flat (Topic 14). To include the intercept, add a first column of ones, so that $w_0$ is multiplied by 1 in every row:\n",
    "\n",
    "$$\n",
    "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}\n",
    "$$\n",
    "\n",
    "$$\n",
    "\\mathbf{w} = \\begin{bmatrix} w_0 \\\\ w_1 \\\\ \\vdots \\\\ w_p \\end{bmatrix} \\qquad \\hat{\\mathbf{y}} = X\\mathbf{w}\n",
    "$$\n",
    "\n",
    "One matrix multiplication gives all $n$ predictions. This is the shape $(n, p)$ of the table `X` that scikit-learn expects (Topic 21): $n$ rows, $p$ columns.\n",
    "\n",
    "### 8.6 The best weights\n",
    "\n",
    "The loss is the same as before:\n",
    "\n",
    "$$\n",
    "\\text{MSE} = \\frac{1}{n} \\sum (y - \\hat{y})^2\n",
    "$$\n",
    "\n",
    "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:\n",
    "\n",
    "$$\n",
    "\\mathbf{w} = (X^{T} X)^{-1} X^{T} \\mathbf{y}\n",
    "$$\n",
    "\n",
    "($X^{T}$ is the transpose and the power $-1$ the inverse, both from Topic 14.) With one feature it gives exactly the $w_0$ and $w_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.\n",
    "\n",
    "Four points: $(0, 1)$, $(1, 3)$, $(2, 4)$, $(3, 8)$.\n",
    "\n",
    "$$\n",
    "X = \\begin{bmatrix} 1 & 0 \\\\ 1 & 1 \\\\ 1 & 2 \\\\ 1 & 3 \\end{bmatrix} \\qquad \\mathbf{y} = \\begin{bmatrix} 1 \\\\ 3 \\\\ 4 \\\\ 8 \\end{bmatrix}\n",
    "$$\n",
    "\n",
    "$$\n",
    "X^{T} X = \\begin{bmatrix} 4 & 6 \\\\ 6 & 14 \\end{bmatrix} \\qquad X^{T} \\mathbf{y} = \\begin{bmatrix} 16 \\\\ 35 \\end{bmatrix}\n",
    "$$\n",
    "\n",
    "The entries are sums: 4 is the number of points, 6 is $\\sum x$, 14 is $\\sum x^2$, 16 is $\\sum y$ and 35 is $\\sum xy$.\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\det(X^{T} X) &= 4 \\times 14 - 6 \\times 6 = 20 \\\\[6pt]\n",
    "(X^{T} X)^{-1} &= \\frac{1}{20} \\begin{bmatrix} 14 & -6 \\\\ -6 & 4 \\end{bmatrix}\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\mathbf{w} &= \\frac{1}{20} \\begin{bmatrix} 14 \\times 16 - 6 \\times 35 \\\\ -6 \\times 16 + 4 \\times 35 \\end{bmatrix} \\\\[6pt]\n",
    "&= \\frac{1}{20} \\begin{bmatrix} 14 \\\\ 44 \\end{bmatrix} = \\begin{bmatrix} 0.7 \\\\ 2.2 \\end{bmatrix}\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "So $\\hat{y} = 0.7 + 2.2x$. The formulas of Part 5 give the same: $w_1 = \\dfrac{11}{5} = 2.2$ and $w_0 = 4 - 2.2 \\times 1.5 = 0.7$.\n",
    "\n",
    "Gradient descent works for many features too. There is one slope for every weight, and all of them fit into one line with matrices:\n",
    "\n",
    "$$\n",
    "\\text{gradient} = \\frac{2}{n}\\,X^{T}(X\\mathbf{w} - \\mathbf{y})\n",
    "$$\n",
    "\n",
    "### 8.7 From a line to a plane\n",
    "\n",
    "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.\n",
    "\n",
    "### 8.8 What changes, and what does not\n",
    "\n",
    "|  | Simple linear regression | Multiple linear regression |\n",
    "| --- | --- | --- |\n",
    "| Features | 1 | $p$ (2 or more) |\n",
    "| Equation | $\\hat{y} = w_0 + w_1 x$ | $\\hat{y} = w_0 + w_1 x_1 + \\dots + w_p x_p$ |\n",
    "| Parameters | 2 | $p + 1$ |\n",
    "| Picture | a line | a plane (2 features), not drawable beyond |\n",
    "| A weight means | the change of $\\hat{y}$ per unit of $x$ | the same, with the other features held fixed |\n",
    "| Loss | MSE | MSE |\n",
    "| Best parameters | the formulas of Part 5 | the normal equation |\n",
    "| Measures | MSE, RMSE, MAE, R² | the same |\n",
    "| In scikit-learn | `LinearRegression` | `LinearRegression`, with more columns in `X` |\n",
    "\n",
    "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.\n",
    "\n",
    "## 9. Linear regression in Python\n",
    "\n",
    "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.\n",
    "\n",
    "### 9.1 The data as arrays\n",
    "\n",
    "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:\n",
    "\n",
    "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."
   ],
   "id": "t22-001"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "hours = np.array([2, 4, 5, 6, 8])\n",
    "marks = np.array([50, 60, 65, 75, 80])\n",
    "\n",
    "X = hours.reshape(-1, 1)\n",
    "y = marks\n",
    "\n",
    "print(X)\n",
    "print(X.shape, y.shape)"
   ],
   "id": "t22-002"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`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.\n",
    "\n",
    "### 9.2 Training the model"
   ],
   "id": "t22-003"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import LinearRegression\n",
    "\n",
    "model = LinearRegression()\n",
    "model.fit(X, y)\n",
    "\n",
    "print(round(model.intercept_, 2))\n",
    "print(model.coef_.round(2))"
   ],
   "id": "t22-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`fit` did the whole of Part 5. The intercept $w_0$ is in `model.intercept_` and the slope $w_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.\n",
    "\n",
    "### 9.3 Predicting\n",
    "\n",
    "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."
   ],
   "id": "t22-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "new_hours = np.array([[7], [3], [10]])\n",
    "print(model.predict(new_hours))"
   ],
   "id": "t22-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.25$, but 10 hours lies outside the data (2 to 8 hours): Part 10 explains why such a number should not be trusted.\n",
    "\n",
    "### 9.4 Predictions and residuals of the training data"
   ],
   "id": "t22-007"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "y_pred = model.predict(X)\n",
    "residuals = y - y_pred\n",
    "\n",
    "print(y_pred.round(2))\n",
    "print(residuals.round(2))\n",
    "print(abs(residuals.sum()) < 1e-9)"
   ],
   "id": "t22-008"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.)\n",
    "\n",
    "### 9.5 Drawing the points and the line"
   ],
   "id": "t22-009"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "plt.scatter(hours, marks, label=\"students\")\n",
    "plt.plot(hours, model.predict(X), color=\"orange\", label=\"regression line\")\n",
    "plt.xlabel(\"hours of study\")\n",
    "plt.ylabel(\"mark\")\n",
    "plt.title(\"Hours of study and marks\")\n",
    "plt.legend()\n",
    "plt.show()"
   ],
   "id": "t22-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A picture is the first check of every regression: do the points really follow a line?\n",
    "\n",
    "### 9.6 The measures, calculated with NumPy\n",
    "\n",
    "The errors first:"
   ],
   "id": "t22-011"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sse = (residuals ** 2).sum()\n",
    "mse = (residuals ** 2).mean()\n",
    "rmse = np.sqrt(mse)\n",
    "mae = np.abs(residuals).mean()\n",
    "\n",
    "print(round(sse, 4), round(mse, 4))\n",
    "print(round(rmse, 4), round(mae, 4))"
   ],
   "id": "t22-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then the total sum of squares and R²:"
   ],
   "id": "t22-013"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sst = ((y - y.mean()) ** 2).sum()\n",
    "r2 = 1 - sse / sst\n",
    "\n",
    "print(round(sst, 4), round(r2, 4))"
   ],
   "id": "t22-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every line is a formula of Part 7, and every number is the one calculated by hand.\n",
    "\n",
    "### 9.7 The measures, with scikit-learn\n",
    "\n",
    "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:"
   ],
   "id": "t22-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score, root_mean_squared_error\n",
    "\n",
    "print(round(mean_squared_error(y, y_pred), 4))\n",
    "print(round(root_mean_squared_error(y, y_pred), 4))\n",
    "print(round(mean_absolute_error(y, y_pred), 4))\n",
    "print(round(r2_score(y, y_pred), 4))"
   ],
   "id": "t22-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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`:"
   ],
   "id": "t22-017"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(round(model.score(X, y), 4))"
   ],
   "id": "t22-018"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The last line of the cell above and this line print the same number.\n",
    "\n",
    "### 9.8 The formulas of Part 5 in NumPy\n",
    "\n",
    "To see that scikit-learn does nothing secret, calculate the slope and the intercept directly:"
   ],
   "id": "t22-019"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x_dev = hours - hours.mean()\n",
    "y_dev = marks - marks.mean()\n",
    "\n",
    "w1 = (x_dev * y_dev).sum() / (x_dev ** 2).sum()\n",
    "w0 = marks.mean() - w1 * hours.mean()\n",
    "\n",
    "print(w1, w0)"
   ],
   "id": "t22-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 9.9 Gradient descent in a few lines\n",
    "\n",
    "The update rule of Part 6, for both parameters, repeated 5,000 times:\n",
    "\n",
    "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`."
   ],
   "id": "t22-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "w0, w1 = 0.0, 0.0\n",
    "rate = 0.02\n",
    "losses = []\n",
    "\n",
    "for step in range(5000):\n",
    "    error = (w0 + w1 * hours) - marks\n",
    "    losses.append((error ** 2).mean())\n",
    "    w0 = w0 - rate * 2 * error.mean()\n",
    "    w1 = w1 - rate * 2 * (error * hours).mean()\n",
    "\n",
    "print(round(w0, 2), round(w1, 2))"
   ],
   "id": "t22-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Starting from $w_0 = 0$ and $w_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:"
   ],
   "id": "t22-023"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(round(losses[0], 2), round(losses[10], 2), round(losses[100], 2), round(losses[-1], 2))"
   ],
   "id": "t22-024"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It falls from 4,470 to 3.75, the MSE of the best line."
   ],
   "id": "t22-025"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "plt.plot(losses[:60])\n",
    "plt.xlabel(\"step\")\n",
    "plt.ylabel(\"loss (MSE)\")\n",
    "plt.title(\"Gradient descent: the loss during the first 60 steps\")\n",
    "plt.show()"
   ],
   "id": "t22-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 9.10 Multiple linear regression\n",
    "\n",
    "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:"
   ],
   "id": "t22-027"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from sklearn.linear_model import LinearRegression\n",
    "\n",
    "flats = np.array([\n",
    "    [45, 1, 20],\n",
    "    [52, 2, 15],\n",
    "    [60, 2, 30],\n",
    "    [68, 2, 5],\n",
    "    [75, 3, 12],\n",
    "    [83, 3, 25],\n",
    "    [90, 3, 2],\n",
    "    [105, 4, 8],\n",
    "    [110, 4, 18],\n",
    "    [130, 4, 10],\n",
    "])\n",
    "prices = np.array([85, 104, 108, 133, 158, 150, 188, 208, 215, 244])\n",
    "\n",
    "print(flats.shape, prices.shape)"
   ],
   "id": "t22-028"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`flats` already has two dimensions, 10 rows and 3 columns, so no reshape is needed."
   ],
   "id": "t22-029"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "flat_model = LinearRegression()\n",
    "flat_model.fit(flats, prices)\n",
    "\n",
    "print(round(flat_model.intercept_, 2))\n",
    "print(flat_model.coef_.round(2))"
   ],
   "id": "t22-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`coef_` now holds three weights, in the order of the columns: area, rooms, age.\n",
    "\n",
    "Change it and run: change the new flat to 4 rooms: the prediction grows by the weight of the rooms."
   ],
   "id": "t22-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "new_flat = np.array([[80, 3, 10]])\n",
    "\n",
    "print(flat_model.predict(new_flat).round(1))\n",
    "print(round(flat_model.score(flats, prices), 4))"
   ],
   "id": "t22-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "Now a simple regression on the area alone (`flats[:, [0]]` keeps the first column as a table):"
   ],
   "id": "t22-033"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "area_only = flats[:, [0]]\n",
    "\n",
    "area_model = LinearRegression()\n",
    "area_model.fit(area_only, prices)\n",
    "\n",
    "print(area_model.coef_.round(2), round(area_model.score(area_only, prices), 4))"
   ],
   "id": "t22-034"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 9.11 More points, with noise\n",
    "\n",
    "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:"
   ],
   "id": "t22-035"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "rng = np.random.default_rng(0)\n",
    "area = rng.uniform(40, 120, 40).round()\n",
    "price = (20 + 1.5 * area + rng.normal(0, 10, 40)).round()\n",
    "\n",
    "print(area[:5])\n",
    "print(price[:5])"
   ],
   "id": "t22-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The same three steps as before: reshape, create, `fit`. Then the intercept and the slope, R², and the RMSE:\n",
    "\n",
    "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."
   ],
   "id": "t22-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.metrics import root_mean_squared_error\n",
    "\n",
    "X = area.reshape(-1, 1)\n",
    "model = LinearRegression()\n",
    "model.fit(X, price)\n",
    "\n",
    "print(round(model.intercept_, 2), model.coef_.round(2))\n",
    "print(round(model.score(X, price), 3))\n",
    "print(round(root_mean_squared_error(price, model.predict(X)), 2))"
   ],
   "id": "t22-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 9.12 The residual plot"
   ],
   "id": "t22-039"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "residuals = price - model.predict(X)\n",
    "\n",
    "plt.scatter(area, residuals)\n",
    "plt.axhline(0, color=\"gray\")\n",
    "plt.xlabel(\"area\")\n",
    "plt.ylabel(\"residual\")\n",
    "plt.title(\"Residual plot\")\n",
    "plt.show()"
   ],
   "id": "t22-040"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 9.13 The pieces of scikit-learn used in this lesson\n",
    "\n",
    "| Code | What it does |\n",
    "| --- | --- |\n",
    "| `x.reshape(-1, 1)` | turns a row of values into a table with one column |\n",
    "| `LinearRegression()` | creates an empty linear regression model |\n",
    "| `model.fit(X, y)` | finds the best intercept and weights |\n",
    "| `model.intercept_` | the intercept $w_0$ (one number) |\n",
    "| `model.coef_` | the weights $w_1, \\dots, w_p$ (an array) |\n",
    "| `model.predict(X_new)` | the predictions for new rows |\n",
    "| `model.score(X, y)` | the R² score |\n",
    "| `mean_squared_error(y, y_pred)` | MSE |\n",
    "| `root_mean_squared_error(y, y_pred)` | RMSE |\n",
    "| `mean_absolute_error(y, y_pred)` | MAE |\n",
    "| `r2_score(y, y_pred)` | R² |\n",
    "\n",
    "## 10. The limits of linear regression\n",
    "\n",
    "Linear regression always gives an answer. It will draw a line through any cloud of points. Whether the line means anything is your responsibility.\n",
    "\n",
    "### 10.1 What the model assumes\n",
    "\n",
    "- The relationship is roughly a straight line. The model has no other shape to offer.\n",
    "- The points are independent of one another: one student's mark does not depend on another's.\n",
    "- The residuals have about the same spread everywhere, not small on the left and huge on the right.\n",
    "- No single point dominates. A few extreme values should not decide the line.\n",
    "\n",
    "The first check is always a scatter plot, and the second a residual plot.\n",
    "\n",
    "### 10.2 A curve is not a line\n",
    "\n",
    "Take the points $(1, 1), (2, 4), (3, 9), \\dots, (8, 64)$: exactly $y = x^2$. The best line is $\\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.\n",
    "\n",
    "### 10.3 One outlier can turn the line\n",
    "\n",
    "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 $\\hat{y} = 39.75 + 5.25x$ to $\\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.\n",
    "\n",
    "### 10.4 Predictions outside the data\n",
    "\n",
    "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 \\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.\n",
    "\n",
    "### 10.5 A relationship is not a cause\n",
    "\n",
    "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.\n",
    "\n",
    "### 10.6 When features repeat each other\n",
    "\n",
    "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.\n",
    "\n",
    "### 10.7 What the next lessons add\n",
    "\n",
    "| Problem | Where it is solved |\n",
    "| --- | --- |\n",
    "| A model that fits the training data but not new data | Topic 23: train/test split, cross-validation, overfitting |\n",
    "| Features on very different scales | Topic 24: scaling |\n",
    "| Features that are categories (a city, a colour), and outliers | Topic 25: encoding and outliers |\n",
    "| Too many features, unstable weights | Topic 26: Ridge and Lasso |\n",
    "| A target that is a category | Topic 27: logistic regression |\n",
    "\n",
    "## 11. Common mistakes\n",
    "\n",
    "| Mistake | Why it is wrong | Right |\n",
    "| --- | --- | --- |\n",
    "| Calculating the residual as $\\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 - \\hat{y}$ |\n",
    "| 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. |\n",
    "| Forgetting to divide by $n$, and calling the SSE \"MSE\". | The SSE grows with the number of points; the MSE is the average. | $\\text{MSE} = \\text{SSE} / n$ |\n",
    "| Reporting the MSE in the unit of $y$. | The MSE has the squared unit. | Take the root: the RMSE has the unit of $y$. |\n",
    "| \"$R^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.\" |\n",
    "| \"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. |\n",
    "| \"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. |\n",
    "| Mixing up the slope and the intercept. | $w_0$ is the value at $x = 0$, $w_1$ the change per unit. | In $\\hat{y} = 39.75 + 5.25x$ the slope is 5.25. |\n",
    "| Calculating $w_0$ before $w_1$. | $w_0 = \\bar{y} - w_1\\,\\bar{x}$ needs the slope. | First $w_1$, then $w_0$. |\n",
    "| Reading the slope as a cause. | The line describes how the values move together in this data. | \"goes with\", \"on average\", not \"causes\". |\n",
    "| Predicting far outside the range of the data. | The line was never checked there. | Predict inside the range; say clearly when you do not. |\n",
    "| Comparing the weights of features with different units. | A weight depends on the unit of its feature. | Scale the features first (Topic 24). |\n",
    "| 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)` |\n",
    "| `model.predict(7)` | A single number is not a table. | `model.predict(np.array([[7]]))` |\n",
    "| `r2_score(y_pred, y)` | The true values come first. The result changes when the order is swapped. | `r2_score(y, y_pred)` |\n",
    "| `model.score(X, y_pred)` | `score` makes the predictions itself; it needs the true answers. | `model.score(X, y)` |\n",
    "| 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. |\n",
    "| Stopping gradient descent after a few steps. | The parameters are still far from the lowest point. | Run until the loss no longer changes. |\n",
    "\n",
    "The error that scikit-learn shows for a plain array as `X`:\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "from sklearn.linear_model import LinearRegression\n",
    "\n",
    "hours = np.array([2, 4, 5, 6, 8])\n",
    "marks = np.array([50, 60, 65, 75, 80])\n",
    "\n",
    "model = LinearRegression()\n",
    "model.fit(hours, marks)\n",
    "```\n",
    "\n",
    "```\n",
    "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.\n",
    "```\n",
    "\n",
    "The message names the repair itself: `reshape(-1, 1)` for data with a single feature.\n",
    "\n",
    "## 12. Solved problems (from the easiest to the hardest)\n",
    "\n",
    "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.\n",
    "\n",
    "### Level 1: The line, the residuals and the loss\n",
    "\n",
    "Problem 1. A prediction from a line\n",
    "\n",
    "A delivery company uses the line $\\hat{y} = 6.5 + 2.3x$ to estimate the time of a delivery in minutes from the distance $x$ in kilometres. How long will a delivery over 5 km take? And over 10 km?\n",
    "\n",
    "Idea. Put the distance into the equation (Part 2).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "x = 5:\\quad \\hat{y} &= 6.5 + 2.3 \\times 5 = 6.5 + 11.5 = 18 \\\\[4pt]\n",
    "x = 10:\\quad \\hat{y} &= 6.5 + 2.3 \\times 10 = 6.5 + 23 = 29.5\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "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.\n",
    "\n",
    "Problem 2. Reading the slope and the intercept\n",
    "\n",
    "The price of a used car of one model, in thousands, follows the line $\\hat{y} = 20.6 - 2.2x$, where $x$ 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?\n",
    "\n",
    "Idea. The intercept is the prediction at $x = 0$, the slope the change per unit (Part 2).\n",
    "\n",
    "(a) The intercept 20.6: the predicted price of a new car (age 0) is 20.6 thousand. The slope $-2.2$: every year of age takes away 2.2 thousand.\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{(b)}\\quad \\hat{y} &= 20.6 - 2.2 \\times 3 = 20.6 - 6.6 = 14 \\\\[4pt]\n",
    "\\text{(c)}\\quad & 4 \\times 2.2 = 8.8 \\text{ thousand}\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: a negative slope means a falling line: more $x$, less $y$. The change over several units is the slope times the number of units.\n",
    "\n",
    "Problem 3. Residuals\n",
    "\n",
    "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 $\\hat{y} = 2.6 + 0.8x$. Find the prediction and the residual of every month.\n",
    "\n",
    "Idea. $e = y - \\hat{y}$, true minus predicted (Part 3).\n",
    "\n",
    "| $x$ | $y$ | $\\hat{y} = 2.6 + 0.8x$ | $e = y - \\hat{y}$ |\n",
    "| --- | --- | --- | --- |\n",
    "| 1 | 3 | 3.4 | $-0.4$ |\n",
    "| 2 | 5 | 4.2 | 0.8 |\n",
    "| 3 | 4 | 5 | $-1$ |\n",
    "| 4 | 7 | 5.8 | 1.2 |\n",
    "| 5 | 6 | 6.6 | $-0.6$ |\n",
    "| Sum |  |  | 0 |\n",
    "\n",
    "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.\n",
    "\n",
    "Problem 4. SSE and MSE\n",
    "\n",
    "Find the SSE and the MSE of the line of Problem 3.\n",
    "\n",
    "Idea. Square the residuals, add them, divide by $n$ (Part 4).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{SSE} &= (-0.4)^2 + 0.8^2 + (-1)^2 + 1.2^2 + (-0.6)^2 \\\\[4pt]\n",
    "&= 0.16 + 0.64 + 1 + 1.44 + 0.36 = 3.6 \\\\[4pt]\n",
    "\\text{MSE} &= \\frac{3.6}{5} = 0.72\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "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.\n",
    "\n",
    "Problem 5. Which line fits better?\n",
    "\n",
    "Four points: $(1, 3)$, $(2, 5)$, $(3, 6)$, $(4, 10)$. Compare the lines $\\hat{y} = 1 + 2x$ and $\\hat{y} = 0.5 + 2.2x$ by their SSE.\n",
    "\n",
    "Idea. The line with the smaller SSE fits better (Part 4).\n",
    "\n",
    "| $x$ | $y$ | first line $\\hat{y}$ | $e$ | second line $\\hat{y}$ | $e$ |\n",
    "| --- | --- | --- | --- | --- | --- |\n",
    "| 1 | 3 | 3 | 0 | 2.7 | 0.3 |\n",
    "| 2 | 5 | 5 | 0 | 4.9 | 0.1 |\n",
    "| 3 | 6 | 7 | $-1$ | 7.1 | $-1.1$ |\n",
    "| 4 | 10 | 9 | 1 | 9.3 | 0.7 |\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{first line:} \\\\\n",
    "& \\quad \\text{SSE} = 0^2 + 0^2 + (-1)^2 + 1^2 = 2 \\\\[6pt]\n",
    "& \\text{second line:} \\\\\n",
    "& \\quad \\text{SSE} = 0.3^2 + 0.1^2 + (-1.1)^2 + 0.7^2 \\\\\n",
    "& \\quad \\phantom{\\text{SSE}} = 0.09 + 0.01 + 1.21 + 0.49 = 1.8\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "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.\n",
    "\n",
    "Problem 6. The best line from the formulas\n",
    "\n",
    "Find the least-squares line for the points $(0, 1)$, $(1, 3)$, $(2, 4)$, $(3, 4)$, $(4, 8)$.\n",
    "\n",
    "Idea. $w_1 = \\dfrac{\\sum (x - \\bar{x})(y - \\bar{y})}{\\sum (x - \\bar{x})^2}$, then $w_0 = \\bar{y} - w_1\\,\\bar{x}$ (Part 5).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\bar{x} &= \\frac{0 + 1 + 2 + 3 + 4}{5} = 2 \\\\[4pt]\n",
    "\\bar{y} &= \\frac{1 + 3 + 4 + 4 + 8}{5} = 4\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "| $x$ | $y$ | $x - \\bar{x}$ | $y - \\bar{y}$ | product | $(x - \\bar{x})^2$ |\n",
    "| --- | --- | --- | --- | --- | --- |\n",
    "| 0 | 1 | $-2$ | $-3$ | 6 | 4 |\n",
    "| 1 | 3 | $-1$ | $-1$ | 1 | 1 |\n",
    "| 2 | 4 | 0 | 0 | 0 | 0 |\n",
    "| 3 | 4 | 1 | 0 | 0 | 1 |\n",
    "| 4 | 8 | 2 | 4 | 8 | 4 |\n",
    "| Sum |  |  |  | 15 | 10 |\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "w_1 &= \\frac{15}{10} = 1.5 \\\\[4pt]\n",
    "w_0 &= 4 - 1.5 \\times 2 = 1 \\\\[4pt]\n",
    "\\hat{y} &= 1 + 1.5\\,x\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: the slope compares how $x$ and $y$ move together (the top) with how much $x$ moves at all (the bottom). The intercept then puts the line through the point of the means $(2, 4)$.\n",
    "\n",
    "Problem 7. A line for the deliveries\n",
    "\n",
    "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.\n",
    "\n",
    "Idea. The five steps of Part 5.\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\bar{x} = \\frac{20}{4} = 5 \\qquad \\bar{y} = \\frac{72}{4} = 18 \\\\[4pt]\n",
    "& \\text{deviations of } x:\\ -3,\\ -1,\\ 1,\\ 3 \\\\[4pt]\n",
    "& \\text{deviations of } y:\\ -7,\\ -3,\\ 4,\\ 6 \\\\[4pt]\n",
    "& \\text{products: } 21 + 3 + 4 + 18 = 46 \\\\[4pt]\n",
    "& \\text{squares: } 9 + 1 + 1 + 9 = 20 \\\\[4pt]\n",
    "& w_1 = \\frac{46}{20} = 2.3 \\\\[4pt]\n",
    "& w_0 = 18 - 2.3 \\times 5 = 18 - 11.5 = 6.5 \\\\[4pt]\n",
    "& \\hat{y} = 6.5 + 2.3\\,x \\\\[4pt]\n",
    "& x = 5:\\quad \\hat{y} = 6.5 + 11.5 = 18\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "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.\n",
    "\n",
    "Problem 8. RMSE and MAE\n",
    "\n",
    "For the line $\\hat{y} = 1 + 1.5x$ of Problem 6, find the MSE, the RMSE and the MAE.\n",
    "\n",
    "Idea. The residuals first, then the three formulas of Part 7.\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{predictions: } 1,\\ 2.5,\\ 4,\\ 5.5,\\ 7 \\\\[4pt]\n",
    "& \\text{residuals: } 0,\\ 0.5,\\ 0,\\ -1.5,\\ 1 \\\\[4pt]\n",
    "& \\text{SSE} = 0 + 0.25 + 0 + 2.25 + 1 = 3.5 \\\\[4pt]\n",
    "& \\text{MSE} = \\frac{3.5}{5} = 0.7 \\\\[4pt]\n",
    "& \\text{RMSE} = \\sqrt{0.7} = 0.8367 \\\\[4pt]\n",
    "& \\text{MAE} = \\frac{0 + 0.5 + 0 + 1.5 + 1}{5} = \\frac{3}{5} = 0.6\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: the RMSE (0.84) is larger than the MAE (0.6) because the square gives the one large residual, $-1.5$, more weight. Both are in the unit of $y$.\n",
    "\n",
    "Problem 9. The R² score\n",
    "\n",
    "Find R² for the line of Problem 6.\n",
    "\n",
    "Idea. $R^2 = 1 - \\dfrac{\\text{SSE}}{\\text{SST}}$, where SST is the squared error of \"always the mean\" (Part 7).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\bar{y} &= 4 \\\\[4pt]\n",
    "\\text{SST} &= (-3)^2 + (-1)^2 + 0^2 + 0^2 + 4^2 \\\\[4pt]\n",
    "&= 9 + 1 + 0 + 0 + 16 = 26 \\\\[4pt]\n",
    "\\text{SSE} &= 3.5 \\\\[4pt]\n",
    "R^2 &= 1 - \\frac{3.5}{26} = 1 - 0.1346 = 0.8654\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "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 $y$.\n",
    "\n",
    "### Level 2: Complete regressions, gradient descent and several features\n",
    "\n",
    "Problem 10. A complete regression by hand\n",
    "\n",
    "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.\n",
    "\n",
    "Idea. Fit the line (Part 5), then the residuals, SSE, SST and R² (Part 7).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\bar{x} = 3 \\qquad \\bar{y} = \\frac{70}{5} = 14 \\\\[4pt]\n",
    "& \\text{deviations of } x:\\ -2,\\ -1,\\ 0,\\ 1,\\ 2 \\\\[4pt]\n",
    "& \\text{deviations of } y:\\ 4,\\ 2,\\ 1,\\ -2,\\ -5 \\\\[4pt]\n",
    "& \\text{products: } -8 - 2 + 0 - 2 - 10 = -22 \\\\[4pt]\n",
    "& \\text{squares: } 4 + 1 + 0 + 1 + 4 = 10 \\\\[4pt]\n",
    "& w_1 = \\frac{-22}{10} = -2.2 \\\\[4pt]\n",
    "& w_0 = 14 - (-2.2) \\times 3 = 14 + 6.6 = 20.6\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{predictions: } 18.4,\\ 16.2,\\ 14,\\ 11.8,\\ 9.6 \\\\[4pt]\n",
    "& \\text{residuals: } -0.4,\\ -0.2,\\ 1,\\ 0.2,\\ -0.6 \\\\[4pt]\n",
    "& \\text{SSE} = 0.16 + 0.04 + 1 + 0.04 + 0.36 = 1.6 \\\\[4pt]\n",
    "& \\text{SST} = 16 + 4 + 1 + 4 + 25 = 50 \\\\[4pt]\n",
    "& R^2 = 1 - \\frac{1.6}{50} = 0.968\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: $\\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.\n",
    "\n",
    "Problem 11. Salary and experience\n",
    "\n",
    "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?\n",
    "\n",
    "Idea. Parts 5 and 7, and the warning about predictions outside the data (Part 10).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{(a)} \\\\\n",
    "& \\bar{x} = 5 \\qquad \\bar{y} = \\frac{8000}{5} = 1600 \\\\[4pt]\n",
    "& \\text{deviations of } x:\\ -4,\\ -2,\\ 0,\\ 2,\\ 4 \\\\[4pt]\n",
    "& \\text{deviations of } y:\\ -700,\\ -300,\\ -100,\\ 500,\\ 600 \\\\[4pt]\n",
    "& \\text{products: } 2800 + 600 + 0 + 1000 + 2400 = 6800 \\\\[4pt]\n",
    "& \\text{squares: } 16 + 4 + 0 + 4 + 16 = 40 \\\\[4pt]\n",
    "& w_1 = \\frac{6800}{40} = 170 \\\\[4pt]\n",
    "& w_0 = 1600 - 170 \\times 5 = 750 \\\\[4pt]\n",
    "& \\hat{y} = 750 + 170\\,x\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{(b)} \\\\\n",
    "& \\text{predictions: } 920,\\ 1260,\\ 1600,\\ 1940,\\ 2280 \\\\[4pt]\n",
    "& \\text{residuals: } -20,\\ 40,\\ -100,\\ 160,\\ -80 \\\\[4pt]\n",
    "& \\text{SSE} = 400 + 1600 + 10000 + 25600 + 6400 \\\\\n",
    "& \\phantom{\\text{SSE}} = 44000 \\\\[4pt]\n",
    "& \\text{MSE} = \\frac{44000}{5} = 8800 \\\\[4pt]\n",
    "& \\text{RMSE} = \\sqrt{8800} = 93.81 \\\\[6pt]\n",
    "& \\text{(c)}\\quad \\hat{y} = 750 + 170 \\times 6 = 1770 \\\\[6pt]\n",
    "& \\text{(d)}\\quad \\hat{y} = 750 + 170 \\times 30 = 5850\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "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.\n",
    "\n",
    "Problem 12. Two checks of a line\n",
    "\n",
    "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.\n",
    "\n",
    "Idea. The formulas, and the facts about the least-squares line (Part 5).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\bar{x} = 20 \\qquad \\bar{y} = \\frac{155}{5} = 31 \\\\[4pt]\n",
    "& \\text{deviations of } x:\\ -10,\\ -5,\\ 0,\\ 5,\\ 10 \\\\[4pt]\n",
    "& \\text{deviations of } y:\\ -11,\\ -7,\\ 1,\\ 4,\\ 13 \\\\[4pt]\n",
    "& \\text{products: } 110 + 35 + 0 + 20 + 130 = 295 \\\\[4pt]\n",
    "& \\text{squares: } 100 + 25 + 0 + 25 + 100 = 250 \\\\[4pt]\n",
    "& w_1 = \\frac{295}{250} = 1.18 \\\\[4pt]\n",
    "& w_0 = 31 - 1.18 \\times 20 = 31 - 23.6 = 7.4\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{check 1: } 7.4 + 1.18 \\times 20 = 7.4 + 23.6 = 31 = \\bar{y} \\\\[4pt]\n",
    "& \\text{predictions: } 19.2,\\ 25.1,\\ 31,\\ 36.9,\\ 42.8 \\\\[4pt]\n",
    "& \\text{residuals: } 0.8,\\ -1.1,\\ 1,\\ -1.9,\\ 1.2 \\\\[4pt]\n",
    "& \\text{check 2: } 0.8 - 1.1 + 1 - 1.9 + 1.2 = 0\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "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.\n",
    "\n",
    "Problem 13. Gradient descent by hand\n",
    "\n",
    "Two points: $(1, 3)$ and $(2, 6)$. The model is $\\hat{y} = w\\,x$. Start at $w = 1$ and take three steps of gradient descent with the learning rate $\\alpha = 0.1$.\n",
    "\n",
    "Idea. $\\text{slope} = \\dfrac{2}{n} \\sum (\\hat{y} - y)\\,x$, then $w_{\\text{new}} = w_{\\text{old}} - \\alpha \\times \\text{slope}$ (Part 6).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{slope} &= \\frac{2}{2}\\left[(w \\times 1 - 3) \\times 1 + (w \\times 2 - 6) \\times 2\\right] \\\\[4pt]\n",
    "&= (w - 3) + (4w - 12) = 5w - 15\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "| Step | $w$ | slope $5w - 15$ | new $w$ |\n",
    "| --- | --- | --- | --- |\n",
    "| 1 | 1 | $-10$ | 2 |\n",
    "| 2 | 2 | $-5$ | 2.5 |\n",
    "| 3 | 2.5 | $-2.5$ | 2.75 |\n",
    "\n",
    "Why: both points lie on the line $\\hat{y} = 3x$, so the lowest point of the loss is $w = 3$. The slope is negative as long as $w$ is below 3, so every step makes $w$ larger, and the steps shrink as the slope gets flatter: 1, 0.5, 0.25.\n",
    "\n",
    "Problem 14. A learning rate that is too large\n",
    "\n",
    "Repeat Problem 13 with the learning rate $\\alpha = 0.5$. What happens?\n",
    "\n",
    "Idea. The same rule; watch the distance from the lowest point $w = 3$ (Part 6).\n",
    "\n",
    "| Step | $w$ | slope $5w - 15$ | new $w$ |\n",
    "| --- | --- | --- | --- |\n",
    "| 1 | 1 | $-10$ | 6 |\n",
    "| 2 | 6 | 15 | $-1.5$ |\n",
    "| 3 | $-1.5$ | $-22.5$ | 9.75 |\n",
    "\n",
    "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.\n",
    "\n",
    "Problem 15. A model with three features\n",
    "\n",
    "A company describes the salaries of its employees with the model $\\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?\n",
    "\n",
    "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).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{(a)}\\quad \\text{salary} &= 400 + 120 \\times 5 + 150 \\times 2 + 2 \\times 30 \\\\[4pt]\n",
    "&= 400 + 600 + 300 + 60 = 1360\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "(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.\n",
    "\n",
    "(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 \\times 50 = 100$, almost as much as one level of education.\n",
    "\n",
    "Why: weights of features with different scales cannot be compared. Topic 24 shows how scaling makes them comparable.\n",
    "\n",
    "Problem 16. The normal equation by hand\n",
    "\n",
    "Find the least-squares line for the points $(0, 2)$, $(1, 3)$, $(2, 7)$ with the normal equation $\\mathbf{w} = (X^{T} X)^{-1} X^{T} \\mathbf{y}$, and check the result with the formulas of Part 5.\n",
    "\n",
    "Idea. $X$ gets a first column of ones; the rest is the matrix work of Topic 14 (Part 8).\n",
    "\n",
    "$$\n",
    "X = \\begin{bmatrix} 1 & 0 \\\\ 1 & 1 \\\\ 1 & 2 \\end{bmatrix} \\qquad \\mathbf{y} = \\begin{bmatrix} 2 \\\\ 3 \\\\ 7 \\end{bmatrix}\n",
    "$$\n",
    "\n",
    "$$\n",
    "X^{T} X = \\begin{bmatrix} 3 & 3 \\\\ 3 & 5 \\end{bmatrix} \\qquad X^{T} \\mathbf{y} = \\begin{bmatrix} 12 \\\\ 17 \\end{bmatrix}\n",
    "$$\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\det(X^{T} X) &= 3 \\times 5 - 3 \\times 3 = 6 \\\\[6pt]\n",
    "(X^{T} X)^{-1} &= \\frac{1}{6} \\begin{bmatrix} 5 & -3 \\\\ -3 & 3 \\end{bmatrix}\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\mathbf{w} &= \\frac{1}{6} \\begin{bmatrix} 5 \\times 12 - 3 \\times 17 \\\\ -3 \\times 12 + 3 \\times 17 \\end{bmatrix} \\\\[6pt]\n",
    "&= \\frac{1}{6} \\begin{bmatrix} 9 \\\\ 15 \\end{bmatrix} = \\begin{bmatrix} 1.5 \\\\ 2.5 \\end{bmatrix}\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{check: } \\bar{x} = 1, \\quad \\bar{y} = 4 \\\\[4pt]\n",
    "& \\text{products: } 2 + 0 + 3 = 5 \\qquad \\text{squares: } 2 \\\\[4pt]\n",
    "& w_1 = \\frac{5}{2} = 2.5 \\qquad w_0 = 4 - 2.5 \\times 1 = 1.5\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: $\\hat{y} = 1.5 + 2.5x$ both ways. The entries of $X^{T} X$ and $X^{T} \\mathbf{y}$ are the sums $n$, $\\sum x$, $\\sum x^2$, $\\sum y$ and $\\sum xy$: the normal equation is the formula of Part 5 in the language of matrices, and it stays the same when $X$ gets more columns.\n",
    "\n",
    "Problem 17. The deliveries with scikit-learn\n",
    "\n",
    "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.\n",
    "\n",
    "Idea. Reshape the feature into a column, then create, `fit`, `predict` (Part 9)."
   ],
   "id": "t22-041"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from sklearn.linear_model import LinearRegression\n",
    "\n",
    "distance = np.array([2, 4, 6, 8])\n",
    "minutes = np.array([11, 15, 22, 24])\n",
    "\n",
    "X = distance.reshape(-1, 1)\n",
    "model = LinearRegression()\n",
    "model.fit(X, minutes)\n",
    "\n",
    "print(round(model.intercept_, 2), model.coef_.round(2))\n",
    "print(model.predict(np.array([[5]])).round(2))"
   ],
   "id": "t22-042"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "Problem 18. The measures with scikit-learn\n",
    "\n",
    "For the model of Problem 17, print the MSE, the RMSE, the MAE and R².\n",
    "\n",
    "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."
   ],
   "id": "t22-043"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score, root_mean_squared_error\n",
    "\n",
    "predicted = model.predict(X)\n",
    "\n",
    "print(round(mean_squared_error(minutes, predicted), 4))\n",
    "print(round(root_mean_squared_error(minutes, predicted), 4))\n",
    "print(round(mean_absolute_error(minutes, predicted), 4))\n",
    "print(round(r2_score(minutes, predicted), 4))"
   ],
   "id": "t22-044"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: by hand: the residuals are $-0.1,\\ -0.7,\\ 1.7,\\ -0.9$, so $\\text{SSE} = 4.2$, $\\text{MSE} = 1.05$, $\\text{RMSE} = 1.0247$, $\\text{MAE} = 0.85$, and with $\\text{SST} = 110$ the score is $R^2 = 0.9618$. The predictions are off by about one minute.\n",
    "\n",
    "### Level 3: Regression in code\n",
    "\n",
    "Problem 19. The formulas in NumPy\n",
    "\n",
    "For the cafe of Problem 12, calculate the slope and the intercept with the formulas of Part 5 in NumPy, without scikit-learn.\n",
    "\n",
    "Idea. Deviations are one subtraction for a whole array (Topic 9)."
   ],
   "id": "t22-045"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "temperature = np.array([10, 15, 20, 25, 30])\n",
    "drinks = np.array([20, 24, 32, 35, 44])\n",
    "\n",
    "x_dev = temperature - temperature.mean()\n",
    "y_dev = drinks - drinks.mean()\n",
    "\n",
    "w1 = (x_dev * y_dev).sum() / (x_dev ** 2).sum()\n",
    "w0 = drinks.mean() - w1 * temperature.mean()\n",
    "\n",
    "print(round(w1, 2), round(w0, 2))\n",
    "print(round(w0 + w1 * 22, 2))"
   ],
   "id": "t22-046"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "Problem 20. R² in two ways\n",
    "\n",
    "For the cars of Problem 10, calculate R² from its definition with NumPy and compare it with `model.score`.\n",
    "\n",
    "Idea. $R^2 = 1 - \\dfrac{\\text{SSE}}{\\text{SST}}$ (Part 7); `score` gives the same number (Part 9)."
   ],
   "id": "t22-047"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from sklearn.linear_model import LinearRegression\n",
    "\n",
    "age = np.array([1, 2, 3, 4, 5])\n",
    "price = np.array([18, 16, 15, 12, 9])\n",
    "X = age.reshape(-1, 1)\n",
    "\n",
    "model = LinearRegression()\n",
    "model.fit(X, price)\n",
    "predicted = model.predict(X)\n",
    "\n",
    "sse = ((price - predicted) ** 2).sum()\n",
    "sst = ((price - price.mean()) ** 2).sum()\n",
    "\n",
    "print(round(sse, 2), round(sst, 2))\n",
    "print(round(1 - sse / sst, 4))\n",
    "print(round(model.score(X, price), 4))"
   ],
   "id": "t22-048"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "Problem 21. A function for the loss\n",
    "\n",
    "Write a function `mse(w0, w1)` that returns the mean squared error of the line $\\hat{y} = w_0 + w_1 x$ on the five students. Use it to compare the three lines of Part 4.\n",
    "\n",
    "Idea. The loss is a function of the parameters: the data stays the same, the line changes (Part 4)."
   ],
   "id": "t22-049"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "hours = np.array([2, 4, 5, 6, 8])\n",
    "marks = np.array([50, 60, 65, 75, 80])\n",
    "\n",
    "def mse(w0, w1):\n",
    "    predicted = w0 + w1 * hours\n",
    "    return ((marks - predicted) ** 2).mean()\n",
    "\n",
    "print(mse(40, 5))\n",
    "print(mse(30, 7))\n",
    "print(mse(39.75, 5.25))"
   ],
   "id": "t22-050"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "Problem 22. Gradient descent with one parameter\n",
    "\n",
    "Repeat the table of Part 6 in code: the points $(1, 2)$ and $(2, 4)$, the model $\\hat{y} = w\\,x$, the start $w = 0$, the learning rate 0.1. Print $w$ and the loss after each of the first four steps, and $w$ after 20 steps.\n",
    "\n",
    "Idea. One loop: the error, the slope, the update (Part 6)."
   ],
   "id": "t22-051"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "x = np.array([1, 2])\n",
    "y = np.array([2, 4])\n",
    "\n",
    "w = 0.0\n",
    "rate = 0.1\n",
    "\n",
    "for step in range(1, 21):\n",
    "    error = w * x - y\n",
    "    slope = 2 * (error * x).mean()\n",
    "    w = w - rate * slope\n",
    "    if step <= 4:\n",
    "        print(step, round(w, 4), round(((w * x - y) ** 2).mean(), 4))\n",
    "\n",
    "print(round(w, 6))"
   ],
   "id": "t22-052"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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 $w$ differs from 2 only in the sixth decimal.\n",
    "\n",
    "Problem 23. Gradient descent for a whole line\n",
    "\n",
    "Train the line for the cars of Problem 10 by gradient descent: start at $w_0 = 0$, $w_1 = 0$, learning rate 0.05, 5,000 steps. Compare with the exact answer $\\hat{y} = 20.6 - 2.2x$.\n",
    "\n",
    "Idea. Two slopes, two updates in every step (Part 6)."
   ],
   "id": "t22-053"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "age = np.array([1, 2, 3, 4, 5])\n",
    "price = np.array([18, 16, 15, 12, 9])\n",
    "\n",
    "w0, w1 = 0.0, 0.0\n",
    "rate = 0.05\n",
    "\n",
    "for step in range(5000):\n",
    "    error = (w0 + w1 * age) - price\n",
    "    slope0 = 2 * error.mean()\n",
    "    slope1 = 2 * (error * age).mean()\n",
    "    w0 = w0 - rate * slope0\n",
    "    w1 = w1 - rate * slope1\n",
    "\n",
    "print(round(w0, 2), round(w1, 2))\n",
    "print(round((((w0 + w1 * age) - price) ** 2).mean(), 4))"
   ],
   "id": "t22-054"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.32$. Both slopes are calculated from the same `error` before either parameter is changed: the two updates belong to one step.\n",
    "\n",
    "Problem 24. Several features\n",
    "\n",
    "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².\n",
    "\n",
    "Idea. `X` is a table with two columns; everything else is unchanged (Parts 8 and 9)."
   ],
   "id": "t22-055"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from sklearn.linear_model import LinearRegression\n",
    "\n",
    "people = np.array([\n",
    "    [1, 12],\n",
    "    [2, 16],\n",
    "    [3, 12],\n",
    "    [5, 16],\n",
    "    [6, 14],\n",
    "    [8, 12],\n",
    "    [9, 16],\n",
    "    [10, 18],\n",
    "])\n",
    "salary = np.array([820, 1190, 1060, 1540, 1490, 1620, 2010, 2290])\n",
    "\n",
    "model = LinearRegression()\n",
    "model.fit(people, salary)\n",
    "\n",
    "print(round(model.intercept_, 1))\n",
    "print(model.coef_.round(1))\n",
    "print(model.predict(np.array([[6, 16]])).round(0))\n",
    "print(round(model.score(people, salary), 4))"
   ],
   "id": "t22-056"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "Problem 25. The effect of one outlier\n",
    "\n",
    "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.\n",
    "\n",
    "Idea. The squared loss lets one distant point pull the line (Part 10)."
   ],
   "id": "t22-057"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from sklearn.linear_model import LinearRegression\n",
    "\n",
    "hours = np.array([2, 4, 5, 6, 8])\n",
    "marks = np.array([50, 60, 65, 75, 80])\n",
    "\n",
    "hours_more = np.append(hours, 9)\n",
    "marks_more = np.append(marks, 40)\n",
    "\n",
    "for x, y in [(hours, marks), (hours_more, marks_more)]:\n",
    "    X = x.reshape(-1, 1)\n",
    "    model = LinearRegression()\n",
    "    model.fit(X, y)\n",
    "    print(model.coef_.round(2), round(model.intercept_, 2), round(model.score(X, y), 4))"
   ],
   "id": "t22-058"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "Problem 26. A line through noisy data\n",
    "\n",
    "Generate 60 points with $y = 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.\n",
    "\n",
    "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)."
   ],
   "id": "t22-059"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.metrics import root_mean_squared_error\n",
    "\n",
    "rng = np.random.default_rng(1)\n",
    "x = rng.uniform(0, 20, 60).round(1)\n",
    "y = (3 * x + 10 + rng.normal(0, 5, 60)).round(1)\n",
    "\n",
    "X = x.reshape(-1, 1)\n",
    "model = LinearRegression()\n",
    "model.fit(X, y)\n",
    "\n",
    "print(round(model.intercept_, 2), model.coef_.round(2))\n",
    "print(round(model.score(X, y), 3))\n",
    "print(round(root_mean_squared_error(y, model.predict(X)), 2))"
   ],
   "id": "t22-060"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The chart, in a second cell:"
   ],
   "id": "t22-061"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "plt.scatter(x, y, label=\"the 60 points\")\n",
    "plt.plot(x, model.predict(X), color=\"orange\", label=\"regression line\")\n",
    "plt.xlabel(\"x\")\n",
    "plt.ylabel(\"y\")\n",
    "plt.title(\"A line through noisy data\")\n",
    "plt.legend()\n",
    "plt.show()"
   ],
   "id": "t22-062"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "## 15. Quick summary\n",
    "\n",
    "| Idea | Formula or code | In words |\n",
    "| --- | --- | --- |\n",
    "| The model | $\\hat{y} = w_0 + w_1 x$ | a line: intercept plus slope times the feature |\n",
    "| Residual | $e = y - \\hat{y}$ | the vertical distance of a point from the line |\n",
    "| SSE | $\\sum (y - \\hat{y})^2$ | the sum of the squared residuals |\n",
    "| MSE | $\\text{SSE} / n$ | the loss that training makes small |\n",
    "| Slope | $w_1 = \\frac{\\sum (x - \\bar{x})(y - \\bar{y})}{\\sum (x - \\bar{x})^2}$ | how $x$ and $y$ move together, per unit of movement of $x$ |\n",
    "| Intercept | $w_0 = \\bar{y} - w_1\\,\\bar{x}$ | puts the line through the point of the means |\n",
    "| Gradient descent | $w_{\\text{new}} = w_{\\text{old}} - \\alpha \\times \\text{slope}$ | small steps downhill on the loss |\n",
    "| RMSE | $\\sqrt{\\text{MSE}}$ | the typical error, in the unit of $y$ |\n",
    "| MAE | $\\frac{1}{n} \\sum \\lvert y - \\hat{y} \\rvert$ | the average absolute error |\n",
    "| $R^2$ | $1 - \\frac{\\text{SSE}}{\\text{SST}}$ | the share of the variation that the model explains |\n",
    "| Multiple regression | $\\hat{y} = w_0 + w_1 x_1 + \\dots + w_p x_p$ | one weight for every feature |\n",
    "| Normal equation | $\\mathbf{w} = (X^{T} X)^{-1} X^{T} \\mathbf{y}$ | the best weights in one formula |\n",
    "| scikit-learn | `LinearRegression().fit(X, y)` | then `intercept_`, `coef_`, `predict`, `score` |\n",
    "\n",
    "### Rules to keep\n",
    "\n",
    "1. Look at the points before you fit a line: a scatter plot first, a residual plot after.\n",
    "2. The residual is true minus predicted, and the best line makes the sum of the squared residuals as small as possible.\n",
    "3. First the slope, then the intercept. The line passes through the point of the means.\n",
    "4. Report an error in the unit of the target (RMSE or MAE) and R². R² is not a share of right answers.\n",
    "5. A weight is the change per unit of its feature, with the other features held fixed. It is not a cause.\n",
    "6. Do not predict far outside the range of the data, and watch for outliers.\n",
    "7. In gradient descent the loss must fall step after step. If it grows, lower the learning rate.\n",
    "8. In scikit-learn `X` is a table with two dimensions: `reshape(-1, 1)` for a single feature.\n",
    "\n",
    "### What comes next\n",
    "\n",
    "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.\n",
    "\n",
    "Next: the practice notebook (topic-22-practice.ipynb), then Topic 23: Train/test split and cross-validation; overfitting, underfitting, and the bias-variance tradeoff."
   ],
   "id": "t22-063"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
