{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 27: Logistic Regression\n",
    "\n",
    "Asiman Data School, Module 3: Comprehensive Machine Learning. Week 14, 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-27-practice.ipynb.\n",
    "\n",
    "The cells continue from each other: a cell uses the variables of the cells above it. Parts 6 to 10 are one project, so start at the first cell of Part 6. The solved problems 5 to 16 are a second project that starts again from reading the file.\n",
    "\n",
    "This notebook reads the file Bank Customer Churn Prediction.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. What logistic regression is, and why it is needed\n",
    "2. The formula, and where it comes from\n",
    "3. Two classes or more: the sigmoid and the softmax\n",
    "4. The loss function: cross-entropy\n",
    "5. The parameters of LogisticRegression\n",
    "6. The project: the data and its preparation\n",
    "7. The first model\n",
    "8. Changing the hyperparameters\n",
    "9. A better model through better features\n",
    "10. More than two classes on the same data\n",
    "11. The workflow, step by step\n",
    "12. Common mistakes\n",
    "13. Solved problems\n",
    "14. Practice (in topic-27-practice.ipynb)\n",
    "15. Check yourself (on the website)\n",
    "16. Summary"
   ],
   "id": "t27-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction: from numbers to classes\n",
    "\n",
    "What matters most in this lesson. Five things matter most today. First, logistic regression is a model for classification: it calculates a linear score, turns it into a probability, and the probability into a class. Second, the two functions: the sigmoid for two classes and the softmax for three or more. Third, the loss it is trained with, the cross-entropy: minus the logarithm of the probability given to the true class. Fourth, the parameters, above all `C`: a small `C` is a strong regularization. Fifth, the work on the data: look at the classes of the target, compare every accuracy with the baseline, and remember that better features beat better hyperparameters.\n",
    "\n",
    "In this lesson a model is judged with the accuracy only. Topic 28 adds the other measures.\n",
    "\n",
    "The seventh lesson of Module 3. Every model so far predicted a number: a mark, a price. This lesson is about the other large task of supervised learning (Topic 21): predicting a class. Will this customer leave the bank, yes or no? Is this e-mail spam? Is this tumour benign or malignant? The first and most important model for such questions is logistic regression.\n",
    "\n",
    "The lesson has two halves. The first explains the model: what it is, where its formula comes from, the sigmoid for two classes and the softmax for several, the loss it is trained with, and its parameters. The second half is a complete project on a real data file, `Bank Customer Churn Prediction.csv`: every step from reading the file to a trained and tuned model, in the order of real work. It repeats everything of Topics 22 to 26.\n",
    "\n",
    "In this lesson a model is judged with one measure only, the accuracy: the share of right predictions. Topic 28 adds the other measures of classification.\n",
    "\n",
    "You need: linear regression and gradient descent (Topic 22), the train/test split and cross-validation (Topic 23), scaling (Topic 24), outliers and encoding (Topic 25), regularization (Topic 26), and probability (Topic 16).\n",
    "\n",
    "| Word | Meaning |\n",
    "| --- | --- |\n",
    "| classification | predicting a class (a category), not a number |\n",
    "| binary classification | two classes: yes or no, 1 or 0 |\n",
    "| multi-class classification | three or more classes |\n",
    "| logistic regression | a linear model that predicts the probability of a class |\n",
    "| odds | the probability that something happens divided by the probability that it does not |\n",
    "| log-odds (logit) | the logarithm of the odds |\n",
    "| sigmoid | the S-shaped function that turns any number into a number between 0 and 1 |\n",
    "| softmax | the function that turns several scores into probabilities that add up to 1 |\n",
    "| activation function | the function between the linear score and the output: here the sigmoid or the softmax |\n",
    "| threshold | the probability from which the model answers \"yes\": usually 0.5 |\n",
    "| cross-entropy (log loss) | the loss function of logistic regression |\n",
    "| accuracy | the share of predictions that are right |\n",
    "| churn | a customer leaving a company |\n",
    "\n",
    "## 1. What logistic regression is, and why it is needed\n",
    "\n",
    "### 1.1 A new kind of question\n",
    "\n",
    "|  | Regression | Classification |\n",
    "| --- | --- | --- |\n",
    "| The target is | a number | a class |\n",
    "| Example | the price of a house | will the customer leave: yes or no |\n",
    "| Typical model | linear regression | logistic regression |\n",
    "| Typical measure | $R^2$, RMSE | accuracy |\n",
    "\n",
    "Despite its name, logistic regression is a model for classification. The word \"regression\" is there because, inside, it calculates a number, a probability, and only then turns it into a class.\n",
    "\n",
    "A model that says \"this customer will leave with a probability of 0.83\" is worth more than one that only says \"leaves\". The bank can call the customers with the highest probabilities first. Logistic regression gives exactly this: a probability for every row.\n",
    "\n",
    "### 1.2 Why not linear regression?\n",
    "\n",
    "The two classes can be written as numbers, 1 for \"yes\" and 0 for \"no\". Then a linear regression could be trained on them. It is tried in the left picture, and it fails for three reasons.\n",
    "\n",
    "1. A line has no limits. For large $x$ it predicts more than 1, for small $x$ less than 0. A probability of 1.3 or of $-0.2$ does not exist.\n",
    "2. A line changes at the same speed everywhere. In reality the answer is almost certain far from the border between the classes, and it changes quickly near the border. That is the shape of an S, not of a line.\n",
    "3. The squared error fits numbers, not classes. Part 4 comes back to this.\n",
    "\n",
    "Logistic regression keeps what is good about a linear model, a weighted sum of the features, and bends its result into the range from 0 to 1.\n",
    "\n",
    "## 2. The formula, and where it comes from\n",
    "\n",
    "### 2.1 Step 1: a linear score\n",
    "\n",
    "Like linear regression, the model first calculates a weighted sum of the features. It is called the score and written $z$:\n",
    "\n",
    "$$\n",
    "z = w_0 + w_1 x_1 + w_2 x_2 + \\dots + w_p x_p\n",
    "$$\n",
    "\n",
    "$z$ can be any number, from very negative to very positive. A large positive $z$ shall mean \"almost certainly class 1\", a large negative $z$ \"almost certainly class 0\". What is needed is a bridge from $z$ to a probability.\n",
    "\n",
    "### 2.2 Step 2: from a probability to the odds\n",
    "\n",
    "A probability $p$ lies between 0 and 1. The odds compare it with its opposite:\n",
    "\n",
    "$$\n",
    "\\text{odds} = \\frac{p}{1 - p}\n",
    "$$\n",
    "\n",
    "| Probability $p$ | Odds | In words |\n",
    "| --- | --- | --- |\n",
    "| 0.5 | $\\frac{0.5}{0.5} = 1$ | one to one |\n",
    "| 0.8 | $\\frac{0.8}{0.2} = 4$ | four to one |\n",
    "| 0.9 | $\\frac{0.9}{0.1} = 9$ | nine to one |\n",
    "| 0.2 | $\\frac{0.2}{0.8} = 0.25$ | one to four |\n",
    "\n",
    "The odds run from 0 to infinity. That is already one limit less.\n",
    "\n",
    "### 2.3 Step 3: from the odds to the log-odds\n",
    "\n",
    "The logarithm of the odds, the log-odds or logit, removes the other limit:\n",
    "\n",
    "$$\n",
    "\\text{log-odds} = \\ln \\frac{p}{1 - p}\n",
    "$$\n",
    "\n",
    "| Probability $p$ | Odds | Log-odds |\n",
    "| --- | --- | --- |\n",
    "| 0.1 | 0.111 | $-2.197$ |\n",
    "| 0.2 | 0.25 | $-1.386$ |\n",
    "| 0.5 | 1 | 0 |\n",
    "| 0.8 | 4 | 1.386 |\n",
    "| 0.9 | 9 | 2.197 |\n",
    "\n",
    "The log-odds run from minus infinity to plus infinity, they are 0 when the probability is 0.5, and they are symmetric: 0.8 and 0.2 give 1.386 and $-1.386$. That is exactly the kind of number a linear score can be.\n",
    "\n",
    "### 2.4 Step 4: the idea of logistic regression\n",
    "\n",
    "Logistic regression assumes that the log-odds are a linear function of the features:\n",
    "\n",
    "$$\n",
    "\\ln \\frac{p}{1 - p} = z = w_0 + w_1 x_1 + \\dots + w_p x_p\n",
    "$$\n",
    "\n",
    "That one line is the whole model. Everything else follows by solving it for $p$:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\frac{p}{1 - p} &= e^{z} \\\\[6pt]\n",
    "p &= e^{z} \\, (1 - p) \\\\[6pt]\n",
    "p \\, (1 + e^{z}) &= e^{z} \\\\[6pt]\n",
    "p &= \\frac{e^{z}}{1 + e^{z}} \\\\[6pt]\n",
    "p &= \\frac{1}{1 + e^{-z}}\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "The last step divides the top and the bottom by $e^{z}$. The result is the formula of logistic regression:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "p &= \\frac{1}{1 + e^{-z}} \\\\[8pt]\n",
    "z &= w_0 + w_1 x_1 + \\dots + w_p x_p\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "The function that turns $z$ into $p$ has a name of its own: the sigmoid.\n",
    "\n",
    "### 2.5 The sigmoid\n",
    "\n",
    "$$\n",
    "\\text{sigmoid}(z) = \\frac{1}{1 + e^{-z}}\n",
    "$$\n",
    "\n",
    "By hand, with $e^{-2} = 0.135$ and $e^{2} = 7.389$:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "z = 0:\\quad & \\frac{1}{1 + e^{0}} = \\frac{1}{1 + 1} = 0.5 \\\\[8pt]\n",
    "z = 2:\\quad & \\frac{1}{1 + e^{-2}} = \\frac{1}{1 + 0.135} \\\\[4pt]\n",
    "& = \\frac{1}{1.135} = 0.881 \\\\[8pt]\n",
    "z = -2:\\quad & \\frac{1}{1 + e^{2}} = \\frac{1}{1 + 7.389} \\\\[4pt]\n",
    "& = \\frac{1}{8.389} = 0.119\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Read the curve:\n",
    "\n",
    "- It turns any number into a number between 0 and 1. A score of 100 gives a probability just below 1, a score of $-100$ one just above 0. The limits are never reached.\n",
    "- At $z = 0$ it gives exactly 0.5.\n",
    "- It is steep in the middle and flat at the ends: near the border a small change of the score moves the probability a lot; far from the border the model is sure and stays sure.\n",
    "- It is symmetric: $\\text{sigmoid}(-z) = 1 - \\text{sigmoid}(z)$. The values 0.881 and 0.119 above add up to 1.\n",
    "\n",
    "### 2.6 From a probability to a class: the threshold\n",
    "\n",
    "The model answers with a class by comparing the probability with a threshold, usually 0.5:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "p \\ge 0.5:\\quad & \\text{class 1} \\\\[4pt]\n",
    "p < 0.5:\\quad & \\text{class 0}\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Because $p = 0.5$ exactly when $z = 0$, this is the same as asking whether the score is positive. The points where $z = 0$ form the decision boundary: a straight line (with two features), a plane or its higher relative (with more). So logistic regression is a linear classifier: it separates the two classes with a straight border. The S is the shape of the probability, not of the border.\n",
    "\n",
    "### 2.7 An example by hand\n",
    "\n",
    "A small model for churn has two features: the age (in decades) and whether the customer is an active member (1 or 0).\n",
    "\n",
    "$$\n",
    "z = -4 + 1.0 \\times \\text{age} - 1.0 \\times \\text{active}\n",
    "$$\n",
    "\n",
    "A customer of 50 years (age = 5) who is not active:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "z &= -4 + 1.0 \\times 5 - 1.0 \\times 0 = 1 \\\\[8pt]\n",
    "p &= \\frac{1}{1 + e^{-1}} = \\frac{1}{1 + 0.368} \\\\[4pt]\n",
    "&= \\frac{1}{1.368} = 0.731\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "The probability of leaving is 0.731, above 0.5: the model predicts class 1, \"leaves\". The same customer as an active member:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "z &= -4 + 1.0 \\times 5 - 1.0 \\times 1 = 0 \\\\[8pt]\n",
    "p &= \\frac{1}{1 + e^{0}} = 0.5\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Exactly on the border.\n",
    "\n",
    "### 2.8 What a weight means\n",
    "\n",
    "In linear regression a weight is \"the change of the prediction for one unit of the feature\". Here the weight changes the log-odds, and that reads best in odds:\n",
    "\n",
    "- A weight of $w$ adds $w$ to the log-odds for every unit of the feature.\n",
    "- The odds are then multiplied by $e^{w}$.\n",
    "\n",
    "In the example, one decade of age adds 1.0 to the score, so it multiplies the odds of leaving by $e^{1} = 2.718$. Being an active member multiplies them by $e^{-1} = 0.368$: it cuts them to about a third.\n",
    "\n",
    "The simple reading is enough for most work: a positive weight pushes towards class 1, a negative weight towards class 0, and a weight further from 0 pushes harder.\n",
    "\n",
    "## 3. Two classes or more: the sigmoid and the softmax\n",
    "\n",
    "### 3.1 Binary and multi-class\n",
    "\n",
    "|  | Binary classification | Multi-class classification |\n",
    "| --- | --- | --- |\n",
    "| Classes | two | three or more |\n",
    "| Examples | leaves or stays; spam or not; ill or healthy | the country of a customer; the digit in a picture; the species of a flower |\n",
    "| The model calculates | one score $z$ | one score for every class |\n",
    "| Function at the end | sigmoid | softmax |\n",
    "| Output | one probability $p$ (the other is $1 - p$) | one probability for every class; together they add up to 1 |\n",
    "\n",
    "The function that stands between the linear score and the output is called the activation function of the model. The word comes from neural networks (Module 5), where logistic regression returns as the smallest possible network: one layer of weights and an activation function.\n",
    "\n",
    "### 3.2 The softmax\n",
    "\n",
    "With three classes the model has three sets of weights and calculates three scores, $z_1$, $z_2$, $z_3$: one for every class. The softmax turns them into three probabilities:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "p_1 &= \\frac{e^{z_1}}{e^{z_1} + e^{z_2} + e^{z_3}} \\\\[8pt]\n",
    "p_2 &= \\frac{e^{z_2}}{e^{z_1} + e^{z_2} + e^{z_3}} \\\\[8pt]\n",
    "p_3 &= \\frac{e^{z_3}}{e^{z_1} + e^{z_2} + e^{z_3}}\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Two things happen. $e^{z}$ makes every score positive and makes large scores much larger. Dividing by the sum makes the three results add up to 1.\n",
    "\n",
    "By hand, with the scores 2, 1 and 0 ($e^{2} = 7.389$, $e^{1} = 2.718$, $e^{0} = 1$):\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{sum} &= 7.389 + 2.718 + 1 = 11.107 \\\\[8pt]\n",
    "p_1 &= \\frac{7.389}{11.107} = 0.665 \\\\[6pt]\n",
    "p_2 &= \\frac{2.718}{11.107} = 0.245 \\\\[6pt]\n",
    "p_3 &= \\frac{1}{11.107} = 0.090\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "The three probabilities add up to 1, and the class with the highest score has the highest probability. The model answers with that class: class 1.\n",
    "\n",
    "- The name: it is a soft version of the maximum. A hard maximum would answer 1, 0, 0. The softmax gives most of the probability to the largest score and leaves a little for the others.\n",
    "- The differences between the scores matter, not the scores themselves: 2, 1, 0 and 12, 11, 10 give the same probabilities.\n",
    "- With two classes the softmax is the sigmoid. The two functions are one idea: the sigmoid is the short form for the case of two classes.\n",
    "\n",
    "### 3.3 Side by side\n",
    "\n",
    "|  | Sigmoid | Softmax |\n",
    "| --- | --- | --- |\n",
    "| Used for | two classes | three or more classes |\n",
    "| Input | one score | one score for every class |\n",
    "| Output | one probability between 0 and 1 | probabilities that add up to 1 |\n",
    "| Formula | $\\frac{1}{1 + e^{-z}}$ | $\\frac{e^{z_k}}{\\text{sum of all } e^{z}}$ |\n",
    "| Decision | class 1 if $p \\ge 0.5$ | the class with the largest probability |\n",
    "\n",
    "In scikit-learn you do not choose between them: `LogisticRegression` looks at the target and uses the right one. Part 10 shows it on the bank data.\n",
    "\n",
    "## 4. The loss function: cross-entropy\n",
    "\n",
    "### 4.1 What the training needs\n",
    "\n",
    "Training means finding the weights that make a loss as small as possible (Topic 22). For linear regression the loss was the mean squared error. A classifier predicts a probability $p$, and the true answer $y$ is 1 or 0. A good loss must be small when the model gives a high probability to the true class, and large when it does not.\n",
    "\n",
    "### 4.2 The formula\n",
    "\n",
    "For one row the cross-entropy, also called log loss, is:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{loss} &= -\\ln(p) && \\text{when the true class is 1} \\\\[4pt]\n",
    "\\text{loss} &= -\\ln(1 - p) && \\text{when the true class is 0}\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "In both cases it is minus the logarithm of the probability that the model gave to the true class. The two lines are usually written as one formula:\n",
    "\n",
    "$$\n",
    "\\text{loss} = -\\left[ \\, y \\ln(p) + (1 - y) \\ln(1 - p) \\, \\right]\n",
    "$$\n",
    "\n",
    "With $y = 1$ the second part disappears, with $y = 0$ the first. The loss of the model is the mean over all rows.\n",
    "\n",
    "### 4.3 By hand\n",
    "\n",
    "Four customers who really left ($y = 1$), and the probability of leaving that the model gave each of them:\n",
    "\n",
    "| The model said | Loss | Reading |\n",
    "| --- | --- | --- |\n",
    "| $p = 0.99$ | $-\\ln(0.99) = 0.010$ | sure and right: almost no loss |\n",
    "| $p = 0.9$ | $-\\ln(0.9) = 0.105$ | right: a small loss |\n",
    "| $p = 0.6$ | $-\\ln(0.6) = 0.511$ | right, but unsure: a medium loss |\n",
    "| $p = 0.1$ | $-\\ln(0.1) = 2.303$ | wrong: a large loss |\n",
    "| $p = 0.01$ | $-\\ln(0.01) = 4.605$ | sure and wrong: a very large loss |\n",
    "\n",
    "The loss is 0 for a perfect prediction and grows without limit as the model becomes sure of the wrong answer.\n",
    "\n",
    "### 4.4 Why this loss, and not the squared error?\n",
    "\n",
    "1. It punishes a confident mistake properly. Compare the two losses for a customer who left ($y = 1$):\n",
    "\n",
    "| The model said | Squared error $(1 - p)^2$ | Cross-entropy $-\\ln(p)$ |\n",
    "| --- | --- | --- |\n",
    "| $p = 0.9$ | 0.01 | 0.105 |\n",
    "| $p = 0.5$ | 0.25 | 0.693 |\n",
    "| $p = 0.1$ | 0.81 | 2.303 |\n",
    "| $p = 0.01$ | 0.98 | 4.605 |\n",
    "\n",
    "For the squared error, saying 0.1 and saying 0.01 are almost the same mistake: 0.81 and 0.98. It can never be larger than 1. For the cross-entropy the second mistake costs twice as much, and a model that says \"0.000001\" for something that happens pays a huge price. A model trained with it learns not to be sure without a reason.\n",
    "\n",
    "2. It has one valley. With the sigmoid inside, the squared error becomes a loss with flat regions and several dips, and gradient descent (Topic 22) can get stuck. The cross-entropy of a logistic regression is a single smooth bowl: wherever the walk starts, it reaches the same lowest point.\n",
    "\n",
    "3. It keeps learning when the model is badly wrong. Where the sigmoid is flat, the squared error gives almost no slope, so a very wrong model would learn very slowly. With the cross-entropy the slope is simply the error, $p - y$: the worse the prediction, the larger the step.\n",
    "\n",
    "4. It is the loss that belongs to probabilities. Minimising the cross-entropy is the same as choosing the weights under which the observed data is most probable. This principle is called maximum likelihood.\n",
    "\n",
    "### 4.5 Why not the accuracy as a loss?\n",
    "\n",
    "The accuracy only counts right and wrong. If a weight changes a little, usually no prediction flips, and the accuracy does not move at all: there is no slope to walk down. The cross-entropy changes with every small change of every probability. So the model is trained with the cross-entropy and judged with the accuracy.\n",
    "\n",
    "### 4.6 More than two classes\n",
    "\n",
    "The idea stays the same: the loss of a row is minus the logarithm of the probability that the model gave to the true class.\n",
    "\n",
    "$$\n",
    "\\text{loss} = -\\ln(p \\text{ of the true class})\n",
    "$$\n",
    "\n",
    "In the softmax example of Part 3 the probabilities were 0.665, 0.245 and 0.090. If the true class is class 1, the loss is $-\\ln(0.665) = 0.408$. If it is class 3, the loss is $-\\ln(0.090) = 2.408$.\n",
    "\n",
    "## 5. The parameters of `LogisticRegression`\n",
    "\n",
    "A model has two kinds of numbers (Topic 21). The weights are learned by `fit`. The hyperparameters are set by you when the model is created. `LogisticRegression()` works without any of them, but each one has a job.\n",
    "\n",
    "| Parameter | Default | What it does |\n",
    "| --- | --- | --- |\n",
    "| `C` | `1.0` | the strength of the regularization, turned round: a small `C` is a strong penalty |\n",
    "| `l1_ratio` | `0` | the kind of penalty: `0` is L2 (as Ridge), `1` is L1 (as Lasso), between them an elastic net |\n",
    "| `solver` | `\"lbfgs\"` | the method that searches for the weights |\n",
    "| `max_iter` | `100` | the largest number of steps the solver may take |\n",
    "| `class_weight` | `None` | `\"balanced\"` gives the rare class more weight in the loss |\n",
    "| `random_state` | `None` | fixes the randomness of the solvers that use it |\n",
    "\n",
    "### 5.1 `C`: regularization against overfitting\n",
    "\n",
    "This is the most important one. Logistic regression is regularized by default: its loss is the cross-entropy plus a penalty for large weights, exactly as in Topic 26. The strength is set with `C`, and `C` works the other way round than `alpha`:\n",
    "\n",
    "$$\n",
    "C = \\frac{1}{\\alpha}\n",
    "$$\n",
    "\n",
    "- A small `C` (0.01) is a strong penalty: small weights, a simpler model, less overfitting, and with too small a value underfitting.\n",
    "- A large `C` (100) is a weak penalty: the model is almost free.\n",
    "\n",
    "`C` is chosen like `alpha`: with cross-validation on the training data.\n",
    "\n",
    "### 5.2 `l1_ratio`: which penalty\n",
    "\n",
    "With `l1_ratio=0`, the default, the penalty is L2: all weights become smaller. With `l1_ratio=1` it is L1: some weights become exactly 0, and the model selects features. Values between 0 and 1 give an elastic net. (Older code and many books set this with another parameter, `penalty=\"l1\"` or `penalty=\"l2\"`. It still works in current versions and gives a warning.)\n",
    "\n",
    "Because the penalty looks at the size of the weights, the features must be scaled, as in Topic 26.\n",
    "\n",
    "### 5.3 `solver` and `max_iter`: how the weights are found\n",
    "\n",
    "There is no direct formula for the best weights of a logistic regression, as there was for linear regression. They are found step by step, by a relative of gradient descent. The solver is the method, and `max_iter` is the limit of its steps.\n",
    "\n",
    "| Solver | Good for |\n",
    "| --- | --- |\n",
    "| `\"lbfgs\"` | the default: fast and reliable; L2 penalty only |\n",
    "| `\"liblinear\"` | small data sets; supports the L1 penalty |\n",
    "| `\"saga\"` | large data sets; supports L1, L2 and the elastic net |\n",
    "\n",
    "If the solver reaches `max_iter` before it has found the lowest point, scikit-learn prints a `ConvergenceWarning`. The two usual cures: scale the features (unscaled features make the valley long and narrow, as in Topic 24), or raise `max_iter`.\n",
    "\n",
    "### 5.4 `class_weight`: when one class is rare\n",
    "\n",
    "If 80 percent of the customers stay, a model can reach a high accuracy by mostly answering \"stays\". With `class_weight=\"balanced\"` every mistake on the rare class counts more in the loss, so the model pays more attention to it. It then finds more of the customers who leave, usually at the price of a lower accuracy. Part 8 shows it, and Topics 28 and 41 explain when that trade is worth it.\n",
    "\n",
    "### 5.5 What is learned, not set\n",
    "\n",
    "After `fit` the model holds the learned numbers, with an underscore at the end (Topic 21):\n",
    "\n",
    "| Attribute | Meaning |\n",
    "| --- | --- |\n",
    "| `model.coef_` | the weights, one for every feature |\n",
    "| `model.intercept_` | the intercept $w_0$ |\n",
    "| `model.classes_` | the classes, in the order of the columns of `predict_proba` |\n",
    "| `model.n_iter_` | the number of steps the solver needed |\n",
    "\n",
    "## 6. 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 whether a customer of a bank will leave.\n",
    "\n",
    "### 6.1 Step 1: read the file and look at it\n",
    "\n",
    "`Bank Customer Churn Prediction.csv` is a public data set of 10,000 customers of a bank."
   ],
   "id": "t27-001"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"Bank Customer Churn Prediction.csv\")\n",
    "\n",
    "print(df.shape)\n",
    "print(df.head(3).T)"
   ],
   "id": "t27-002"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| Column | Meaning |\n",
    "| --- | --- |\n",
    "| `customer_id` | the identification number of the customer |\n",
    "| `credit_score` | the credit score: how reliable the customer is with money |\n",
    "| `country` | France, Germany or Spain |\n",
    "| `gender` | Female or Male |\n",
    "| `age` | the age in years |\n",
    "| `tenure` | for how many years the customer has been with the bank |\n",
    "| `balance` | the money in the account |\n",
    "| `products_number` | how many products of the bank the customer uses |\n",
    "| `credit_card` | has a credit card: 1 or 0 |\n",
    "| `active_member` | is an active member: 1 or 0 |\n",
    "| `estimated_salary` | the estimated salary |\n",
    "| `churn` | the target: 1 if the customer left the bank, 0 if not |\n",
    "\n",
    "### 6.2 Step 2: check the columns\n",
    "\n",
    "Missing values, repeated rows, and the columns that are text (Topic 11):"
   ],
   "id": "t27-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": "t27-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Nothing is missing and nothing is repeated. Two columns are text and must be encoded.\n",
    "\n",
    "### 6.3 Step 3: drop the columns without information"
   ],
   "id": "t27-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.nunique())"
   ],
   "id": "t27-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`customer_id` has 10,000 values in 10,000 rows: an identification number (Topic 24). It names a customer and says nothing about him or her, so it is dropped."
   ],
   "id": "t27-007"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = df.drop(columns=[\"customer_id\"])\n",
    "\n",
    "print(df.shape)"
   ],
   "id": "t27-008"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.4 Step 4: look at the target\n",
    "\n",
    "In a classification project the target deserves a look of its own: how many rows does each class have?"
   ],
   "id": "t27-009"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df[\"churn\"].value_counts())\n",
    "print(df[\"churn\"].mean())"
   ],
   "id": "t27-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "2,037 of the 10,000 customers left. The mean of a column of 0 and 1 is the share of the ones: 20.37 percent left, and about 80 percent stayed. The two classes are not balanced.\n",
    "\n",
    "Keep this number in mind. A \"model\" that answers \"stays\" for every customer, without looking at anything, would be right in about 80 percent of the cases. That is the baseline: a real model has to beat it.\n",
    "\n",
    "### 6.5 Step 5: look for outliers\n",
    "\n",
    "The columns with continuous measurements (Topic 25):"
   ],
   "id": "t27-011"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df[[\"credit_score\", \"age\", \"balance\", \"estimated_salary\"]].describe().round(0))"
   ],
   "id": "t27-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The IQR rule on each of them:"
   ],
   "id": "t27-013"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for name in [\"credit_score\", \"age\", \"balance\", \"estimated_salary\"]:\n",
    "    q1 = df[name].quantile(0.25)\n",
    "    q3 = df[name].quantile(0.75)\n",
    "    low = q1 - 1.5 * (q3 - q1)\n",
    "    high = q3 + 1.5 * (q3 - q1)\n",
    "    print(name, low, high, ((df[name] < low) | (df[name] > high)).sum())"
   ],
   "id": "t27-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The rule marks 359 ages above 62 and 15 credit scores below 383. Mistakes, or real values? The oldest customer is 92 and the lowest credit score is 350: both are possible. A bank does have customers of 70 and 80 years. These are real values, so they stay (Topic 25). Nothing in this file looks like a typing mistake.\n",
    "\n",
    "### 6.6 Step 6: encode the text columns\n",
    "\n",
    "`gender` has two values. It becomes 0 and 1:"
   ],
   "id": "t27-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df[\"gender\"] = df[\"gender\"].map({\"Female\": 0, \"Male\": 1})\n",
    "\n",
    "print(df[\"gender\"].value_counts())"
   ],
   "id": "t27-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`country` has three values without an order. It gets one-hot encoding, with one column dropped (Topic 25):"
   ],
   "id": "t27-017"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.get_dummies(df, columns=[\"country\"], drop_first=True, dtype=int)\n",
    "\n",
    "print(df.columns.tolist())"
   ],
   "id": "t27-018"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "France, the first country in the alphabet, is the reference: a French customer has 0 in both new columns.\n",
    "\n",
    "### 6.7 Step 7: a look at the correlations"
   ],
   "id": "t27-019"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.corr()[\"churn\"].round(2).sort_values())"
   ],
   "id": "t27-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The age has the strongest relationship with leaving (older customers leave more often), then the German customers and the balance; active members and men leave less often. No single column is strongly correlated with the target. That is normal in real data: the model has to combine many weak hints.\n",
    "\n",
    "### 6.8 Step 8: split\n",
    "\n",
    "Change it and run: change `test_size` to `0.3` and run: 3,000 customers become test data."
   ],
   "id": "t27-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "X = df.drop(columns=[\"churn\"])\n",
    "y = df[\"churn\"]\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": "t27-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.9 Step 9: scale\n",
    "\n",
    "The scaler is fitted on the training data and applied to both parts (Topic 24). For logistic regression scaling matters twice: the model is regularized, and its solver walks down a loss."
   ],
   "id": "t27-023"
  },
  {
   "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": "t27-024"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The data is ready: 8,000 customers for training, 2,000 for the test, eleven features on the same scale.\n",
    "\n",
    "## 7. The first model\n",
    "\n",
    "### 7.1 Train and judge\n",
    "\n",
    "`LogisticRegression` is used like every model of scikit-learn. For a classifier, `score` returns the accuracy: the share of right predictions.\n",
    "\n",
    "Change it and run: write `LogisticRegression(C=0.001)` and run: both accuracies fall, because the penalty is too strong."
   ],
   "id": "t27-025"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import LogisticRegression\n",
    "\n",
    "model = LogisticRegression()\n",
    "model.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(model.score(X_train_scaled, y_train), 4))\n",
    "print(round(model.score(X_test_scaled, y_test), 4))"
   ],
   "id": "t27-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "An accuracy of 0.8114 on the training data and 0.811 on the test data: the model is right for 81 of 100 customers, and it does not overfit (the two numbers are almost equal).\n",
    "\n",
    "### 7.2 Compare with the baseline\n",
    "\n",
    "Is 0.811 good? The share of test customers who stayed:"
   ],
   "id": "t27-027"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(round(1 - y_test.mean(), 4))"
   ],
   "id": "t27-028"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Always answering \"stays\" would already be right for 0.8035 of the test customers. The model is better than that, but only by a little. An accuracy means nothing without its baseline, and with unbalanced classes the baseline is high. This is the main weakness of the accuracy, and the reason for the other measures of Topic 28. Part 9 will improve the model itself.\n",
    "\n",
    "### 7.3 `predict` and `predict_proba`\n",
    "\n",
    "`predict` returns the class of every row:"
   ],
   "id": "t27-029"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(model.predict(X_test_scaled)[:5])\n",
    "print(y_test[:5].tolist())"
   ],
   "id": "t27-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The first line is the prediction for the first five test customers, the second the truth. `predict_proba` returns the probabilities behind the predictions:"
   ],
   "id": "t27-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(model.classes_)\n",
    "print(model.predict_proba(X_test_scaled)[:5].round(3))"
   ],
   "id": "t27-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- Every row has two numbers that add up to 1: the probability of class 0 (stays) and of class 1 (leaves). `model.classes_` gives the order of the columns.\n",
    "- The first customer leaves with a probability of 0.233, the second with 0.077. Both are below 0.5, so `predict` says 0.\n",
    "- These numbers are the output of the sigmoid of Part 2.\n",
    "\n",
    "The probability of leaving for every test customer is the second column:"
   ],
   "id": "t27-033"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "leaving = model.predict_proba(X_test_scaled)[:, 1]\n",
    "\n",
    "print(leaving[:5].round(3))\n",
    "print(round(leaving.max(), 3))"
   ],
   "id": "t27-034"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`[:, 1]` takes the second column (Topic 8). A bank can sort its customers by this number and speak first with the ones at the top.\n",
    "\n",
    "### 7.4 The threshold\n",
    "\n",
    "`predict` uses the threshold 0.5. With the probabilities you can use your own. The cell counts how many customers the model marks as leaving, and its accuracy, for three thresholds:\n",
    "\n",
    "Change it and run: add `0.4` and `0.6` to the list and run."
   ],
   "id": "t27-035"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for threshold in [0.3, 0.5, 0.7]:\n",
    "    predicted = (leaving >= threshold).astype(int)\n",
    "    print(threshold, predicted.sum(), round((predicted == y_test).mean(), 4))"
   ],
   "id": "t27-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`(leaving >= threshold)` is `True` or `False` for every customer, `astype(int)` makes 1 and 0 of it, and `(predicted == y_test).mean()` is the share of right predictions: the accuracy, calculated by hand.\n",
    "\n",
    "A lower threshold marks many more customers as leaving. Whether that is better depends on what a missed customer costs and what a needless call costs: a question of Topic 28. The accuracy alone cannot answer it.\n",
    "\n",
    "### 7.5 The weights"
   ],
   "id": "t27-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(round(model.intercept_[0], 3))\n",
    "\n",
    "for name, weight in zip(X.columns, model.coef_[0]):\n",
    "    print(name, round(weight, 3))"
   ],
   "id": "t27-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`coef_` is a table with one row here, so `coef_[0]` is the list of the weights. The features are standardised, so the weights can be compared (Topic 24):\n",
    "\n",
    "- `age` has the largest positive weight: older customers leave more often.\n",
    "- `active_member` has the largest negative weight: active members stay.\n",
    "- `country_Germany` is positive: German customers leave more often than French ones, the reference.\n",
    "- `gender` is negative: men (1) leave less often than women (0).\n",
    "- `credit_card`, `estimated_salary` and `tenure` are close to 0: they hardly matter.\n",
    "\n",
    "The intercept is negative: for an average customer the score is clearly below 0, so the probability of leaving is far below 0.5. That is the 20 percent of Step 4, seen from inside the model.\n",
    "\n",
    "## 8. Changing the hyperparameters\n",
    "\n",
    "Now the parameters of Part 5, one at a time, on the same data. Change one thing, train again, and compare.\n",
    "\n",
    "### 8.1 `C`\n",
    "\n",
    "Every line shows `C`, the training accuracy and the test accuracy:"
   ],
   "id": "t27-039"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for C in [0.0001, 0.001, 0.01, 0.1, 1, 10, 100]:\n",
    "    model = LogisticRegression(C=C)\n",
    "    model.fit(X_train_scaled, y_train)\n",
    "    print(C, round(model.score(X_train_scaled, y_train), 4), round(model.score(X_test_scaled, y_test), 4))"
   ],
   "id": "t27-040"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- From `C = 0.1` upwards nothing changes: the penalty is weak, and the model is the same.\n",
    "- With `C = 0.0001` the penalty is so strong that all weights are pressed to almost 0. The test accuracy is 0.8035: exactly the baseline. The model has stopped using its features and answers \"stays\" for everybody. That is underfitting by too much regularization.\n",
    "- In between, `C = 0.01` is a little better than the default on the test data.\n",
    "\n",
    "The model has 11 features and 8,000 rows, so it hardly overfits, and regularization has little to do (the lesson of Topic 26). The choice of `C` is made with cross-validation on the training data, not with these test scores:"
   ],
   "id": "t27-041"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import cross_val_score\n",
    "\n",
    "for C in [0.001, 0.01, 0.1, 1, 10]:\n",
    "    scores = cross_val_score(LogisticRegression(C=C), X_train_scaled, y_train, cv=5)\n",
    "    print(C, round(scores.mean(), 4))"
   ],
   "id": "t27-042"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "All values from 0.01 upwards are equal within a few ten-thousandths. The default, `C = 1`, is a fine choice here.\n",
    "\n",
    "### 8.2 The L1 penalty\n",
    "\n",
    "With `l1_ratio=1` the penalty is L1, as in a Lasso. The default solver cannot work with it, so `solver=\"liblinear\"` is chosen too:\n",
    "\n",
    "Change it and run: change `C=0.01` to `C=0.005` and run: fewer weights are left."
   ],
   "id": "t27-043"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = LogisticRegression(l1_ratio=1, solver=\"liblinear\", C=0.01)\n",
    "model.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(model.score(X_test_scaled, y_test), 4))\n",
    "print((model.coef_[0] != 0).sum())\n",
    "print(X.columns[model.coef_[0] != 0].tolist())"
   ],
   "id": "t27-044"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Only 5 of the 11 weights are left, and the test accuracy is still 0.813. The model has selected the five features it needs most: the age, the gender, the balance, the active membership and Germany. A short model with the same accuracy is easier to explain to a bank.\n",
    "\n",
    "### 8.3 `max_iter`\n",
    "\n",
    "How many steps did the solver of the first model need?"
   ],
   "id": "t27-045"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = LogisticRegression()\n",
    "model.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(model.n_iter_)"
   ],
   "id": "t27-046"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It was finished long before the limit of 100. On unscaled features it is another story:"
   ],
   "id": "t27-047"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "unscaled = LogisticRegression()\n",
    "unscaled.fit(X_train, y_train)\n",
    "\n",
    "print(unscaled.n_iter_)\n",
    "print(unscaled.score(X_test, y_test) < model.score(X_test_scaled, y_test))"
   ],
   "id": "t27-048"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The first line shows that the solver used all 100 steps: it was stopped before it was finished. The second line asks whether the accuracy of this model is lower than that of the scaled model, and the answer is `True` (it is about 0.80 here, below even the baseline; the exact number of an unfinished model can differ a little from one computer to the next). When you run this cell it also shows a `ConvergenceWarning`. The warning itself names the two cures: scale the data, or raise `max_iter`. Scaling is the better one: it removes the cause.\n",
    "\n",
    "### 8.4 `class_weight`"
   ],
   "id": "t27-049"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "balanced = LogisticRegression(class_weight=\"balanced\")\n",
    "balanced.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(balanced.score(X_test_scaled, y_test), 4))\n",
    "print(model.predict(X_test_scaled).sum(), balanced.predict(X_test_scaled).sum(), y_test.sum())"
   ],
   "id": "t27-050"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The accuracy falls from 0.811 to 0.7195. The second line explains why: the first model marked 143 test customers as leaving, the balanced one marks many more, and 393 really left. The first model was careful and missed most of the customers who leave. The balanced model finds far more of them and gives many false alarms on the way, and every false alarm costs accuracy.\n",
    "\n",
    "Which model is better? With the accuracy alone, the first. For a bank that wants to find the customers who are about to leave, probably the second. This is exactly the point where the accuracy stops being enough, and where Topic 28 begins.\n",
    "\n",
    "## 9. A better model through better features\n",
    "\n",
    "The hyperparameters moved the accuracy by a few thousandths. In Topic 24 the large gains came from the features. Look at one of them again:"
   ],
   "id": "t27-051"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.groupby(\"products_number\")[\"churn\"].agg([\"mean\", \"count\"]).round(3))"
   ],
   "id": "t27-052"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`groupby` with `agg([\"mean\", \"count\"])` gives the share of customers who left and the number of customers, for every number of products (Topic 11).\n",
    "\n",
    "This is a surprise. Customers with 2 products leave least often (7.6 percent), customers with 1 product much more often (27.7 percent), and of the customers with 3 or 4 products almost all left. The column is a number, but its effect is not in order: more products do not simply mean more or less churn.\n",
    "\n",
    "A linear score can only say \"every product more adds the same amount\". It cannot follow down, then up. The cure is the one of Topic 25 for categories without order: one-hot encoding. The number of products is treated as four categories."
   ],
   "id": "t27-053"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.get_dummies(df, columns=[\"products_number\"], drop_first=True, dtype=int)\n",
    "\n",
    "print(df.columns.tolist())"
   ],
   "id": "t27-054"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The table changed, so the split, the scaling and the training are repeated. The same `random_state` gives the same customers in each part:"
   ],
   "id": "t27-055"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X = df.drop(columns=[\"churn\"])\n",
    "y = df[\"churn\"]\n",
    "\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\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": "t27-056"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = LogisticRegression()\n",
    "model.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(model.score(X_train_scaled, y_train), 4))\n",
    "print(round(model.score(X_test_scaled, y_test), 4))"
   ],
   "id": "t27-057"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| Model | Test accuracy |\n",
    "| --- | --- |\n",
    "| always \"stays\" (the baseline) | 0.8035 |\n",
    "| the first model, 11 features | 0.811 |\n",
    "| the best `C` | 0.8145 |\n",
    "| `products_number` one-hot encoded, 13 features | 0.843 |\n",
    "\n",
    "From 0.811 to 0.843: one look at a column and one line of encoding did more than every hyperparameter. The model is now four points above the baseline, not one. Understanding the data comes before tuning the model.\n",
    "\n",
    "## 10. More than two classes on the same data\n",
    "\n",
    "`LogisticRegression` handles three or more classes with the same code. To see it, the question is turned round for a moment: predict the country of a customer from the other columns. (The bank knows the country, of course. The exercise only shows how the model behaves with three classes.)"
   ],
   "id": "t27-058"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "raw = pd.read_csv(\"Bank Customer Churn Prediction.csv\")\n",
    "raw = raw.drop(columns=[\"customer_id\"])\n",
    "raw[\"gender\"] = raw[\"gender\"].map({\"Female\": 0, \"Male\": 1})\n",
    "\n",
    "X3 = raw.drop(columns=[\"country\"])\n",
    "y3 = raw[\"country\"]\n",
    "\n",
    "X3_train, X3_test, y3_train, y3_test = train_test_split(X3, y3, test_size=0.2, random_state=42)\n",
    "\n",
    "scaler3 = StandardScaler()\n",
    "X3_train_scaled = scaler3.fit_transform(X3_train)\n",
    "X3_test_scaled = scaler3.transform(X3_test)\n",
    "\n",
    "print(y3.value_counts())"
   ],
   "id": "t27-059"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The target is a text column with three values. It does not have to be encoded: scikit-learn accepts class names as they are."
   ],
   "id": "t27-060"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model3 = LogisticRegression()\n",
    "model3.fit(X3_train_scaled, y3_train)\n",
    "\n",
    "print(model3.classes_)\n",
    "print(model3.predict_proba(X3_test_scaled)[:3].round(3))\n",
    "print(model3.predict(X3_test_scaled)[:3])"
   ],
   "id": "t27-061"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- `classes_` has three entries, and `predict_proba` has three columns: one probability for every country, in that order. Every row adds up to 1. This is the softmax of Part 3.\n",
    "- `predict` answers with the country of the largest probability."
   ],
   "id": "t27-062"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(model3.coef_.shape)\n",
    "print(round(model3.score(X3_test_scaled, y3_test), 4))"
   ],
   "id": "t27-063"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`coef_` now has three rows of weights, one for every class: three scores, as Part 3 described. The accuracy is 0.536, and about half of all customers are French, so the baseline is about 0.5. The model is hardly better than always answering \"France\": these columns say little about where a customer lives. That is an honest result, and it shows again why a baseline is needed. The mechanics are the point here: three classes, three scores, three probabilities, one line of code.\n",
    "\n",
    "## 11. The workflow, step by step\n",
    "\n",
    "| Step | What is done | In this project |\n",
    "| --- | --- | --- |\n",
    "| 1. Look | shape, first rows, the meaning of the columns | 10,000 customers, 12 columns |\n",
    "| 2. Check | missing values, repeated rows, text columns | nothing missing; two text columns |\n",
    "| 3. Drop | columns without information | `customer_id` |\n",
    "| 4. Target | the share of each class, the baseline | 20 percent left; baseline about 0.80 |\n",
    "| 5. Outliers | find them, decide: mistake or real | real customers: kept |\n",
    "| 6. Encode | text to numbers | `gender` as 0 and 1, `country` one-hot |\n",
    "| 7. Split | training and test data | 8,000 and 2,000 |\n",
    "| 8. Scale | fit on the training data, transform both | `StandardScaler` |\n",
    "| 9. First model | a simple starting point, compared with the baseline | accuracy 0.811 |\n",
    "| 10. Tune | hyperparameters, with cross-validation | `C`, the penalty, `class_weight` |\n",
    "| 11. Improve | better features | `products_number` one-hot: 0.843 |\n",
    "| 12. Judge | the test score of the finished model | Topic 28 adds more measures |\n",
    "\n",
    "Compared with a regression project, two steps are new: looking at the classes of the target, and comparing the accuracy with a baseline.\n",
    "\n",
    "## 12. Common mistakes\n",
    "\n",
    "| Mistake | Why it is wrong | Right |\n",
    "| --- | --- | --- |\n",
    "| Using linear regression for a target of 0 and 1. | Its predictions leave the range from 0 to 1, and its loss does not fit classes. | Logistic regression. |\n",
    "| \"Logistic regression is a regression model.\" | It predicts classes. Only its inner score is a number. | It is a classifier. |\n",
    "| Reading an accuracy without the baseline. | With 80 percent in one class, 0.80 is reached without any model. | Compare with the share of the largest class. |\n",
    "| \"A large `C` is a strong regularization.\" | `C` is turned round: a small `C` is the strong penalty. | $C = \\frac{1}{\\alpha}$. |\n",
    "| Training without scaling. | The penalty treats the features unequally, and the solver may not finish. | Scale first, with a scaler fitted on the training data. |\n",
    "| Ignoring a `ConvergenceWarning`. | The weights are not the best ones yet. | Scale the data, or raise `max_iter`. |\n",
    "| `l1_ratio=1` with the default solver. | `lbfgs` supports only the L2 penalty: an error. | `solver=\"liblinear\"` or `\"saga\"`. |\n",
    "| Reading a weight as \"the change of the probability\". | A weight changes the log-odds, not the probability. | Sign and size; or the odds are multiplied by $e^{w}$. |\n",
    "| Thinking `predict_proba` gives one number per row. | It gives one column for every class. | `[:, 1]` is the probability of class 1. |\n",
    "| Choosing `C` or the threshold with the test data. | The test data then takes part in building the model. | Cross-validation on the training data. |\n",
    "| Giving a numerical column with an effect that is not in order to a linear model as it is. | One weight cannot go down and up again. | One-hot encode it, as `products_number`. |\n",
    "| Expecting `class_weight=\"balanced\"` to raise the accuracy. | It finds more of the rare class and usually lowers the accuracy. | Judge it with the measures of Topic 28. |\n",
    "\n",
    "## 13. Solved problems\n",
    "\n",
    "Sixteen problems. The first four are short and solved by hand. Problems 5 to 16 are one project on `Bank Customer Churn Prediction.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 the better encoding from the start and another split.\n",
    "\n",
    "For the problems by hand: $e^{-3} = 0.050$, $e^{-1} = 0.368$, $e^{1} = 2.718$, $e^{3} = 20.086$.\n",
    "\n",
    "Problem 1. The sigmoid by hand\n",
    "\n",
    "Calculate the sigmoid of 3 and of $-3$. What do the two results add up to?\n",
    "\n",
    "Idea. $\\text{sigmoid}(z) = \\frac{1}{1 + e^{-z}}$ (Part 2).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "z = 3:\\quad & \\frac{1}{1 + e^{-3}} = \\frac{1}{1 + 0.050} \\\\[4pt]\n",
    "& = \\frac{1}{1.050} = 0.952 \\\\[8pt]\n",
    "z = -3:\\quad & \\frac{1}{1 + e^{3}} = \\frac{1}{1 + 20.086} \\\\[4pt]\n",
    "& = \\frac{1}{21.086} = 0.047\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: the two results add up to 1 (the small difference comes from rounding), because the sigmoid is symmetric: $\\text{sigmoid}(-z) = 1 - \\text{sigmoid}(z)$. A score of 3 is \"almost sure yes\", a score of $-3$ \"almost sure no\".\n",
    "\n",
    "Problem 2. From the features to a class\n",
    "\n",
    "A model for churn is $z = -3 + 0.5 \\times \\text{age} + 1.0 \\times \\text{german}$, with the age in decades and `german` 1 or 0. Predict for a German customer of 40 years (age = 4).\n",
    "\n",
    "Idea. First the score, then the sigmoid, then the threshold 0.5 (Part 2).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "z &= -3 + 0.5 \\times 4 + 1.0 \\times 1 \\\\\n",
    "&= -3 + 2 + 1 = 0 \\\\[8pt]\n",
    "p &= \\frac{1}{1 + e^{0}} = \\frac{1}{2} = 0.5\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: the score is exactly 0, so the probability is exactly 0.5: this customer lies on the decision boundary. With the rule \"class 1 if $p$ is at least 0.5\" the prediction is 1. One year more and the score would be positive.\n",
    "\n",
    "Problem 3. The softmax by hand\n",
    "\n",
    "A model for three classes gives the scores 3, 1 and 1. Calculate the three probabilities.\n",
    "\n",
    "Idea. $e$ to the power of every score, divided by the sum (Part 3).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& e^{3} = 20.086 \\qquad e^{1} = 2.718 \\\\[4pt]\n",
    "& \\text{sum} = 20.086 + 2.718 + 2.718 = 25.522 \\\\[8pt]\n",
    "p_1 &= \\frac{20.086}{25.522} = 0.787 \\\\[6pt]\n",
    "p_2 &= \\frac{2.718}{25.522} = 0.106 \\\\[6pt]\n",
    "p_3 &= \\frac{2.718}{25.522} = 0.106\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: the class with the largest score gets most of the probability, the two classes with equal scores get equal shares, and the three numbers add up to 1 (0.999 after rounding). The model answers with class 1.\n",
    "\n",
    "Problem 4. The cross-entropy by hand\n",
    "\n",
    "A customer stayed ($y = 0$). Model A gave a probability of leaving of 0.2, Model B of 0.9. Calculate the loss of each. Use $\\ln(0.8) = -0.223$ and $\\ln(0.1) = -2.303$.\n",
    "\n",
    "Idea. For $y = 0$ the loss is $-\\ln(1 - p)$: minus the logarithm of the probability given to the true class (Part 4).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{Model A:}\\quad & -\\ln(1 - 0.2) = -\\ln(0.8) = 0.223 \\\\[6pt]\n",
    "\\text{Model B:}\\quad & -\\ln(1 - 0.9) = -\\ln(0.1) = 2.303\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: Model A gave the true class, \"stays\", a probability of 0.8 and pays little. Model B gave it only 0.1 and pays ten times as much. The cross-entropy punishes being sure of the wrong answer.\n",
    "\n",
    "Problem 5. Read and check\n",
    "\n",
    "Read the file. Print its shape, the number of missing values and the number of repeated rows.\n",
    "\n",
    "Idea. The first two steps of the workflow (Part 6)."
   ],
   "id": "t27-064"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"Bank Customer Churn Prediction.csv\")\n",
    "\n",
    "print(df.shape)\n",
    "print(df.isna().sum().sum(), df.duplicated().sum())"
   ],
   "id": "t27-065"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: before any model, know what is in the table. Nothing has to be repaired here.\n",
    "\n",
    "Problem 6. Drop and look at the target\n",
    "\n",
    "Drop `customer_id`. Print the share of customers who left, rounded to 4 decimals.\n",
    "\n",
    "Idea. An identification number carries no information; the mean of a column of 0 and 1 is the share of the ones (Part 6)."
   ],
   "id": "t27-066"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = df.drop(columns=[\"customer_id\"])\n",
    "\n",
    "print(round(df[\"churn\"].mean(), 4))"
   ],
   "id": "t27-067"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: about one customer in five left. The classes are not balanced, so the accuracy of a model must later be compared with a baseline of about 0.80.\n",
    "\n",
    "Problem 7. Encode\n",
    "\n",
    "Encode `gender` as 0 (Female) and 1 (Male). One-hot encode `country` and `products_number` with `drop_first=True`. Print the number of columns.\n",
    "\n",
    "Idea. Two values: a dictionary. Categories without order, and a number whose effect is not in order: one-hot encoding (Parts 6 and 9)."
   ],
   "id": "t27-068"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df[\"gender\"] = df[\"gender\"].map({\"Female\": 0, \"Male\": 1})\n",
    "df = pd.get_dummies(df, columns=[\"country\", \"products_number\"], drop_first=True, dtype=int)\n",
    "\n",
    "print(len(df.columns))"
   ],
   "id": "t27-069"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `get_dummies` takes a list of columns and encodes them in one line. 14 columns: 13 features and the target.\n",
    "\n",
    "Problem 8. 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 6)."
   ],
   "id": "t27-070"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "X = df.drop(columns=[\"churn\"])\n",
    "y = df[\"churn\"]\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": "t27-071"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: a quarter of the customers is put aside. The model will not see them before it is finished.\n",
    "\n",
    "Problem 9. Scale\n",
    "\n",
    "Scale the features with a `StandardScaler` 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": "t27-072"
  },
  {
   "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": "t27-073"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: logistic regression is regularized and is trained step by step. Both need features on the same scale.\n",
    "\n",
    "Problem 10. The baseline\n",
    "\n",
    "Print the accuracy of a \"model\" that answers 0 (stays) for every test customer, rounded to 4 decimals.\n",
    "\n",
    "Idea. It is right for every customer who stayed: the share of zeros in `y_test` (Part 7)."
   ],
   "id": "t27-074"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(round(1 - y_test.mean(), 4))"
   ],
   "id": "t27-075"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: this is the number to beat. A model with a lower accuracy has learned nothing useful.\n",
    "\n",
    "Problem 11. Train and judge\n",
    "\n",
    "Train a `LogisticRegression` and print its training accuracy and its test accuracy, rounded to 4 decimals.\n",
    "\n",
    "Idea. `fit`, then `score`, which is the accuracy for a classifier (Part 7)."
   ],
   "id": "t27-076"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import LogisticRegression\n",
    "\n",
    "model = LogisticRegression()\n",
    "model.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(model.score(X_train_scaled, y_train), 4))\n",
    "print(round(model.score(X_test_scaled, y_test), 4))"
   ],
   "id": "t27-077"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the two accuracies are close together, so the model does not overfit, and the test accuracy lies about four points above the baseline of Problem 10.\n",
    "\n",
    "Problem 12. Probabilities\n",
    "\n",
    "Print the probabilities of the first three test customers, rounded to 3 decimals, and the predicted classes of the same customers.\n",
    "\n",
    "Idea. `predict_proba` gives a column for every class; `predict` compares the second column with 0.5 (Part 7)."
   ],
   "id": "t27-078"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(model.predict_proba(X_test_scaled)[:3].round(3))\n",
    "print(model.predict(X_test_scaled)[:3])"
   ],
   "id": "t27-079"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: every row of probabilities adds up to 1. A customer is predicted as 1 exactly when the second number is at least 0.5.\n",
    "\n",
    "Problem 13. Another threshold\n",
    "\n",
    "Take the probability of leaving of every test customer. With the threshold 0.4, how many customers are marked as leaving, and what is the accuracy?\n",
    "\n",
    "Idea. `[:, 1]` is the probability of class 1; compare it with the threshold yourself (Part 7)."
   ],
   "id": "t27-080"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "leaving = model.predict_proba(X_test_scaled)[:, 1]\n",
    "predicted = (leaving >= 0.4).astype(int)\n",
    "\n",
    "print(predicted.sum())\n",
    "print(round((predicted == y_test).mean(), 4))"
   ],
   "id": "t27-081"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: a lower threshold marks more customers. The accuracy hardly moves, but the model now catches customers it missed before: a difference the accuracy does not show.\n",
    "\n",
    "Problem 14. Choosing C\n",
    "\n",
    "Compare the values 0.001, 0.01, 0.1, 1 and 10 for `C` with a 5-fold cross-validation on the training data. Print every `C` with its mean accuracy, rounded to 4 decimals.\n",
    "\n",
    "Idea. A hyperparameter is chosen with cross-validation, never with the test data (Part 8)."
   ],
   "id": "t27-082"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import cross_val_score\n",
    "\n",
    "for C in [0.001, 0.01, 0.1, 1, 10]:\n",
    "    scores = cross_val_score(LogisticRegression(C=C), X_train_scaled, y_train, cv=5)\n",
    "    print(C, round(scores.mean(), 4))"
   ],
   "id": "t27-083"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: a very small `C` is too strong a penalty and lowers the accuracy. From 0.1 upwards the values are practically equal, so the default `C = 1` can stay.\n",
    "\n",
    "Problem 15. The L1 penalty\n",
    "\n",
    "Train a model with `l1_ratio=1`, `solver=\"liblinear\"` and `C=0.01`. Print its test accuracy and the number of weights that are not 0.\n",
    "\n",
    "Idea. The L1 penalty sets weights to exactly 0, as a Lasso does (Part 8)."
   ],
   "id": "t27-084"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "lasso_like = LogisticRegression(l1_ratio=1, solver=\"liblinear\", C=0.01)\n",
    "lasso_like.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(lasso_like.score(X_test_scaled, y_test), 4))\n",
    "print((lasso_like.coef_[0] != 0).sum())"
   ],
   "id": "t27-085"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: several of the 13 weights are exactly 0, and the accuracy stays close to that of the full model. The model has chosen its features itself.\n",
    "\n",
    "Problem 16. Balanced classes\n",
    "\n",
    "Train a model with `class_weight=\"balanced\"`. Print its test accuracy, then the number of test customers that the first model and this model mark as leaving, and the number who really left.\n",
    "\n",
    "Idea. The rare class gets more weight in the loss (Part 8)."
   ],
   "id": "t27-086"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "balanced = LogisticRegression(class_weight=\"balanced\")\n",
    "balanced.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(balanced.score(X_test_scaled, y_test), 4))\n",
    "print(model.predict(X_test_scaled).sum(), balanced.predict(X_test_scaled).sum(), y_test.sum())"
   ],
   "id": "t27-087"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the accuracy is lower, and the balanced model marks far more customers as leaving than the first model did. It finds more of the customers who leave and gives more false alarms. Which model is better depends on the purpose, and the accuracy cannot decide it: Topic 28.\n",
    "\n",
    "## 16. Summary\n",
    "\n",
    "|  | Formula | Meaning |\n",
    "| --- | --- | --- |\n",
    "| Score | $z = w_0 + w_1 x_1 + \\dots + w_p x_p$ | a weighted sum, as in linear regression |\n",
    "| Sigmoid | $p = \\frac{1}{1 + e^{-z}}$ | turns the score into a probability (two classes) |\n",
    "| Softmax | $p_k = \\frac{e^{z_k}}{\\text{sum of all } e^{z}}$ | probabilities for three or more classes |\n",
    "| Log-odds | $\\ln \\frac{p}{1 - p} = z$ | what the model assumes to be linear |\n",
    "| Cross-entropy | $-\\left[ y \\ln(p) + (1 - y) \\ln(1 - p) \\right]$ | the loss: minus the logarithm of the probability of the true class |\n",
    "| Decision | class 1 if $p \\ge 0.5$ | the same as $z \\ge 0$ |\n",
    "\n",
    "| Code | What it does |\n",
    "| --- | --- |\n",
    "| `model = LogisticRegression()` | creates the model (regularized, `C=1`) |\n",
    "| `model.fit(X_train_scaled, y_train)` | learns the weights |\n",
    "| `model.score(X_test_scaled, y_test)` | the accuracy |\n",
    "| `model.predict(X_test_scaled)` | the classes |\n",
    "| `model.predict_proba(X_test_scaled)[:, 1]` | the probability of class 1 |\n",
    "| `model.coef_`, `model.intercept_`, `model.classes_` | the weights, the intercept, the classes |\n",
    "| `LogisticRegression(C=0.01)` | a stronger regularization |\n",
    "| `LogisticRegression(l1_ratio=1, solver=\"liblinear\")` | the L1 penalty: some weights become 0 |\n",
    "| `LogisticRegression(class_weight=\"balanced\")` | more weight for the rare class |\n",
    "| `1 - y_test.mean()` | the baseline for a target of 0 and 1 with more zeros |\n",
    "\n",
    "### Rules to keep\n",
    "\n",
    "1. Logistic regression is a classifier. It predicts a probability and turns it into a class.\n",
    "2. A linear score, then the sigmoid (two classes) or the softmax (more classes).\n",
    "3. It is trained with the cross-entropy and judged, in this lesson, with the accuracy.\n",
    "4. Look at the classes of the target first, and compare every accuracy with the baseline.\n",
    "5. Scale the features: the model is regularized, and its solver walks down a loss.\n",
    "6. A small `C` is a strong regularization. Choose it with cross-validation.\n",
    "7. Better features beat better hyperparameters.\n",
    "\n",
    "### What comes next\n",
    "\n",
    "This lesson judged its models with the accuracy and found its limits twice: a model that is barely above the baseline, and a balanced model that is \"worse\" and still more useful. Topic 28, classification metrics, gives the tools to see what the accuracy hides: the confusion matrix, precision, recall, the F1-score and the ROC curve.\n",
    "\n",
    "Next: the practice notebook (topic-27-practice.ipynb), then Topic 28: Classification metrics."
   ],
   "id": "t27-088"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
