{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 23: Train/test split and cross-validation; overfitting, underfitting and the bias-variance tradeoff\n",
    "\n",
    "Asiman Data School, Module 3: Comprehensive Machine Learning. Week 12, Tuesday.\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. The practice problems are in a separate notebook, topic-23-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",
    "This notebook reads the file flats.csv. Put the file into the same folder as the notebook. On the Asiman Data School website the file is already there.\n",
    "\n",
    "Contents\n",
    "\n",
    "1. Why split the data?\n",
    "2. The split in Python\n",
    "3. Reading the two scores\n",
    "4. Overfitting and underfitting\n",
    "5. Cross-validation\n",
    "6. The bias-variance tradeoff\n",
    "7. Common mistakes\n",
    "8. Solved problems\n",
    "9. Practice (in topic-23-practice.ipynb)\n",
    "10. Check yourself (on the website)\n",
    "11. Quick summary"
   ],
   "id": "t23-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction: is the score fair?\n",
    "\n",
    "What matters most in this lesson. Five things matter most today. First, the rule: a model is judged on rows it has not seen, so a part of the data is put aside before training. Second, the code: `train_test_split` gives four pieces, `fit` gets the training pieces, and the measures get the test pieces. Third, how to read the two scores: both high and close together is a good fit, a high training score with a much lower test score is overfitting, and two low scores are underfitting. Fourth, cross-validation: several splits and the mean of their scores are steadier than one split. Fifth, the two words behind it all: bias, the error of a model that is too simple, and variance, the error of a model that follows its training rows too closely.\n",
    "\n",
    "The lesson is short. Its practice is one small project in eight steps on the same data file.\n",
    "\n",
    "The third lesson of Module 3. In Topic 22 you trained your first model and measured it with R² and RMSE. But every one of those numbers was calculated on the same points the model had learned from. This lesson asks whether that is a fair measure, and the answer is no. It shows the fair way: put a part of the data aside before training, and judge the model on that part.\n",
    "\n",
    "The lesson is short and practical. It explains why the data is split into a training part and a test part, how to read the two scores side by side, what overfitting and underfitting are, why one split is not enough and how cross-validation repairs that, and what the words bias and variance mean. Everything is done on one small data file, `flats.csv`, with the linear regression of Topic 22.\n",
    "\n",
    "You need: `LinearRegression`, `fit`, `predict`, R², MSE and RMSE (Topic 22), and reading a CSV file into a DataFrame (Topic 10).\n",
    "\n",
    "| Word | Meaning |\n",
    "| --- | --- |\n",
    "| training data | the rows the model learns from |\n",
    "| test data | the rows that are put aside and used only to judge the finished model |\n",
    "| training score, test score | the R² of the model on the training data and on the test data |\n",
    "| generalisation | how well a model works on data it has not seen |\n",
    "| overfitting | the model has learned the training data too closely, noise included: high training score, much lower test score |\n",
    "| underfitting | the model is too simple to find the pattern: low score on both parts |\n",
    "| cross-validation | splitting the data several times, so that every row is test data once, and averaging the scores |\n",
    "| fold | one of the equal parts the data is cut into for cross-validation |\n",
    "| bias | the error of a model that is too simple for the data |\n",
    "| variance | how much a model changes when it is trained on other rows |\n",
    "\n",
    "## 1. Why split the data?\n",
    "\n",
    "### 1.1 The problem with one set of data\n",
    "\n",
    "In Topic 22 the model was trained on five students and then measured on the same five students. That is like a teacher who gives the class twenty exercises with their answers, and then uses the same twenty exercises in the exam. A student who learned the twenty answers by heart gets full marks, and nobody finds out whether the student understood anything.\n",
    "\n",
    "A model can do the same. It can adapt so closely to the rows it was given that it reproduces them, noise and accidents included, without having found the real pattern. Its score on those rows is then excellent, and it says nothing about new data.\n",
    "\n",
    "But new data is the whole purpose. Nobody needs a model to tell the price of a flat that was already sold. The model is needed for the flat that comes on the market tomorrow. The ability to work on data it has not seen is called generalisation, and that is what must be measured.\n",
    "\n",
    "### 1.2 The solution: put a part aside\n",
    "\n",
    "Before training, the rows are divided into two parts:\n",
    "\n",
    "- The training data is what the model learns from. `fit` sees only these rows.\n",
    "- The test data is locked away during the training. When the model is finished, it predicts the test rows, and its predictions are compared with the true answers.\n",
    "\n",
    "For the model, the test rows are new: it has never seen them. So the score on the test data is an honest estimate of how the model will do on tomorrow's flats.\n",
    "\n",
    "### 1.3 How the split is made\n",
    "\n",
    "- At random. The rows are shuffled before they are divided. If the file is sorted, for example by price, and the last 20 percent were simply cut off, the test data would contain only the most expensive flats, and it would not look like the training data.\n",
    "- Usually 80 percent for training and 20 percent for testing. 75 to 25 and 70 to 30 are also common. More training rows give a better model; more test rows give a more reliable score. With very little data, the test part must not become too small: a score from 5 rows means almost nothing.\n",
    "- Once, and before anything else. The test data is separated first and touched only at the very end.\n",
    "\n",
    "### 1.4 Why the test score is the one that counts\n",
    "\n",
    "After the split, every measure exists twice: on the training data and on the test data.\n",
    "\n",
    "- The training score says how well the model reproduces what it has already seen. It is always flattering.\n",
    "- The test score says how well the model predicts what it has not seen. That is the question we care about.\n",
    "\n",
    "So the rule of this lesson: a model is reported and compared by its score on the test data. The training score is not thrown away. It is useful as the second half of a comparison, as Part 3 shows.\n",
    "\n",
    "## 2. The split in Python\n",
    "\n",
    "### 2.1 The data\n",
    "\n",
    "The file `flats.csv` describes 200 invented flats. Every column is a number, so the data can go into a model as it is."
   ],
   "id": "t23-001"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"flats.csv\")\n",
    "\n",
    "print(df.shape)\n",
    "print(df.columns.tolist())"
   ],
   "id": "t23-002"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The six columns that matter most here, for the first five flats:"
   ],
   "id": "t23-003"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df[[\"area\", \"rooms\", \"age\", \"floor\", \"distance_km\", \"price\"]].head())"
   ],
   "id": "t23-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| Column | Meaning |\n",
    "| --- | --- |\n",
    "| `area` | the area in m² |\n",
    "| `rooms` | the number of rooms |\n",
    "| `age` | the age of the building in years |\n",
    "| `floor` | the floor |\n",
    "| `distance_km` | the distance to the city centre in km |\n",
    "| `photos` | the number of photographs in the advertisement |\n",
    "| `listing_day` | the day of the month on which the advertisement was posted |\n",
    "| `owner_age` | the age of the owner |\n",
    "| `building_number` | the number of the building in its street |\n",
    "| `agent_id` | the number of the estate agent |\n",
    "| `price` | the price in thousands: the target |\n",
    "\n",
    "The first five columns describe the flat. The next five have nothing to do with its price. They will be useful later, to show how a model goes wrong.\n",
    "\n",
    "### 2.2 Step 1: X and y\n",
    "\n",
    "The features are the five columns that describe the flat, and the target is the price:"
   ],
   "id": "t23-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X = df[[\"area\", \"rooms\", \"age\", \"floor\", \"distance_km\"]]\n",
    "y = df[\"price\"]\n",
    "\n",
    "print(X.shape, y.shape)"
   ],
   "id": "t23-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.3 Step 2: the split\n",
    "\n",
    "Change it and run: change `test_size` to `0.3` and run: 60 flats become test data and 140 stay for the training."
   ],
   "id": "t23-007"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
    "\n",
    "print(X_train.shape, X_test.shape)\n",
    "print(y_train.shape, y_test.shape)"
   ],
   "id": "t23-008"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- `test_size=0.2`: 20 percent of the rows, 40 flats, become the test data. The other 160 are the training data.\n",
    "- `random_state=42`: the rows are shuffled at random before they are divided. This number fixes the shuffle, so that the same rows land in the test data every time the code runs, on your computer and on this page. Any whole number works; another number gives another split.\n",
    "- The function returns four pieces, always in this order: the training features, the test features, the training target, the test target.\n",
    "\n",
    "### 2.4 Step 3: train on the training data"
   ],
   "id": "t23-009"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import LinearRegression\n",
    "\n",
    "model = LinearRegression()\n",
    "model.fit(X_train, y_train)\n",
    "\n",
    "print(round(model.score(X_train, y_train), 3))\n",
    "print(round(model.score(X_test, y_test), 3))"
   ],
   "id": "t23-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`fit` gets the training data and nothing else. `score` is R² (Topic 22): the first line is the training score, the second the test score.\n",
    "\n",
    "### 2.5 Step 4: the errors on the test data\n",
    "\n",
    "R² says how much of the variation is explained. MSE and RMSE say how large the errors are. For them, the model first predicts the test rows:"
   ],
   "id": "t23-011"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import mean_squared_error, r2_score, root_mean_squared_error\n",
    "\n",
    "y_pred = model.predict(X_test)\n",
    "\n",
    "print(round(r2_score(y_test, y_pred), 3))\n",
    "print(round(mean_squared_error(y_test, y_pred), 2))\n",
    "print(round(root_mean_squared_error(y_test, y_pred), 2))"
   ],
   "id": "t23-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The three functions get the true answers of the test rows, `y_test`, and the predictions for the test rows, `y_pred`. The R² is the test score of Step 3. The RMSE says that the price of a flat the model has never seen is predicted with a typical error of about 13 thousand, for prices between 20 and 294 thousand.\n",
    "\n",
    "### 2.6 The whole recipe\n",
    "\n",
    "1. Read the data.\n",
    "2. Choose `X` (the features) and `y` (the target).\n",
    "3. Split: `train_test_split(X, y, test_size=0.2, random_state=42)`.\n",
    "4. Create the model and `fit` it on `X_train` and `y_train`.\n",
    "5. Predict the test rows: `y_pred = model.predict(X_test)`.\n",
    "6. Measure on the test data: R², MSE, RMSE, with `y_test` and `y_pred`.\n",
    "7. Compare the training score with the test score (Part 3).\n",
    "\n",
    "## 3. Reading the two scores\n",
    "\n",
    "### 3.1 What a normal difference looks like\n",
    "\n",
    "The model of Part 2 has a training score of 0.953 and a test score of 0.952. The two numbers are almost equal, and that is the picture of a healthy model: it does on new flats what it does on the flats it learned from.\n",
    "\n",
    "In general the test score is a little lower than the training score. The model was fitted to the training rows, so it has a small advantage there. A small gap is normal and nothing to repair.\n",
    "\n",
    "There is no exact law for \"small\", but these rules of thumb are used in practice for R²:\n",
    "\n",
    "| Training score and test score | What it says |\n",
    "| --- | --- |\n",
    "| both high, the test score lower by a few hundredths (0.95 and 0.93) | normal: a good model |\n",
    "| both high, the test score slightly higher (0.94 and 0.95) | also normal: the test rows happened to be a little easier |\n",
    "| training score high, test score lower by 0.1 or more (0.98 and 0.70) | overfitting: the model learned the training rows, not the pattern |\n",
    "| both low (0.30 and 0.28) | underfitting: the model is too simple, or the features do not carry the answer |\n",
    "\n",
    "So two questions are asked about every model, in this order:\n",
    "\n",
    "1. Is the test score good enough for the purpose? That is the quality of the model.\n",
    "2. How far is it from the training score? That is the diagnosis: a large gap means overfitting, two low scores mean underfitting.\n",
    "\n",
    "The same reading works for the errors, with the direction turned round: a test RMSE that is much larger than the training RMSE is the sign of overfitting.\n",
    "\n",
    "## 4. Overfitting and underfitting\n",
    "\n",
    "### 4.1 Three models of the same data\n",
    "\n",
    "The three pictures show the same points. On the left the model is so simple that it misses the pattern. On the right the model is so flexible that it passes through every point: it has learned the noise. In the middle the model follows the pattern and leaves the noise alone.\n",
    "\n",
    "### 4.2 Underfitting\n",
    "\n",
    "A model underfits when it is too simple to find the pattern in the data.\n",
    "\n",
    "- How to recognise it: the training score is low, and the test score is low too. The model is bad everywhere, even on the rows it learned from.\n",
    "- When it happens: the model is too simple for the data (a straight line for a clear curve); the features do not carry the answer (predicting a price from the floor alone); too few features are used.\n",
    "- What helps: better or more features; a more flexible model. More rows do not help: a model that cannot describe the pattern cannot describe it with more data either.\n",
    "\n",
    "On the flats, a model that knows only the floor:\n",
    "\n",
    "Change it and run: replace `\"floor\"` by `\"area\"` and run: with a column that carries information, both scores rise to about 0.8."
   ],
   "id": "t23-013"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "X = df[[\"floor\"]]\n",
    "y = df[\"price\"]\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
    "\n",
    "model = LinearRegression()\n",
    "model.fit(X_train, y_train)\n",
    "\n",
    "print(round(model.score(X_train, y_train), 3))\n",
    "print(round(model.score(X_test, y_test), 3))"
   ],
   "id": "t23-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Both scores are near 0: the floor alone says almost nothing about the price. (A test score slightly below 0 means that the model is a little worse than always predicting the mean price, as Topic 22 explained.)\n",
    "\n",
    "### 4.3 Overfitting\n",
    "\n",
    "A model overfits when it learns the training data too closely: the noise and the accidents of those rows, and not only the pattern behind them.\n",
    "\n",
    "- How to recognise it: the training score is very high, and the test score is much lower.\n",
    "- When it happens: there are too few training rows for the number of features; the model is too flexible for the amount of data; features are used that have nothing to do with the target, and the model finds accidental patterns in them.\n",
    "- What helps: more training rows; fewer features (leave out the ones that carry no information); a simpler model; regularization, the subject of Topic 26.\n",
    "\n",
    "On the flats, a model that gets all ten columns, the five useless ones included, and only 14 flats to learn from:\n",
    "\n",
    "First the data: all ten columns, the usual split, and then only the first 14 training flats."
   ],
   "id": "t23-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "X = df.drop(columns=\"price\")\n",
    "y = df[\"price\"]\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
    "\n",
    "X_small = X_train.iloc[:14]\n",
    "y_small = y_train.iloc[:14]\n",
    "\n",
    "print(X_small.shape, X_test.shape)"
   ],
   "id": "t23-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Fourteen flats with ten features each, and the same 40 test flats as before. Now the model:\n",
    "\n",
    "Change it and run: change both `14` in the cell above to `100` and run the two cells again: with enough flats the gap closes."
   ],
   "id": "t23-017"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import LinearRegression\n",
    "\n",
    "model = LinearRegression()\n",
    "model.fit(X_small, y_small)\n",
    "\n",
    "print(round(model.score(X_small, y_small), 3))\n",
    "print(round(model.score(X_test, y_test), 3))"
   ],
   "id": "t23-018"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`df.drop(columns=\"price\")` is the table without the target: all ten features. `iloc[:14]` keeps the first 14 training rows.\n",
    "\n",
    "The training score is almost perfect: with ten weights and only 14 flats, the model can bend to fit nearly every one of them. On the 40 test flats the score falls to about 0.57. The model did not learn how prices work. It learned those 14 flats.\n",
    "\n",
    "### 4.4 The three models side by side\n",
    "\n",
    "| Model | Training rows | Features | Training score | Test score | Diagnosis |\n",
    "| --- | --- | --- | --- | --- | --- |\n",
    "| only the floor | 160 | 1 | 0.000 | $-0.021$ | underfitting |\n",
    "| the five columns of the flat | 160 | 5 | 0.953 | 0.952 | a good fit |\n",
    "| all ten columns, 14 flats | 14 | 10 | 0.996 | 0.566 | overfitting |\n",
    "\n",
    "Without test data, the third model would look like the best of the three. Only the test score shows that it is the worst of the two models that learned anything.\n",
    "\n",
    "## 5. Cross-validation\n",
    "\n",
    "### 5.1 One split is a matter of luck\n",
    "\n",
    "Which 40 flats land in the test data is decided by chance. With another `random_state` the same model gets another test score:"
   ],
   "id": "t23-019"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "X = df[[\"area\", \"rooms\", \"age\", \"floor\", \"distance_km\"]]\n",
    "y = df[\"price\"]\n",
    "\n",
    "for state in [1, 2, 3, 4, 5]:\n",
    "    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=state)\n",
    "    model = LinearRegression()\n",
    "    model.fit(X_train, y_train)\n",
    "    print(state, round(model.score(X_test, y_test), 3))"
   ],
   "id": "t23-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The same data, the same model, the same code: five different scores. None of them is wrong. Each is the answer for one particular set of 40 test flats. A single split can be lucky (easy test rows) or unlucky, and from one number you cannot tell which.\n",
    "\n",
    "### 5.2 The idea: every row is test data once\n",
    "\n",
    "Cross-validation removes the luck by repeating the split in an organised way. In 5-fold cross-validation:\n",
    "\n",
    "1. The data is cut into 5 equal parts, called folds.\n",
    "2. The model is trained on 4 folds and tested on the fifth.\n",
    "3. This is done 5 times, and each time another fold is the test data.\n",
    "4. The result is 5 scores. Their mean is the cross-validation score.\n",
    "\n",
    "### 5.3 Why this is better than one split\n",
    "\n",
    "- Every row is used for testing exactly once, and for training four times. No row is wasted, and no row is tested by a model that saw it.\n",
    "- The mean of five scores is steadier than one score. A lucky fold and an unlucky fold balance each other, just as the mean of five measurements is more reliable than a single one (Topic 17).\n",
    "- The spread of the five scores is information too. Five scores close together: the model behaves the same whatever rows it gets. Five scores far apart: the model depends strongly on its training rows, and no single number describes it well.\n",
    "\n",
    "The price is time: the model is trained five times, not once. For linear regression on 200 rows that is nothing. For a large model on millions of rows it matters.\n",
    "\n",
    "### 5.4 How many folds?\n",
    "\n",
    "5 and 10 are the usual choices. More folds mean more training data in every round (with 10 folds, 90 percent) and more rounds to wait for. With little data, 10 folds use it better; with a lot of data, 5 are enough. There is nothing magic in the numbers: they are habits that work well.\n",
    "\n",
    "### 5.5 Cross-validation in Python"
   ],
   "id": "t23-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.model_selection import cross_val_score\n",
    "\n",
    "X = df[[\"area\", \"rooms\", \"age\", \"floor\", \"distance_km\"]]\n",
    "y = df[\"price\"]\n",
    "\n",
    "model = LinearRegression()\n",
    "scores = cross_val_score(model, X, y, cv=5)\n",
    "\n",
    "print(scores.round(3))"
   ],
   "id": "t23-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The five scores have a mean and a spread:"
   ],
   "id": "t23-023"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(round(scores.mean(), 3))\n",
    "print(round(scores.std(), 3))"
   ],
   "id": "t23-024"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- `cross_val_score` gets the model (not yet trained), the features, the target and the number of folds, `cv=5`. It does the five rounds of splitting, training and testing by itself.\n",
    "- For a regression model the score is R². The result is an array with the five scores.\n",
    "- `scores.mean()` is the number to report: R² is about 0.947. `scores.std()` is the spread: 0.012 is small, so the model is stable.\n",
    "\n",
    "A report then reads: \"R² = 0.947 ± 0.012 in 5-fold cross-validation.\" That says more than \"0.952 on one test set\".\n",
    "\n",
    "### 5.6 What cross-validation shows about the three models"
   ],
   "id": "t23-025"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "good = cross_val_score(LinearRegression(), df[[\"area\", \"rooms\", \"age\", \"floor\", \"distance_km\"]], y, cv=5)\n",
    "weak = cross_val_score(LinearRegression(), df[[\"floor\"]], y, cv=5)\n",
    "few = cross_val_score(LinearRegression(), df.drop(columns=\"price\").iloc[:20], y.iloc[:20], cv=5)\n",
    "\n",
    "print(good.round(2), round(good.mean(), 3))\n",
    "print(weak.round(2), round(weak.mean(), 3))\n",
    "print(few.round(2), round(few.mean(), 3))"
   ],
   "id": "t23-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- The good model: five scores close together, with a high mean.\n",
    "- The model with only the floor: five scores close together, all bad. Stable, and stably wrong: underfitting.\n",
    "- All ten columns on only 20 flats: the scores jump from below zero to 0.6. In every round the model is trained on 16 flats and learns something different. That is overfitting, seen through cross-validation.\n",
    "\n",
    "### 5.7 Where cross-validation fits in the recipe\n",
    "\n",
    "Cross-validation is used to choose: which features, which model, which settings. The test data stays locked away during all of that, and is used once at the end for the final, honest number:"
   ],
   "id": "t23-027"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
    "\n",
    "model = LinearRegression()\n",
    "scores = cross_val_score(model, X_train, y_train, cv=5)\n",
    "\n",
    "print(round(scores.mean(), 3))"
   ],
   "id": "t23-028"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The cross-validation used the training data only. Now the model is trained on all of the training data and meets the test data for the first and only time:"
   ],
   "id": "t23-029"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model.fit(X_train, y_train)\n",
    "\n",
    "print(round(model.score(X_test, y_test), 3))"
   ],
   "id": "t23-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The cross-validation score, calculated on the training data only, already predicted what the test data then confirmed.\n",
    "\n",
    "## 6. The bias-variance tradeoff\n",
    "\n",
    "Underfitting and overfitting have a second pair of names, which explains why they happen. The error of a model on new data comes from two different sources.\n",
    "\n",
    "### 6.1 Bias\n",
    "\n",
    "Bias is the error of a model that is too simple for the data. Such a model makes a strong assumption (\"the price depends only on the floor\", \"the relationship is a straight line\"), and when the assumption is wrong, the model is wrong in the same way whatever rows it is trained on. More data does not help: the model keeps missing the pattern, steadily.\n",
    "\n",
    "High bias is underfitting.\n",
    "\n",
    "### 6.2 Variance\n",
    "\n",
    "Variance is how much a model changes when it is trained on other rows. A very flexible model with little data fits every accident of its training rows. Train it on another sample and you get a clearly different model with clearly different predictions. Each of these models fits its own rows well and new rows badly.\n",
    "\n",
    "High variance is overfitting.\n",
    "\n",
    "### 6.3 Four combinations\n",
    "\n",
    "Think of every dot as the result of training the model on one sample of data, and of the centre of the target as the truth:\n",
    "\n",
    "|  | Low variance | High variance |\n",
    "| --- | --- | --- |\n",
    "| Low bias | the goal: right on average, and steady | overfitting: right on average, but every single model is far off |\n",
    "| High bias | underfitting: steady, and steadily wrong | the worst case: wrong on average, and unsteady |\n",
    "\n",
    "### 6.4 Why it is a tradeoff\n",
    "\n",
    "The two errors pull in opposite directions.\n",
    "\n",
    "- A simple model (few features, a rigid shape) cannot follow the pattern closely: high bias. But it hardly changes from one sample to the next: low variance.\n",
    "- A flexible model (many features, a shape that bends easily) can follow the pattern: low bias. But it also follows the noise of its training rows: high variance.\n",
    "\n",
    "Making a model more flexible lowers the bias and raises the variance. Making it simpler does the opposite. The best model is in between: flexible enough to find the pattern, and not so flexible that it learns the noise.\n",
    "\n",
    "The picture is the most important one of the lesson. As a model becomes more flexible, its error on the training data keeps falling. Its error on the test data falls at first, reaches a lowest point, and then rises again: from there on, the model is learning noise. The gap between the two curves is what Part 3 taught you to read.\n",
    "\n",
    "### 6.5 What to do\n",
    "\n",
    "| The problem | How it shows | Why it happens | What helps |\n",
    "| --- | --- | --- | --- |\n",
    "| High bias (underfitting) | low training score, low test score | the model is too simple; the features do not carry the answer | add better features; use a more flexible model |\n",
    "| High variance (overfitting) | high training score, much lower test score; cross-validation scores far apart | too few rows for the number of features; a model that is too flexible; useless features | get more training rows; remove features; use a simpler model; regularization (Topic 26) |\n",
    "\n",
    "Two cures are often mixed up:\n",
    "\n",
    "- More data cures high variance, not high bias. With more rows, a flexible model has less room to follow accidents. A model that is too simple stays too simple.\n",
    "- More features cure high bias, and can cause high variance. Every feature gives the model more freedom. Useful features lower the bias; useless ones only add room for overfitting.\n",
    "\n",
    "## 7. Common mistakes\n",
    "\n",
    "| Mistake | Why it is wrong | Right |\n",
    "| --- | --- | --- |\n",
    "| Judging the model by its training score. | The training score is always flattering: the model was fitted to those rows. | Report the test score, or the cross-validation score. |\n",
    "| `model.fit(X, y)` with all rows, then `model.score(X_test, y_test)`. | The model has seen the test rows; the test is no longer honest. | `model.fit(X_train, y_train)` |\n",
    "| `model.fit(X_test, y_test)` | The test data is never used for training. | `fit` on the training data only. |\n",
    "| Mixing up the four results of the split. | The order is fixed: training features, test features, training target, test target. | `X_train, X_test, y_train, y_test = train_test_split(X, y, ...)` |\n",
    "| `r2_score(y_train, y_pred)` when `y_pred` was made from `X_test`. | The true answers and the predictions must belong to the same rows. | `r2_score(y_test, y_pred)` |\n",
    "| Leaving out `random_state`. | Every run gives another split and other numbers; results cannot be repeated or compared. | Set `random_state` to a fixed number. |\n",
    "| Trying many values of `random_state` and keeping the best score. | That is choosing the luckiest test set, not the best model. | Use cross-validation and report the mean. |\n",
    "| \"The training score is 0.99, so the model is excellent.\" | A very high training score with a much lower test score is overfitting. | Always look at both scores. |\n",
    "| \"The test score is lower than the training score, so the model overfits.\" | A small gap is normal. | Worry when the gap is large (about 0.1 or more for R²). |\n",
    "| Trying to cure underfitting with more rows. | A model that is too simple stays too simple. | Better features, or a more flexible model. |\n",
    "| Adding every available column as a feature. | Columns without information add nothing and give the model room to overfit. | Use the columns that can sensibly influence the target. |\n",
    "| Using the test data again and again to choose features and settings. | After many looks, the choices are fitted to the test data, and its score becomes flattering too. | Choose with cross-validation on the training data; use the test data once at the end. |\n",
    "\n",
    "## 8. Solved problems\n",
    "\n",
    "Six short problems, all in Python, all on `flats.csv`. Problems 2, 3 and 4 continue from the cell of Problem 1, and Problem 6 from Problem 5.\n",
    "\n",
    "Problem 1. X and y\n",
    "\n",
    "Read `flats.csv`. Take the area and the number of rooms as features and the price as the target. Print the shapes of `X` and `y`."
   ],
   "id": "t23-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"flats.csv\")\n",
    "\n",
    "X = df[[\"area\", \"rooms\"]]\n",
    "y = df[\"price\"]\n",
    "\n",
    "print(X.shape, y.shape)"
   ],
   "id": "t23-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `X` is a table: a list of column names in double brackets gives a DataFrame with 200 rows and 2 columns. `y` is one column: 200 values.\n",
    "\n",
    "Problem 2. A split of 80 to 20\n",
    "\n",
    "Split the `X` and `y` of Problem 1 into training and test data: 20 percent for testing, `random_state=42`. Print the four shapes."
   ],
   "id": "t23-033"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
    "\n",
    "print(X_train.shape, X_test.shape)\n",
    "print(y_train.shape, y_test.shape)"
   ],
   "id": "t23-034"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: 20 percent of 200 rows are 40 test rows, and 160 remain for training. The features and the target are cut in the same places: row 17 of `X_train` and row 17 of `y_train` belong to the same flat.\n",
    "\n",
    "Problem 3. Another size\n",
    "\n",
    "Split the same data so that 30 percent of the rows are test data, with `random_state=0`. Print how many rows each part has."
   ],
   "id": "t23-035"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)\n",
    "\n",
    "print(len(X_train), len(X_test))"
   ],
   "id": "t23-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `test_size=0.3` gives 60 test rows and 140 training rows. `len` of a table is its number of rows.\n",
    "\n",
    "Problem 4. The same split every time\n",
    "\n",
    "Split the data twice with `random_state=42` and once with `random_state=1`. Each time print the row numbers (the index) of the first five test flats."
   ],
   "id": "t23-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for state in [42, 42, 1]:\n",
    "    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=state)\n",
    "    print(state, X_test.index[:5].tolist())"
   ],
   "id": "t23-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the same `random_state` gives the same test flats, and another number gives others. The index shows that the rows were shuffled: the test data is not simply the end of the file.\n",
    "\n",
    "Problem 5. Train on one part, judge on the other\n",
    "\n",
    "Use the area, the rooms and the distance to the centre as features. Split 80 to 20 with `random_state=42`, train a linear regression on the training data, and print the training score and the test score."
   ],
   "id": "t23-039"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "df = pd.read_csv(\"flats.csv\")\n",
    "\n",
    "X = df[[\"area\", \"rooms\", \"distance_km\"]]\n",
    "y = df[\"price\"]\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
    "\n",
    "model = LinearRegression()\n",
    "model.fit(X_train, y_train)\n",
    "\n",
    "print(round(model.score(X_train, y_train), 3))\n",
    "print(round(model.score(X_test, y_test), 3))"
   ],
   "id": "t23-040"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the two scores are high and close together: a good fit, without overfitting. They are a little lower than with five features in Part 2, because the age and the floor carry information too.\n",
    "\n",
    "Problem 6. Five folds\n",
    "\n",
    "For the features of Problem 5, run a 5-fold cross-validation. Print the five scores and their mean."
   ],
   "id": "t23-041"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import cross_val_score\n",
    "\n",
    "scores = cross_val_score(LinearRegression(), X, y, cv=5)\n",
    "\n",
    "print(scores.round(3))\n",
    "print(round(scores.mean(), 3))"
   ],
   "id": "t23-042"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `cross_val_score` does the five splits itself, so no `train_test_split` is needed here. The five scores lie close together, and their mean is the number to report.\n",
    "\n",
    "## 11. Quick summary\n",
    "\n",
    "| Idea | In one sentence |\n",
    "| --- | --- |\n",
    "| Train/test split | Put a part of the rows aside before training, and judge the model on that part |\n",
    "| Test score | The score that counts: it estimates how the model does on new data |\n",
    "| Normal gap | The test score is a little lower than the training score; a few hundredths of R² are normal |\n",
    "| Overfitting | High training score, much lower test score: the model learned the rows, not the pattern |\n",
    "| Underfitting | Low score on both parts: the model is too simple or the features are too weak |\n",
    "| Cross-validation | Cut the data into k folds, test on each fold once, report the mean of the k scores |\n",
    "| Bias | The error of a model that is too simple: underfitting |\n",
    "| Variance | How much a model changes with its training rows: overfitting |\n",
    "| The tradeoff | More flexibility lowers the bias and raises the variance; the best model is in between |\n",
    "\n",
    "| Code | What it does |\n",
    "| --- | --- |\n",
    "| `train_test_split(X, y, test_size=0.2, random_state=42)` | returns `X_train, X_test, y_train, y_test` |\n",
    "| `model.fit(X_train, y_train)` | trains on the training data only |\n",
    "| `model.score(X_test, y_test)` | R² on the test data |\n",
    "| `y_pred = model.predict(X_test)` | the predictions for the test rows |\n",
    "| `r2_score(y_test, y_pred)` | R² |\n",
    "| `mean_squared_error(y_test, y_pred)` | MSE |\n",
    "| `root_mean_squared_error(y_test, y_pred)` | RMSE |\n",
    "| `cross_val_score(model, X, y, cv=5)` | the five scores of a 5-fold cross-validation |\n",
    "\n",
    "### Rules to keep\n",
    "\n",
    "1. Split first. `fit` sees the training data only.\n",
    "2. Report the test score, and compare it with the training score.\n",
    "3. A small gap is normal. A large gap is overfitting. Two low scores are underfitting.\n",
    "4. One split is one piece of luck. Cross-validation gives a steadier number.\n",
    "5. Underfitting: better features or a more flexible model. Overfitting: more rows, fewer features, a simpler model.\n",
    "6. The test data is used once, at the end.\n",
    "\n",
    "### What comes next\n",
    "\n",
    "In this lesson every column was already a number on a scale the model could use. Real tables are not so kind: an area in tens stands next to a price in thousands. Topic 24, feature engineering with the scaling of numerical values, brings features to the same scale, and it will use the split of this lesson from its first example on.\n",
    "\n",
    "Next: the practice notebook (topic-23-practice.ipynb), then Topic 24: Feature engineering: scaling numerical values."
   ],
   "id": "t23-043"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
