{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 26: Regularization: Ridge and Lasso regression\n",
    "\n",
    "Asiman Data School, Module 3: Comprehensive Machine Learning. Week 13, 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. The practice problems are in a separate notebook, topic-26-practice.ipynb.\n",
    "\n",
    "The cells continue from each other: a cell uses the variables of the cells above it. Parts 3 to 7 are one project, so start at the first cell of Part 3. The solved problems 4 to 14 are a second project that starts again from reading the file.\n",
    "\n",
    "This notebook reads the file Housing.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 regularization?\n",
    "2. Three penalties: Ridge, Lasso, elastic net\n",
    "3. The project: the data and its preparation\n",
    "4. A first model, without regularization\n",
    "5. Ridge, Lasso and elastic net on the housing data\n",
    "6. Choosing alpha with cross-validation\n",
    "7. When regularization really matters: many features\n",
    "8. The workflow, step by step\n",
    "9. Common mistakes\n",
    "10. Solved problems\n",
    "11. Practice (in topic-26-practice.ipynb)\n",
    "12. Check yourself (on the website)\n",
    "13. Summary"
   ],
   "id": "t26-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction: keeping the weights small\n",
    "\n",
    "What matters most in this lesson. Five things matter most today. First, the idea: regularization adds a penalty for large weights to the loss, so the model gives up a little fit on the training data and becomes steadier on new data. Second, the three kinds: Ridge (the sum of the squared weights) makes all weights small, Lasso (the sum of the absolute weights) sets some of them to exactly 0, and the elastic net mixes both. Third, two rules: scale the features first, and choose the strength alpha with cross-validation on the training data. Fourth, the order of a real project: look, check, encode, split, scale, a first model, then improve and tune. Fifth, an honest result: regularization cures overfitting, so it changes little for a model that does not overfit and a great deal for a model with many features.\n",
    "\n",
    "The sixth lesson of Module 3. In Topic 23 you met overfitting: a model that follows its training rows so closely that it does worse on new rows. The cures named there were more rows, fewer features or a simpler model. This lesson adds a fourth cure, and the most widely used one: regularization. The model keeps all its features, but it is trained with a rule that keeps its weights small.\n",
    "\n",
    "The lesson has two halves. The first explains the idea and the three kinds of regularization for linear models: Ridge, Lasso and elastic net, with their formulas and the logic behind them. The second half is a complete machine learning project on a real data file, `Housing.csv`: every step from reading the file to comparing the models, in the order in which it is done in practice. It uses everything of Topics 22 to 25.\n",
    "\n",
    "You need: linear regression, its weights and its loss (Topic 22), the train/test split, overfitting and cross-validation (Topic 23), scaling (Topic 24), outliers and encoding (Topic 25).\n",
    "\n",
    "| Word | Meaning |\n",
    "| --- | --- |\n",
    "| regularization | training with a penalty for large weights, to keep the model simple |\n",
    "| penalty | the extra term that is added to the loss |\n",
    "| Ridge regression | linear regression with the L2 penalty: the sum of the squared weights |\n",
    "| Lasso regression | linear regression with the L1 penalty: the sum of the absolute weights |\n",
    "| elastic net | linear regression with a mix of both penalties |\n",
    "| `alpha` | the strength of the penalty: 0 is no regularization, a large value is a strong one |\n",
    "| `l1_ratio` | in an elastic net: the share of the L1 penalty in the mix |\n",
    "| shrinking | weights moving towards 0 under a penalty |\n",
    "| sparse model | a model in which many weights are exactly 0 |\n",
    "| hyperparameter | a number that you choose before training, such as `alpha` (Topic 21) |\n",
    "\n",
    "## 1. Why regularization?\n",
    "\n",
    "### 1.1 Overfitting, seen in the weights\n",
    "\n",
    "A linear regression chooses the weights that make the error on the training data as small as possible. Nothing else counts. When the model has many features and not many rows, it uses its freedom to follow the accidents of the training rows, and it often does so with very large weights: one feature gets a huge positive weight, another a huge negative one, and the two almost cancel each other. On the training rows the result fits beautifully. On new rows a small change in a feature is multiplied by a huge weight, and the prediction jumps.\n",
    "\n",
    "Large weights are therefore a sign of a model that trusts its training data too much. Part 7 will show a model on the housing data whose largest weight is many times as large as it should be, and whose test score is negative.\n",
    "\n",
    "### 1.2 The idea: make large weights cost something\n",
    "\n",
    "Regularization changes what the training is asked to do. The loss gets a second term:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{loss} = {} & \\text{error on the training data} \\\\\n",
    "& + \\text{penalty for large weights}\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Now the model must balance two wishes. A large weight is still allowed, but only if it reduces the error by more than it costs. A weight that only follows noise is not worth its price and stays small.\n",
    "\n",
    "- The error pulls the weights towards the values that fit the training data best.\n",
    "- The penalty pulls every weight towards 0.\n",
    "- A number called alpha says how strong the penalty is.\n",
    "\n",
    "The model that comes out fits the training data a little worse than plain linear regression. That is intended. It gives up a little of the training score to become steadier on new data: less variance for a little more bias, the tradeoff of Topic 23.\n",
    "\n",
    "### 1.3 What regularization is not\n",
    "\n",
    "- It does not add data and it does not remove columns from the table.\n",
    "- It does not make a weak model strong. If the features carry little information, no penalty will find more.\n",
    "- It is not always needed. A model with few features and many rows hardly overfits, and then there is little to gain. The project of this lesson will show that honestly.\n",
    "\n",
    "## 2. Three penalties: Ridge, Lasso, elastic net\n",
    "\n",
    "The three methods differ only in how they measure \"large weights\". The model itself is the same in all of them: $\\hat{y} = w_0 + w_1 x_1 + \\dots + w_p x_p$, with $p$ features. The intercept $w_0$ is never penalised. In the formulas the strength of the penalty is written $\\alpha$, the Greek letter alpha; in code it is `alpha`.\n",
    "\n",
    "### 2.1 Plain linear regression\n",
    "\n",
    "$$\n",
    "\\text{loss} = \\text{MSE}\n",
    "$$\n",
    "\n",
    "The mean squared error of Topic 22, and nothing else.\n",
    "\n",
    "### 2.2 Ridge regression: the L2 penalty\n",
    "\n",
    "$$\n",
    "\\text{loss} = \\text{MSE} + \\alpha \\left( w_1^2 + w_2^2 + \\dots + w_p^2 \\right)\n",
    "$$\n",
    "\n",
    "The penalty is the sum of the squared weights. It is called the L2 penalty, after the L2 norm of Topic 15.\n",
    "\n",
    "The logic: squaring makes a large weight very expensive and a small weight almost free. A weight of 10 costs 100; a weight of 1 costs 1; a weight of 0.1 costs 0.01. So Ridge attacks the large weights first and pushes all weights to be small and of similar size. But the cost of a small weight is so tiny that pushing it all the way to 0 is never worth it: Ridge makes weights small, never exactly zero. All features stay in the model.\n",
    "\n",
    "### 2.3 Lasso regression: the L1 penalty\n",
    "\n",
    "$$\n",
    "\\text{loss} = \\text{MSE} + \\alpha \\left( \\lvert w_1 \\rvert + \\lvert w_2 \\rvert + \\dots + \\lvert w_p \\rvert \\right)\n",
    "$$\n",
    "\n",
    "The penalty is the sum of the absolute values of the weights: the L1 penalty, after the L1 norm of Topic 15. \"Lasso\" is short for \"least absolute shrinkage and selection operator\".\n",
    "\n",
    "The logic: without the square, every step towards 0 saves the same amount, whether the weight is large or small. A weight of 10 costs 10, a weight of 0.1 costs 0.1, and reducing either of them by 0.1 saves exactly 0.1. So for a feature that helps only a little, the saving is larger than the loss all the way down, and the weight ends at exactly 0. The feature has left the model. Lasso selects features: it does feature selection (Topic 24) by itself, during training.\n",
    "\n",
    "### 2.4 Elastic net: both together\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{loss} = \\text{MSE} + \\alpha \\Big[ \\, & r \\left( \\lvert w_1 \\rvert + \\dots + \\lvert w_p \\rvert \\right) \\\\\n",
    "& + (1 - r) \\left( w_1^2 + \\dots + w_p^2 \\right) \\Big]\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "A mix of the two penalties. The number $r$, called `l1_ratio` in scikit-learn, says how much of the mix is L1:\n",
    "\n",
    "- $r = 1$: only the L1 penalty. The model is a Lasso.\n",
    "- $r = 0$: only the L2 penalty. The model is a Ridge.\n",
    "- $r = 0.5$: half and half.\n",
    "\n",
    "The logic: Lasso has a weakness. When several features are strongly correlated with each other (the multicollinearity of Topic 24), it keeps one of them almost at random and drops the others. Ridge handles such groups well: it gives the correlated features similar weights. The elastic net takes feature selection from Lasso and the steady handling of correlated features from Ridge.\n",
    "\n",
    "(scikit-learn writes these losses with a few fixed factors, for example one half in front of the L2 part of the elastic net, and Ridge uses the sum of the squared errors in the place of their mean. The logic is the same. One consequence matters in practice: the alpha of Ridge and the alpha of Lasso are on different scales and cannot be compared. A usual alpha for Ridge is 1, 10 or 100; a usual alpha for Lasso is 0.01 or 0.1.)\n",
    "\n",
    "### 2.5 The penalties by hand\n",
    "\n",
    "Two models for the same data, each with two weights:\n",
    "\n",
    "|  | Weights | MSE on the training data |\n",
    "| --- | --- | --- |\n",
    "| Model A | 6 and $-8$ | 4.0 |\n",
    "| Model B | 3 and $-2$ | 4.6 |\n",
    "\n",
    "Without a penalty, Model A wins: its error is smaller. Now the two penalties:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\textbf{Model A}\\quad & \\text{L2: } 6^2 + (-8)^2 = 36 + 64 = 100 \\\\[2pt]\n",
    "& \\text{L1: } \\lvert 6 \\rvert + \\lvert -8 \\rvert = 14 \\\\[10pt]\n",
    "\\textbf{Model B}\\quad & \\text{L2: } 3^2 + (-2)^2 = 9 + 4 = 13 \\\\[2pt]\n",
    "& \\text{L1: } \\lvert 3 \\rvert + \\lvert -2 \\rvert = 5\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "The Ridge loss with $\\alpha = 0.1$:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{Model A:}\\quad & 4.0 + 0.1 \\times 100 = 4.0 + 10 = 14.0 \\\\[4pt]\n",
    "\\text{Model B:}\\quad & 4.6 + 0.1 \\times 13 = 4.6 + 1.3 = 5.9\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Model B wins clearly. Its error is a little larger, but its weights are much smaller. The Lasso loss with $\\alpha = 0.1$:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{Model A:}\\quad & 4.0 + 0.1 \\times 14 = 4.0 + 1.4 = 5.4 \\\\[4pt]\n",
    "\\text{Model B:}\\quad & 4.6 + 0.1 \\times 5 = 4.6 + 0.5 = 5.1\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Model B wins here too, by less. The elastic net loss with $\\alpha = 0.1$ and $r = 0.5$ takes half of each penalty:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{Model A:}\\quad & 4.0 + 0.1 \\times (0.5 \\times 14 + 0.5 \\times 100) \\\\\n",
    "& = 4.0 + 5.7 = 9.7 \\\\[6pt]\n",
    "\\text{Model B:}\\quad & 4.6 + 0.1 \\times (0.5 \\times 5 + 0.5 \\times 13) \\\\\n",
    "& = 4.6 + 0.9 = 5.5\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Model B wins again, and the two losses lie between those of Lasso and Ridge, as the penalty itself does. And with a very weak penalty, $\\alpha = 0.001$, in the Ridge loss:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{Model A:}\\quad & 4.0 + 0.001 \\times 100 = 4.1 \\\\[4pt]\n",
    "\\text{Model B:}\\quad & 4.6 + 0.001 \\times 13 = 4.613\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Model A wins again: the penalty is too weak to matter. Alpha decides how much the size of the weights counts against the error.\n",
    "\n",
    "### 2.6 Why Ridge shrinks and Lasso cuts\n",
    "\n",
    "In the simplest case, one feature that is scaled and stands alone, the effect of each penalty on a weight can be written in one line. Let $w$ be the weight that plain linear regression would choose.\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{Ridge:}\\quad & w_{\\text{new}} = \\frac{w}{1 + \\alpha} \\\\[10pt]\n",
    "\\text{Lasso:}\\quad & w_{\\text{new}} = w - \\alpha \\quad \\text{when } w \\text{ is larger than } \\alpha \\\\[4pt]\n",
    "& w_{\\text{new}} = 0 \\quad \\text{when } w \\text{ is smaller than } \\alpha\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Ridge divides. Lasso subtracts. Take two weights, 4 and 0.5, and $\\alpha = 1$:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{Ridge:}\\quad & \\frac{4}{1 + 1} = 2 \\qquad \\frac{0.5}{1 + 1} = 0.25 \\\\[10pt]\n",
    "\\text{Lasso:}\\quad & 4 - 1 = 3 \\\\[4pt]\n",
    "& 0.5 - 1 \\text{ is below } 0 \\text{, so the weight is } 0\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Dividing makes every weight smaller by the same share, and a number that is divided never becomes 0. Subtracting takes the same amount from every weight, and a weight that is smaller than this amount is gone. That is the whole difference between the two methods.\n",
    "\n",
    "### 2.7 The picture with the circle and the diamond\n",
    "\n",
    "There is a second way to see it. A penalty is the same as a budget: the weights may be anything, as long as their penalty stays below a limit. For two weights, the budget of Ridge ($w_1^2 + w_2^2$ below a limit) is a circle, and the budget of Lasso ($\\lvert w_1 \\rvert + \\lvert w_2 \\rvert$ below a limit) is a diamond with its corners on the axes.\n",
    "\n",
    "The ovals in the picture are the error: the dot in their middle is where plain linear regression would put the weights, and every oval further out is a larger error. The model takes the point of its budget that touches the smallest oval.\n",
    "\n",
    "A circle is round everywhere, so the oval touches it at some ordinary point where both weights are small and neither is 0. A diamond has corners, and the corners stick out: the oval very often touches a corner first. At a corner one of the weights is exactly 0. With many features the diamond has many corners and edges, and many weights become 0.\n",
    "\n",
    "### 2.8 Side by side\n",
    "\n",
    "|  | Linear regression | Ridge | Lasso | Elastic net |\n",
    "| --- | --- | --- | --- | --- |\n",
    "| Penalty | none | squared weights (L2) | absolute weights (L1) | a mix of both |\n",
    "| What happens to the weights | free | all become smaller | some become exactly 0 | smaller, and some 0 |\n",
    "| Selects features | no | no | yes | yes |\n",
    "| Correlated features | unstable weights | shares the weight among them | keeps one, drops the others | keeps groups together |\n",
    "| Numbers to choose | none | `alpha` | `alpha` | `alpha` and `l1_ratio` |\n",
    "| In scikit-learn | `LinearRegression()` | `Ridge(alpha=1.0)` | `Lasso(alpha=1.0)` | `ElasticNet(alpha=1.0, l1_ratio=0.5)` |\n",
    "\n",
    "### 2.9 When to use which\n",
    "\n",
    "- Ridge: the usual first choice. Use it when you believe that most features carry some information, and when features are correlated with each other.\n",
    "- Lasso: when you believe that only some of many features matter, or when you want a short model that is easy to explain: the features with a weight of 0 can be left out.\n",
    "- Elastic net: when there are many features and groups of correlated ones, or when Lasso behaves unsteadily. It costs a second number to tune.\n",
    "- Plain linear regression: when there are few features and many rows, and the training and the test score are close together. Then there is nothing to cure.\n",
    "\n",
    "### 2.10 Two rules before any code\n",
    "\n",
    "1. Scale the features first. The penalty looks at the size of the weights, and the size of a weight depends on the unit of its feature (Topic 24). A feature in square feet has a tiny weight and would hardly be penalised; the same feature in thousands of square feet has a large weight and would be punished hard. Only after scaling does the penalty treat all features alike. For plain linear regression scaling was optional; for regularization it is required.\n",
    "\n",
    "2. Alpha is chosen, not learned. The weights are learned from the data. Alpha is a hyperparameter (Topic 21): you set it before training. The right value is found by trying several values and comparing them with cross-validation on the training data (Topic 23). The test data is not used for this choice.\n",
    "\n",
    "## 3. The project: the data and its preparation\n",
    "\n",
    "From here on the lesson is one project, in the order of real work: look at the data, clean it, encode it, split it, scale it, train a first model, then improve it. Every code block is a cell that continues from the cells above it, like a notebook.\n",
    "\n",
    "The task: predict the price of a house.\n",
    "\n",
    "### 3.1 Step 1: read the file and look at it\n",
    "\n",
    "`Housing.csv` is a public data set of 545 houses."
   ],
   "id": "t26-001"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"Housing.csv\")\n",
    "\n",
    "print(df.shape)\n",
    "print(df.head(3).T)"
   ],
   "id": "t26-002"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| Column | Meaning |\n",
    "| --- | --- |\n",
    "| `price` | the price of the house: the target |\n",
    "| `area` | the area of the house |\n",
    "| `bedrooms` | the number of bedrooms |\n",
    "| `bathrooms` | the number of bathrooms |\n",
    "| `stories` | the number of floors |\n",
    "| `mainroad` | is the house on a main road? `yes` or `no` |\n",
    "| `guestroom` | does it have a guest room? |\n",
    "| `basement` | does it have a basement? |\n",
    "| `hotwaterheating` | does it have hot water heating? |\n",
    "| `airconditioning` | does it have air conditioning? |\n",
    "| `parking` | the number of parking places |\n",
    "| `prefarea` | is it in a preferred area of the town? |\n",
    "| `furnishingstatus` | `furnished`, `semi-furnished` or `unfurnished` |\n",
    "\n",
    "### 3.2 Step 2: check the columns\n",
    "\n",
    "Are there missing values or repeated rows (Topic 11)? Which columns are text?"
   ],
   "id": "t26-003"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.isna().sum().sum())\n",
    "print(df.duplicated().sum())\n",
    "print(df.select_dtypes(exclude=\"number\").columns.tolist())"
   ],
   "id": "t26-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "No missing value and no repeated row. Seven columns are text and must be encoded.\n",
    "\n",
    "Are there columns without information (Topic 24)? There is no identification number, no name and no constant column here: every column describes the house. Nothing is dropped.\n",
    "\n",
    "### 3.3 Step 3: look for outliers"
   ],
   "id": "t26-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df[[\"price\", \"area\"]].describe().round(0))"
   ],
   "id": "t26-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The two columns with continuous measurements are the price and the area (Topic 25). The IQR rule on both:"
   ],
   "id": "t26-007"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for name in [\"price\", \"area\"]:\n",
    "    q1 = df[name].quantile(0.25)\n",
    "    q3 = df[name].quantile(0.75)\n",
    "    upper = q3 + 1.5 * (q3 - q1)\n",
    "    print(name, upper, (df[name] > upper).sum())"
   ],
   "id": "t26-008"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The rule marks 15 prices and 12 areas. Now the question of Topic 25: mistakes, or real extreme values? The largest house has 16,200 units of area, about three times the typical house, and the most expensive one costs 13.3 million, about three times the median. Nothing is impossible here, and nothing looks like a typing mistake. These are simply the largest and most expensive houses of the town: real values, so they stay.\n",
    "\n",
    "### 3.4 Step 4: a target in handy numbers\n",
    "\n",
    "The prices are numbers in the millions. That is no problem for the score, but it makes every weight and every error a number with seven digits, and it matters for Lasso, whose alpha is compared with the size of the target. So the price is turned into millions:"
   ],
   "id": "t26-009"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df[\"price\"] = df[\"price\"] / 1000000\n",
    "\n",
    "print(df[\"price\"].describe().round(2))"
   ],
   "id": "t26-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A house now costs between 1.75 and 13.3 (million). This is only a change of unit: it uses no information from other rows, so it is done before the split.\n",
    "\n",
    "### 3.5 Step 5: encode the text columns\n",
    "\n",
    "Six columns have the values `yes` and `no`. Each becomes 1 and 0 (Topic 25), in one loop:"
   ],
   "id": "t26-011"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "yes_no = [\"mainroad\", \"guestroom\", \"basement\", \"hotwaterheating\", \"airconditioning\", \"prefarea\"]\n",
    "\n",
    "for name in yes_no:\n",
    "    df[name] = df[name].map({\"no\": 0, \"yes\": 1})\n",
    "\n",
    "print(df[yes_no].head(3))"
   ],
   "id": "t26-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The seventh text column has three values:"
   ],
   "id": "t26-013"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df[\"furnishingstatus\"].value_counts())"
   ],
   "id": "t26-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Unfurnished, semi-furnished, furnished: these have an order, so the column gets ordinal encoding with numbers in that order:"
   ],
   "id": "t26-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df[\"furnishingstatus\"] = df[\"furnishingstatus\"].map({\"unfurnished\": 0, \"semi-furnished\": 1, \"furnished\": 2})\n",
    "\n",
    "print(df[\"furnishingstatus\"].value_counts().sort_index())"
   ],
   "id": "t26-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every column is a number now.\n",
    "\n",
    "### 3.6 Step 6: a look at the correlations"
   ],
   "id": "t26-017"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.corr()[\"price\"].round(2).sort_values())"
   ],
   "id": "t26-018"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every feature moves with the price in the expected direction. The area and the number of bathrooms are the strongest; `hotwaterheating` is the weakest. In Topic 24 the weakest feature would now be a candidate for dropping. Here all twelve stay, on purpose: Part 5 will let Lasso decide which features are worth keeping.\n",
    "\n",
    "### 3.7 Step 7: split\n",
    "\n",
    "Change it and run: change `test_size` to `0.3` and run: 164 houses become test data."
   ],
   "id": "t26-019"
  },
  {
   "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",
    "\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)"
   ],
   "id": "t26-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`df.drop(columns=[\"price\"])` is the table without the target: all twelve features.\n",
    "\n",
    "### 3.8 Step 8: scale\n",
    "\n",
    "The scaler is fitted on the training data and applied to both parts (Topic 24). For the models of this lesson this step is not optional."
   ],
   "id": "t26-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "scaler = StandardScaler()\n",
    "X_train_scaled = scaler.fit_transform(X_train)\n",
    "X_test_scaled = scaler.transform(X_test)\n",
    "\n",
    "print(X_train_scaled[:2].round(2))"
   ],
   "id": "t26-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The data is ready: 436 houses for training, 109 for the test, twelve features on the same scale.\n",
    "\n",
    "## 4. A first model, without regularization\n",
    "\n",
    "Every project needs a starting point. Here it is plain linear regression."
   ],
   "id": "t26-023"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import LinearRegression\n",
    "\n",
    "linear = LinearRegression()\n",
    "linear.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(linear.score(X_train_scaled, y_train), 3))\n",
    "print(round(linear.score(X_test_scaled, y_test), 3))"
   ],
   "id": "t26-024"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A training score of 0.685 and a test score of 0.649. Read them as in Topic 23: the gap is small (less than 0.04), so this model does not overfit much. The scores are moderate because the twelve columns do not tell everything about a house, not because the model memorised its rows. Keep that in mind: regularization cures overfitting, and there is little of it here.\n",
    "\n",
    "The weights:"
   ],
   "id": "t26-025"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for name, weight in zip(X.columns, linear.coef_):\n",
    "    print(name, round(weight, 3))"
   ],
   "id": "t26-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The features are standardised, so the weights can be compared (Topic 24): one standard deviation more area adds about 0.52 million to the price, and the area, the bathrooms, the air conditioning and the number of floors matter most. All weights are of a reasonable size. No weight is huge.\n",
    "\n",
    "## 5. Ridge, Lasso and elastic net on the housing data\n",
    "\n",
    "### 5.1 Ridge\n",
    "\n",
    "`Ridge` is used exactly like `LinearRegression`. The strength of the penalty is `alpha`.\n",
    "\n",
    "Change it and run: change `10` to `500` and run: both scores fall, because the penalty is now too strong."
   ],
   "id": "t26-027"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import Ridge\n",
    "\n",
    "ridge = Ridge(alpha=10)\n",
    "ridge.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(ridge.score(X_train_scaled, y_train), 3))\n",
    "print(round(ridge.score(X_test_scaled, y_test), 3))"
   ],
   "id": "t26-028"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Almost the same scores as the plain model. Now several strengths, to see what alpha does. Every line shows alpha, the training score and the test score:"
   ],
   "id": "t26-029"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for alpha in [0.1, 1, 10, 100, 1000]:\n",
    "    model = Ridge(alpha=alpha)\n",
    "    model.fit(X_train_scaled, y_train)\n",
    "    print(alpha, round(model.score(X_train_scaled, y_train), 3), round(model.score(X_test_scaled, y_test), 3))"
   ],
   "id": "t26-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- With a small alpha (0.1, 1, 10) the model is practically the plain linear regression.\n",
    "- With $\\alpha = 100$ both scores begin to fall.\n",
    "- With $\\alpha = 1000$ the penalty is so strong that the model can no longer follow the data: both scores are low. This is underfitting (Topic 23), made by too much regularization.\n",
    "\n",
    "Alpha is a dial between two mistakes: too small and the model is free to overfit, too large and it is not allowed to learn.\n",
    "\n",
    "What the strong penalty did to the weights, next to the plain model:"
   ],
   "id": "t26-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "strong = Ridge(alpha=1000)\n",
    "strong.fit(X_train_scaled, y_train)\n",
    "\n",
    "for name, a, b in zip(X.columns, linear.coef_, strong.coef_):\n",
    "    print(name, round(a, 3), round(b, 3))"
   ],
   "id": "t26-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The first number of every line is the weight of the plain model, the second the weight under the strong penalty. The large weights shrank most: the area from 0.519 to 0.212, the bathrooms from 0.523 to 0.212. One weight even grew, `bedrooms`: the number of bedrooms moves together with the area and the bathrooms, and Ridge shares the weight among features that belong together (Part 2). And no weight is 0. That is Ridge: it makes the weights small and similar, and it keeps every feature.\n",
    "\n",
    "### 5.2 Lasso"
   ],
   "id": "t26-033"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import Lasso\n",
    "\n",
    "lasso = Lasso(alpha=0.05)\n",
    "lasso.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(lasso.score(X_train_scaled, y_train), 3))\n",
    "print(round(lasso.score(X_test_scaled, y_test), 3))"
   ],
   "id": "t26-034"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The alpha of Lasso is on another scale than the alpha of Ridge (Part 2): here 0.05 is already a noticeable penalty. Several strengths, this time with a fourth number: how many weights are not 0."
   ],
   "id": "t26-035"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for alpha in [0.001, 0.01, 0.05, 0.1, 0.3]:\n",
    "    model = Lasso(alpha=alpha)\n",
    "    model.fit(X_train_scaled, y_train)\n",
    "    kept = (model.coef_ != 0).sum()\n",
    "    print(alpha, round(model.score(X_train_scaled, y_train), 3), round(model.score(X_test_scaled, y_test), 3), kept)"
   ],
   "id": "t26-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`model.coef_ != 0` is `True` for every weight that is not 0, and `sum()` counts them. Up to $\\alpha = 0.1$ all twelve features stay. With $\\alpha = 0.3$ only seven are left. Which ones?\n",
    "\n",
    "Change it and run: change `0.3` to `0.5` and run: more weights are 0."
   ],
   "id": "t26-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "strong = Lasso(alpha=0.3)\n",
    "strong.fit(X_train_scaled, y_train)\n",
    "\n",
    "for name, weight in zip(X.columns, strong.coef_):\n",
    "    print(name, round(weight, 3))"
   ],
   "id": "t26-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Five weights are exactly 0: `bedrooms`, `mainroad`, `guestroom`, `basement` and `hotwaterheating`. Lasso has thrown them out of the model, and it kept the seven it found most useful. That is feature selection done by the training itself.\n",
    "\n",
    "Look at the price, though: with $\\alpha = 0.3$ the test score fell to 0.47. On this data the five features were not useless. Each carried a little information, and removing them costs. Lasso can select features; whether the shorter model is good enough is still judged by the score.\n",
    "\n",
    "### 5.3 Elastic net\n",
    "\n",
    "`ElasticNet` has two numbers: `alpha`, the strength, and `l1_ratio`, the share of the L1 penalty.\n",
    "\n",
    "Change it and run: set `l1_ratio=1` and run: the scores are those of `Lasso(alpha=0.05)`."
   ],
   "id": "t26-039"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import ElasticNet\n",
    "\n",
    "elastic = ElasticNet(alpha=0.05, l1_ratio=0.5)\n",
    "elastic.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(elastic.score(X_train_scaled, y_train), 3))\n",
    "print(round(elastic.score(X_test_scaled, y_test), 3))"
   ],
   "id": "t26-040"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With a strong penalty, $\\alpha = 0.3$, the mix shows its two sides. Every line shows `l1_ratio`, the test score and the number of weights that are not 0:"
   ],
   "id": "t26-041"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for ratio in [0.1, 0.5, 0.9]:\n",
    "    model = ElasticNet(alpha=0.3, l1_ratio=ratio)\n",
    "    model.fit(X_train_scaled, y_train)\n",
    "    print(ratio, round(model.score(X_test_scaled, y_test), 3), (model.coef_ != 0).sum())"
   ],
   "id": "t26-042"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The closer `l1_ratio` is to 1, the more the model behaves like a Lasso: more weights become 0. Close to 0 it behaves like a Ridge and keeps them all.\n",
    "\n",
    "## 6. Choosing alpha with cross-validation\n",
    "\n",
    "The loops above printed test scores to show what alpha does. For choosing alpha they must not be used: the test data would then take part in building the model (Topic 23). The choice is made with cross-validation on the training data.\n",
    "\n",
    "For every alpha, `cross_val_score` trains the model five times on four fifths of the training data and judges it on the remaining fifth. The mean of the five scores is the judgement of that alpha."
   ],
   "id": "t26-043"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import cross_val_score\n",
    "\n",
    "for alpha in [0.1, 1, 10, 100, 1000]:\n",
    "    scores = cross_val_score(Ridge(alpha=alpha), X_train_scaled, y_train, cv=5)\n",
    "    print(alpha, round(scores.mean(), 3))"
   ],
   "id": "t26-044"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The best mean belongs to $\\alpha = 10$, by a hair. The same for Lasso:"
   ],
   "id": "t26-045"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for alpha in [0.001, 0.01, 0.05, 0.1, 0.3]:\n",
    "    scores = cross_val_score(Lasso(alpha=alpha), X_train_scaled, y_train, cv=5)\n",
    "    print(alpha, round(scores.mean(), 3))"
   ],
   "id": "t26-046"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The two smallest values share the best score; $\\alpha = 0.01$ is taken. And for the elastic net, with `l1_ratio=0.5`:"
   ],
   "id": "t26-047"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for alpha in [0.001, 0.01, 0.05, 0.1, 0.3]:\n",
    "    scores = cross_val_score(ElasticNet(alpha=alpha, l1_ratio=0.5), X_train_scaled, y_train, cv=5)\n",
    "    print(alpha, round(scores.mean(), 3))"
   ],
   "id": "t26-048"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here $\\alpha = 0.05$ is the best.\n",
    "\n",
    "(scikit-learn has ready tools that run such a loop for you: `RidgeCV`, `LassoCV` and `ElasticNetCV`. They do what these cells do.)\n",
    "\n",
    "### 6.1 The four models side by side\n",
    "\n",
    "Now, and only now, the test data is used: once for each finished model."
   ],
   "id": "t26-049"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "models = {\n",
    "    \"linear\": LinearRegression(),\n",
    "    \"ridge\": Ridge(alpha=10),\n",
    "    \"lasso\": Lasso(alpha=0.01),\n",
    "    \"elastic net\": ElasticNet(alpha=0.05, l1_ratio=0.5),\n",
    "}\n",
    "\n",
    "for name, model in models.items():\n",
    "    model.fit(X_train_scaled, y_train)\n",
    "    print(name, round(model.score(X_train_scaled, y_train), 3), round(model.score(X_test_scaled, y_test), 3))"
   ],
   "id": "t26-050"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A dictionary holds the four models under their names, and the loop trains and judges one after the other (Topic 5).\n",
    "\n",
    "| Model | Training score | Test score |\n",
    "| --- | --- | --- |\n",
    "| linear regression | 0.685 | 0.649 |\n",
    "| Ridge, $\\alpha = 10$ | 0.685 | 0.648 |\n",
    "| Lasso, $\\alpha = 0.01$ | 0.685 | 0.646 |\n",
    "| elastic net, $\\alpha = 0.05$ | 0.684 | 0.638 |\n",
    "\n",
    "Four models, practically one score. This is an honest and important result. The plain model was not overfitting, so there was nothing for regularization to cure. Twelve features and 436 training rows leave a linear model little room to memorise. Regularization is a medicine for a particular illness, and a healthy model does not get better from it. A small loss, as with the elastic net here, is normal: the penalty takes away a little of the fit.\n",
    "\n",
    "So when does it help? When the model has much more freedom than the data can support. Part 7 builds such a model from the same houses.\n",
    "\n",
    "## 7. When regularization really matters: many features\n",
    "\n",
    "### 7.1 Giving the model more freedom\n",
    "\n",
    "A linear model cannot multiply two features (Topic 24). Perhaps a large area is worth more in a preferred part of the town, or air conditioning matters more in a house with many floors. Such products of two features can be created by hand, or all at once with `PolynomialFeatures`. With `degree=2` it creates, from twelve features, every feature, every square of a feature and every product of two features:"
   ],
   "id": "t26-051"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import PolynomialFeatures\n",
    "\n",
    "maker = PolynomialFeatures(degree=2, include_bias=False)\n",
    "X_train_many = maker.fit_transform(X_train)\n",
    "X_test_many = maker.transform(X_test)\n",
    "\n",
    "print(X_train_many.shape, X_test_many.shape)"
   ],
   "id": "t26-052"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Ninety features in the place of twelve, for the same 436 houses. (`include_bias=False` leaves out a column of ones that the model does not need.) The new features are scaled like the old ones:"
   ],
   "id": "t26-053"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "scaler_many = StandardScaler()\n",
    "X_train_many = scaler_many.fit_transform(X_train_many)\n",
    "X_test_many = scaler_many.transform(X_test_many)\n",
    "\n",
    "linear_many = LinearRegression()\n",
    "linear_many.fit(X_train_many, y_train)\n",
    "\n",
    "print(round(linear_many.score(X_train_many, y_train), 3))\n",
    "print(round(linear_many.score(X_test_many, y_test), 3))"
   ],
   "id": "t26-054"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The training score jumped from 0.685 to 0.790, and the test score did not move: 0.650. The gap is now 0.14. The model used its seventy-eight new features to follow the training rows, and nothing of that carried over to new houses. This is overfitting, and now there is something to cure.\n",
    "\n",
    "### 7.2 The three regularized models on ninety features\n",
    "\n",
    "Every line: the name, the training score, the test score and the number of weights that are not 0."
   ],
   "id": "t26-055"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "models = {\n",
    "    \"linear\": LinearRegression(),\n",
    "    \"ridge\": Ridge(alpha=100),\n",
    "    \"lasso\": Lasso(alpha=0.05),\n",
    "    \"elastic net\": ElasticNet(alpha=0.1, l1_ratio=0.5),\n",
    "}\n",
    "\n",
    "for name, model in models.items():\n",
    "    model.fit(X_train_many, y_train)\n",
    "    kept = (model.coef_ != 0).sum()\n",
    "    print(name, round(model.score(X_train_many, y_train), 3), round(model.score(X_test_many, y_test), 3), kept)"
   ],
   "id": "t26-056"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| Model on 90 features | Training score | Test score | Features kept |\n",
    "| --- | --- | --- | --- |\n",
    "| linear regression | 0.790 | 0.650 | 90 |\n",
    "| Ridge, $\\alpha = 100$ | 0.742 | 0.668 | 90 |\n",
    "| Lasso, $\\alpha = 0.05$ | 0.728 | 0.658 | 24 |\n",
    "| elastic net, $\\alpha = 0.1$ | 0.726 | 0.659 | 37 |\n",
    "\n",
    "Now the pattern of the theory is there:\n",
    "\n",
    "- All three regularized models have a lower training score and a higher test score than the plain model. They gave up fit on the training rows and gained on new houses.\n",
    "- Ridge kept all ninety features with small weights and has the best test score, 0.668, above every model of Part 6.\n",
    "- Lasso reached almost the same with 24 of the 90 features: it set 66 weights to exactly 0.\n",
    "- The elastic net lies between the two, as its penalty does.\n",
    "\n",
    "### 7.3 Even more freedom\n",
    "\n",
    "With `degree=3` the same twelve features become 454, more than the 436 training houses:"
   ],
   "id": "t26-057"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "maker = PolynomialFeatures(degree=3, include_bias=False)\n",
    "scaler_huge = StandardScaler()\n",
    "X_train_huge = scaler_huge.fit_transform(maker.fit_transform(X_train))\n",
    "X_test_huge = scaler_huge.transform(maker.transform(X_test))\n",
    "\n",
    "print(X_train_huge.shape)"
   ],
   "id": "t26-058"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The plain model first. Its test score is printed in another way this time: the cell only asks whether it is below 0."
   ],
   "id": "t26-059"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "linear_huge = LinearRegression()\n",
    "linear_huge.fit(X_train_huge, y_train)\n",
    "\n",
    "print(round(linear_huge.score(X_train_huge, y_train), 3))\n",
    "print(linear_huge.score(X_test_huge, y_test) < 0)"
   ],
   "id": "t26-060"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A training score of 0.948, and a test score below 0: worse than always answering with the mean price. (On the computer on which this lesson was written the test score is about $-1.9$. With more features than rows the weights of such a model rest on tiny differences in the calculation, so the exact number can differ a little from one computer to the next. That is itself a sign of how unsteady the model is.) With more features than rows the model can fit its training data almost perfectly, and what it learned is noise.\n",
    "\n",
    "The same 454 features with a penalty:"
   ],
   "id": "t26-061"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "models = {\n",
    "    \"ridge\": Ridge(alpha=300),\n",
    "    \"lasso\": Lasso(alpha=0.05),\n",
    "    \"elastic net\": ElasticNet(alpha=0.1, l1_ratio=0.5),\n",
    "}\n",
    "\n",
    "for name, model in models.items():\n",
    "    model.fit(X_train_huge, y_train)\n",
    "    kept = (model.coef_ != 0).sum()\n",
    "    print(name, round(model.score(X_train_huge, y_train), 3), round(model.score(X_test_huge, y_test), 3), kept)"
   ],
   "id": "t26-062"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Ordinary, usable models: Ridge reaches 0.659, Lasso reaches 0.652 with 47 features and 407 weights at 0, and the elastic net reaches 0.653 with 69 features. (Ridge shows 449 weights, not 454: five of the new columns are 0 in every training row, each a product of three yes/no features that never occur together in one house, and a column that never changes gets the weight 0.)\n",
    "\n",
    "The size of the weights tells the story of Part 1. The cell prints the largest weight of the first model of the lesson, then whether the largest weight of the plain model on 454 features is above 10, then the largest weight of the Ridge model on the same features:"
   ],
   "id": "t26-063"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(round(abs(linear.coef_).max(), 2))\n",
    "print(abs(linear_huge.coef_).max() > 10)\n",
    "print(round(abs(models[\"ridge\"].coef_).max(), 2))"
   ],
   "id": "t26-064"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The largest weight of the first model was 0.52. The plain model on 454 features has weights above 10 (about 17 here), more than twenty times as large. The Ridge model on the same features has no weight above 0.06.\n",
    "\n",
    "The picture shows the twelve weights of the housing model for a whole range of alphas. Under Ridge all lines sink towards 0 together and never reach it. Under Lasso the lines hit 0 one after another and stay there: the weak features leave first, the area and the bathrooms last.\n",
    "\n",
    "### 7.4 What the project showed\n",
    "\n",
    "|  | 12 features | 90 features | 454 features |\n",
    "| --- | --- | --- | --- |\n",
    "| linear regression: training / test | 0.685 / 0.649 | 0.790 / 0.650 | 0.948 / below 0 |\n",
    "| Ridge: test | 0.648 | 0.668 | 0.659 |\n",
    "| Lasso: test (features kept) | 0.646 (12) | 0.658 (24) | 0.652 (47) |\n",
    "| Elastic net: test (features kept) | 0.638 (12) | 0.659 (37) | 0.653 (69) |\n",
    "\n",
    "- Few features, enough rows: the plain model is fine, and regularization changes nothing.\n",
    "- Many features: the plain model overfits, and regularization brings a real gain.\n",
    "- More features than rows: the plain model is useless, and regularization makes it work.\n",
    "- The more freedom a model has, the more it needs a penalty. That is why regularization is part of nearly every large model in machine learning.\n",
    "\n",
    "## 8. The workflow, step by step\n",
    "\n",
    "The order of this project is the order of most projects with tables of data.\n",
    "\n",
    "| Step | What is done | In this project |\n",
    "| --- | --- | --- |\n",
    "| 1. Look | shape, first rows, kinds of columns | 545 houses, 13 columns, 7 of them text |\n",
    "| 2. Check | missing values, repeated rows, columns without information | nothing to repair, nothing to drop |\n",
    "| 3. Outliers | find them, decide: mistake or real | real houses: kept |\n",
    "| 4. Encode | text to numbers | six yes/no columns as 1 and 0, one ordinal column |\n",
    "| 5. Split | training and test data | 436 and 109 houses |\n",
    "| 6. Scale | fit on the training data, transform both | `StandardScaler`: required for regularization |\n",
    "| 7. First model | a simple starting point | `LinearRegression`: 0.649 |\n",
    "| 8. Improve | other models, more features, regularization | Ridge, Lasso, elastic net |\n",
    "| 9. Tune | choose hyperparameters with cross-validation | `alpha` |\n",
    "| 10. Judge | the test score of the finished models, once | the table of Part 6 |\n",
    "\n",
    "Steps 1 to 4 need no learning from the rows and are done on the whole table. From step 6 on, everything that learns is fitted on the training data (Topics 24 and 25).\n",
    "\n",
    "## 9. Common mistakes\n",
    "\n",
    "| Mistake | Why it is wrong | Right |\n",
    "| --- | --- | --- |\n",
    "| Regularization on features that are not scaled. | The penalty punishes a feature for its unit, not for its importance. | Scale first, with a scaler fitted on the training data. |\n",
    "| Choosing alpha by the test score. | The test data takes part in building the model, and its score is no longer honest. | Cross-validation on the training data. |\n",
    "| \"A larger alpha is always safer.\" | Too much penalty gives underfitting: both scores fall. | Try several values, from very small to very large. |\n",
    "| Using the same alpha for Ridge and for Lasso. | The two are on different scales. | Tune each model by itself. |\n",
    "| Expecting regularization to raise every score. | It cures overfitting. A model that does not overfit has nothing to gain. | Compare the training and the test score first. |\n",
    "| Expecting Ridge to remove features. | Ridge makes weights small, never exactly 0. | Lasso or elastic net for selection. |\n",
    "| Reading a weight of 0 in a Lasso as \"this feature has no effect in reality\". | Lasso may drop one of two correlated features, although both matter. | It only says: the model does well without it. |\n",
    "| Judging overfitting by the training score alone. | A high training score is exactly what an overfitted model has. | Look at the gap to the test score. |\n",
    "| Fitting the scaler or `PolynomialFeatures` on all rows before the split. | Data leakage (Topic 24). | Split first; fit on the training data. |\n",
    "| Forgetting that $\\alpha = 0$ is plain linear regression. | Then the penalty is switched off. | Use `LinearRegression` when no penalty is wanted. |\n",
    "\n",
    "## 10. Solved problems\n",
    "\n",
    "Fourteen problems. The first three are short and solved by hand. Problems 4 to 14 are one project on `Housing.csv`, solved step by step like a notebook: every cell continues from the cells above it. It is the workflow of the lesson once more, with a few choices made differently: another split, and one-hot encoding for the furnishing.\n",
    "\n",
    "Problem 1. The two penalties by hand\n",
    "\n",
    "A model has the weights 2, $-3$ and 0.5. Calculate its L2 penalty and its L1 penalty (without alpha).\n",
    "\n",
    "Idea. L2 is the sum of the squared weights, L1 the sum of their absolute values (Part 2).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{L2:}\\quad & 2^2 + (-3)^2 + 0.5^2 \\\\\n",
    "& = 4 + 9 + 0.25 = 13.25 \\\\[10pt]\n",
    "\\text{L1:}\\quad & \\lvert 2 \\rvert + \\lvert -3 \\rvert + \\lvert 0.5 \\rvert \\\\\n",
    "& = 2 + 3 + 0.5 = 5.5\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: the sign of a weight does not matter for either penalty: only its size. In L2 the weight $-3$ alone gives 9 of the 13.25: squaring makes the largest weight count most.\n",
    "\n",
    "Problem 2. Which model wins?\n",
    "\n",
    "Model A has a training MSE of 2.0 and the weights 5 and 5. Model B has a training MSE of 2.5 and the weights 2 and 1. Which model has the smaller Ridge loss with $\\alpha = 0.1$? And with $\\alpha = 0.01$?\n",
    "\n",
    "Idea. $\\text{Ridge loss} = \\text{MSE} + \\alpha \\times (\\text{sum of the squared weights})$ (Part 2).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{L2 of A: } 5^2 + 5^2 = 50 \\\\[2pt]\n",
    "& \\text{L2 of B: } 2^2 + 1^2 = 5 \\\\[12pt]\n",
    "\\alpha = 0.1:\\quad & \\text{A: } 2.0 + 0.1 \\times 50 = 7.0 \\\\[2pt]\n",
    "& \\text{B: } 2.5 + 0.1 \\times 5 = 3.0 \\\\[10pt]\n",
    "\\alpha = 0.01:\\quad & \\text{A: } 2.0 + 0.01 \\times 50 = 2.5 \\\\[2pt]\n",
    "& \\text{B: } 2.5 + 0.01 \\times 5 = 2.55\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: with $\\alpha = 0.1$ Model B wins clearly: its small weights outweigh its larger error. With $\\alpha = 0.01$ Model A wins by a little: the penalty is too weak. The choice of alpha decides which model the training prefers.\n",
    "\n",
    "Problem 3. Ridge divides, Lasso subtracts\n",
    "\n",
    "In the simplest case of Part 2, three weights without a penalty are 6, 2 and 0.4. What do they become with $\\alpha = 1$ under Ridge and under Lasso?\n",
    "\n",
    "Idea. Ridge: $\\frac{w}{1 + \\alpha}$. Lasso: $w - \\alpha$, and 0 when $w$ is smaller than $\\alpha$ (Part 2).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{Ridge:}\\quad & \\frac{6}{2} = 3 \\qquad \\frac{2}{2} = 1 \\qquad \\frac{0.4}{2} = 0.2 \\\\[10pt]\n",
    "\\text{Lasso:}\\quad & 6 - 1 = 5 \\qquad 2 - 1 = 1 \\\\[4pt]\n",
    "& 0.4 - 1 \\text{ is below } 0 \\text{, so the weight is } 0\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: Ridge halves every weight and keeps all three. Lasso takes 1 from each: the large weight hardly notices, and the small one is gone. A feature with a weight of 0 has left the model.\n",
    "\n",
    "Problem 4. Read and check\n",
    "\n",
    "Read `Housing.csv`. Print its shape, the number of missing values and the number of repeated rows.\n",
    "\n",
    "Idea. The first two steps of the workflow: look and check (Part 3)."
   ],
   "id": "t26-065"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"Housing.csv\")\n",
    "\n",
    "print(df.shape)\n",
    "print(df.isna().sum().sum(), df.duplicated().sum())"
   ],
   "id": "t26-066"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: before any model, know what is in the table. Nothing is missing and nothing is repeated, so no cleaning is needed here.\n",
    "\n",
    "Problem 5. The target and the yes/no columns\n",
    "\n",
    "Turn the price into millions and encode the six yes/no columns as 1 and 0. Print the first three rows of `price`, `mainroad` and `basement`.\n",
    "\n",
    "Idea. A change of unit, and `map` with a dictionary in a loop (Part 3)."
   ],
   "id": "t26-067"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df[\"price\"] = df[\"price\"] / 1000000\n",
    "\n",
    "for name in [\"mainroad\", \"guestroom\", \"basement\", \"hotwaterheating\", \"airconditioning\", \"prefarea\"]:\n",
    "    df[name] = df[name].map({\"no\": 0, \"yes\": 1})\n",
    "\n",
    "print(df[[\"price\", \"mainroad\", \"basement\"]].head(3))"
   ],
   "id": "t26-068"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: both steps follow fixed rules and learn nothing from the rows, so they are done on the whole table before the split.\n",
    "\n",
    "Problem 6. One-hot encoding for the furnishing\n",
    "\n",
    "The lesson gave `furnishingstatus` numbers in order. Encode it this time with one-hot encoding, with `drop_first=True`. Print the names of the last three columns.\n",
    "\n",
    "Idea. `pd.get_dummies` (Topic 25). With three categories and one dropped, two columns arrive."
   ],
   "id": "t26-069"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.get_dummies(df, columns=[\"furnishingstatus\"], drop_first=True, dtype=int)\n",
    "\n",
    "print(df.columns.tolist()[-3:])"
   ],
   "id": "t26-070"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: both encodings are defensible for this column. One-hot encoding does not assume that the step from unfurnished to semi-furnished is as large as the next one. `furnished`, the first category in the alphabet, is the reference.\n",
    "\n",
    "Problem 7. Split\n",
    "\n",
    "Make `X` and `y`, and split them with `test_size=0.25` and `random_state=7`. Print the shapes of `X_train` and `X_test`.\n",
    "\n",
    "Idea. The split comes before everything that learns from the rows (Part 3)."
   ],
   "id": "t26-071"
  },
  {
   "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",
    "\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=7)\n",
    "\n",
    "print(X_train.shape, X_test.shape)"
   ],
   "id": "t26-072"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: thirteen features now, because the furnishing became two columns. A quarter of the houses is put aside for the test.\n",
    "\n",
    "Problem 8. Scale\n",
    "\n",
    "Scale the features with a `StandardScaler` that is fitted on the training data. Print the shapes of the two scaled arrays.\n",
    "\n",
    "Idea. `fit_transform` on the training data, `transform` on the test data (Topic 24)."
   ],
   "id": "t26-073"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "scaler = StandardScaler()\n",
    "X_train_scaled = scaler.fit_transform(X_train)\n",
    "X_test_scaled = scaler.transform(X_test)\n",
    "\n",
    "print(X_train_scaled.shape, X_test_scaled.shape)"
   ],
   "id": "t26-074"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the penalty of Ridge and Lasso looks at the size of the weights, and only on scaled features do the sizes mean the same for every feature.\n",
    "\n",
    "Problem 9. The starting point\n",
    "\n",
    "Train a `LinearRegression` and print its training score and its test score.\n",
    "\n",
    "Idea. Every project starts with a simple model to compare with (Part 4)."
   ],
   "id": "t26-075"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import LinearRegression\n",
    "\n",
    "linear = LinearRegression()\n",
    "linear.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(linear.score(X_train_scaled, y_train), 3))\n",
    "print(round(linear.score(X_test_scaled, y_test), 3))"
   ],
   "id": "t26-076"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: 0.695 and 0.639. The gap is about 0.06: a little overfitting, not much. These two numbers are what the next models are measured against.\n",
    "\n",
    "Problem 10. Ridge\n",
    "\n",
    "Train a `Ridge` with `alpha=10` and print its two scores.\n",
    "\n",
    "Idea. Used exactly like `LinearRegression`, with the strength of the penalty as `alpha` (Part 5)."
   ],
   "id": "t26-077"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import Ridge\n",
    "\n",
    "ridge = Ridge(alpha=10)\n",
    "ridge.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(ridge.score(X_train_scaled, y_train), 3))\n",
    "print(round(ridge.score(X_test_scaled, y_test), 3))"
   ],
   "id": "t26-078"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: practically the scores of the plain model. With thirteen features and 408 training houses there is little overfitting for the penalty to remove.\n",
    "\n",
    "Problem 11. Lasso and the weights that become 0\n",
    "\n",
    "Train a `Lasso` with `alpha=0.3`. Print its test score, and the names of the features whose weight is 0.\n",
    "\n",
    "Idea. `coef_ == 0` marks the features that Lasso removed (Part 5)."
   ],
   "id": "t26-079"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import Lasso\n",
    "\n",
    "lasso = Lasso(alpha=0.3)\n",
    "lasso.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(lasso.score(X_test_scaled, y_test), 3))\n",
    "print(X.columns[lasso.coef_ == 0].tolist())"
   ],
   "id": "t26-080"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: a strong Lasso removed five of the thirteen features, and the test score fell far below the 0.639 of the plain model. `X.columns[...]` with a list of `True` and `False` keeps the names where it is `True` (Topic 10). The alpha is too large for this data: the next problem looks for a better one.\n",
    "\n",
    "Problem 12. Choosing alpha\n",
    "\n",
    "Compare the Lasso alphas 0.001, 0.01, 0.05 and 0.1 with a 5-fold cross-validation on the training data. Print every alpha with its mean score.\n",
    "\n",
    "Idea. Alpha is chosen with cross-validation, never with the test data (Part 6)."
   ],
   "id": "t26-081"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import cross_val_score\n",
    "\n",
    "for alpha in [0.001, 0.01, 0.05, 0.1]:\n",
    "    scores = cross_val_score(Lasso(alpha=alpha), X_train_scaled, y_train, cv=5)\n",
    "    print(alpha, round(scores.mean(), 3))"
   ],
   "id": "t26-082"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the mean score is best at $\\alpha = 0.01$ and falls for the larger values. A small alpha is right here, which fits the picture: the model hardly overfits, so it needs hardly any penalty.\n",
    "\n",
    "Problem 13. Elastic net\n",
    "\n",
    "Train an `ElasticNet` with `alpha=0.05` and `l1_ratio=0.5`. Print its test score and the number of weights that are not 0.\n",
    "\n",
    "Idea. A mix of both penalties: `l1_ratio` is the share of L1 (Part 5)."
   ],
   "id": "t26-083"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import ElasticNet\n",
    "\n",
    "elastic = ElasticNet(alpha=0.05, l1_ratio=0.5)\n",
    "elastic.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(elastic.score(X_test_scaled, y_test), 3))\n",
    "print((elastic.coef_ != 0).sum())"
   ],
   "id": "t26-084"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: twelve of the thirteen weights are left. The L1 half of the penalty removed one feature, and the L2 half kept the others small but alive.\n",
    "\n",
    "Problem 14. All models side by side\n",
    "\n",
    "Train the four models (linear, Ridge with alpha 10, Lasso with alpha 0.01, elastic net with alpha 0.05) and print the name and the test score of each.\n",
    "\n",
    "Idea. A dictionary of models and one loop (Part 6)."
   ],
   "id": "t26-085"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "models = {\n",
    "    \"linear\": LinearRegression(),\n",
    "    \"ridge\": Ridge(alpha=10),\n",
    "    \"lasso\": Lasso(alpha=0.01),\n",
    "    \"elastic net\": ElasticNet(alpha=0.05, l1_ratio=0.5),\n",
    "}\n",
    "\n",
    "for name, model in models.items():\n",
    "    model.fit(X_train_scaled, y_train)\n",
    "    print(name, round(model.score(X_test_scaled, y_test), 3))"
   ],
   "id": "t26-086"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the four test scores lie within about 0.01 of each other. With another split and another encoding the project gives the same answer as the lesson: on these twelve or thirteen features the plain model is enough, and regularization is the tool to keep ready for models with more freedom.\n",
    "\n",
    "## 13. Summary\n",
    "\n",
    "|  | Ridge | Lasso | Elastic net |\n",
    "| --- | --- | --- | --- |\n",
    "| Penalty | L2: the sum of the squared weights | L1: the sum of the absolute weights | a mix of L1 and L2 |\n",
    "| Effect on the weights | all smaller, none exactly 0 | some exactly 0 | smaller, and some 0 |\n",
    "| Feature selection | no | yes | yes |\n",
    "| Use it when | most features carry something; correlated features | few of many features matter; a short model is wanted | many features and groups of correlated ones |\n",
    "| In scikit-learn | `Ridge(alpha=10)` | `Lasso(alpha=0.01)` | `ElasticNet(alpha=0.05, l1_ratio=0.5)` |\n",
    "\n",
    "| Code | What it does |\n",
    "| --- | --- |\n",
    "| `model = Ridge(alpha=10)` | a linear regression with the L2 penalty |\n",
    "| `model = Lasso(alpha=0.01)` | a linear regression with the L1 penalty |\n",
    "| `model = ElasticNet(alpha=0.05, l1_ratio=0.5)` | a mix of both penalties |\n",
    "| `model.coef_` | the weights after training |\n",
    "| `(model.coef_ != 0).sum()` | the number of features that are left |\n",
    "| `cross_val_score(Ridge(alpha=a), X_train_scaled, y_train, cv=5).mean()` | the judgement of one alpha |\n",
    "| `PolynomialFeatures(degree=2, include_bias=False)` | adds squares and products of the features |\n",
    "\n",
    "### Rules to keep\n",
    "\n",
    "1. Regularization is a penalty for large weights. It trades a little fit on the training data for steadier predictions.\n",
    "2. Ridge shrinks all weights. Lasso sets some to exactly 0. The elastic net does both.\n",
    "3. Scale the features before any regularized model.\n",
    "4. Alpha is chosen with cross-validation on the training data, never with the test data.\n",
    "5. Too small an alpha leaves overfitting; too large an alpha makes underfitting.\n",
    "6. Compare the training and the test score first. Without overfitting there is nothing to cure.\n",
    "7. The more features a model has for its rows, the more it needs a penalty.\n",
    "\n",
    "### What comes next\n",
    "\n",
    "Until now every model predicted a number: a price. Topic 27, logistic regression, is the first model for the other large task of supervised learning: predicting a class, such as \"yes\" or \"no\". The regularization of this lesson will be part of it from the start.\n",
    "\n",
    "Next: the practice notebook (topic-26-practice.ipynb), then Topic 27: Logistic Regression."
   ],
   "id": "t26-087"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
