{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 28: Classification metrics\n",
    "\n",
    "Asiman Data School, Module 3: Comprehensive Machine Learning. Week 14, Thursday.\n",
    "\n",
    "This notebook follows the lesson page. Read the text, run the cell under it with Shift + Enter, then change the values in the cell and run it again. Seeing the output change is how the rules become clear.\n",
    "\n",
    "Run the cells from top to bottom. A cell that draws a chart shows it under the cell when you run it. The practice problems are in a separate notebook, topic-28-practice.ipynb.\n",
    "\n",
    "The cells continue from each other: a cell uses the variables of the cells above it. Parts 7 to 9 are one project, so start at the first cell of Part 7. 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. Why one measure is not enough\n",
    "2. The four outcomes\n",
    "3. The confusion matrix\n",
    "4. The two types of error\n",
    "5. The measures\n",
    "6. Which measure for which task\n",
    "7. The project: from the file to the model\n",
    "8. The measures in code\n",
    "9. The ROC curve, the AUC and the Gini coefficient\n",
    "10. The workflow, step by step\n",
    "11. Common mistakes\n",
    "12. Solved problems\n",
    "13. Practice (in topic-28-practice.ipynb)\n",
    "14. Check yourself (on the website)\n",
    "15. Summary"
   ],
   "id": "t28-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction: what the accuracy hides\n",
    "\n",
    "What matters most in this lesson. Five things matter most today. First, a classifier can be wrong in two ways, and the confusion matrix shows both: learn to read its four cells, TN, FP, FN and TP. Second, precision and recall: precision divides by what the model called positive, recall by what is really positive. Third, the choice: ask which mistake costs more, a miss (watch the recall) or a false alarm (watch the precision), and do not trust the accuracy alone when the classes are unbalanced. Fourth, the threshold trades precision for recall. Fifth, the ROC curve shows a model at all thresholds: its area is the AUC, and the Gini coefficient is $2 \\times \\text{AUC} - 1$.\n",
    "\n",
    "The specificity, the balanced accuracy and the report of scikit-learn are tools around these five ideas.\n",
    "\n",
    "The eighth lesson of Module 3. Topic 27 built a classifier and judged it with one number, the accuracy. Twice that number was not enough: a model was barely above \"always answer stays\", and a model with a lower accuracy looked more useful to the bank. This lesson gives the other measures of classification, and the rule for choosing among them.\n",
    "\n",
    "The lesson has two halves. The first is done on paper: the four outcomes of a prediction, the confusion matrix, the two types of error, the measures that are calculated from them, and which measure fits which task. The second half is a project on the data file of Topic 27, `Bank Customer Churn Prediction.csv`: every step from reading the file to the trained model once more, as a revision, and then every measure in code. The ROC curve, its area (AUC) and the Gini coefficient come at the end.\n",
    "\n",
    "You need: logistic regression, `predict` and `predict_proba` (Topic 27), the train/test split (Topic 23), scaling (Topic 24), encoding (Topic 25), and fractions.\n",
    "\n",
    "| Word | Meaning |\n",
    "| --- | --- |\n",
    "| Positive class | the class the model is looking for, coded 1 (the customer leaves, the patient is sick) |\n",
    "| Negative class | the other class, coded 0 |\n",
    "| True positive (TP) | the model said positive, and it is positive |\n",
    "| True negative (TN) | the model said negative, and it is negative |\n",
    "| False positive (FP) | the model said positive, but it is negative: a false alarm |\n",
    "| False negative (FN) | the model said negative, but it is positive: a miss |\n",
    "| Confusion matrix | the table of these four counts |\n",
    "| Accuracy | the share of all predictions that are right |\n",
    "| Precision | of the rows the model called positive, the share that are positive |\n",
    "| Recall | of the rows that are positive, the share the model found |\n",
    "| F1-score | one number made of precision and recall |\n",
    "| ROC curve | recall against the rate of false alarms, for every threshold |\n",
    "| AUC | the area under the ROC curve |\n",
    "\n",
    "## 1. Why one measure is not enough\n",
    "\n",
    "### 1.1 What the accuracy hides\n",
    "\n",
    "The accuracy counts right answers and nothing else. It does not say which answers were wrong, and in real tasks the two kinds of mistake are rarely equally bad.\n",
    "\n",
    "Two results of Topic 27 showed it:\n",
    "\n",
    "- The first model had an accuracy of 0.811. Always answering \"stays\" gave 0.8035. Almost the same number, for a model and for no model at all.\n",
    "- The model with `class_weight=\"balanced\"` had a lower accuracy and found many more of the customers who leave. For a bank that wants to keep its customers, it was the more useful model.\n",
    "\n",
    "A regression model has its error in one direction of meaning: the prediction is too high or too low by some amount. A classifier is right or wrong, and it can be wrong in two different ways. Telling a healthy person \"you are sick\" and telling a sick person \"you are healthy\" are both one mistake for the accuracy. For the person they are not the same at all.\n",
    "\n",
    "### 1.2 Many measures, one table\n",
    "\n",
    "There are many measures for classification: accuracy, precision, recall, specificity, F1-score, balanced accuracy, ROC-AUC, and more. They look like a long list, but all of them come from one small table with four numbers. Learn the table, and every measure is a fraction of its cells.\n",
    "\n",
    "## 2. The four outcomes\n",
    "\n",
    "### 2.1 Positive and negative\n",
    "\n",
    "First decide which class is the positive one. It is the class the model is looking for, and it is coded 1. \"Positive\" does not mean \"good\": in medicine a positive test means the disease was found. Usually the positive class is the rare and important one: the customer who leaves, the payment that is a fraud, the patient who is sick.\n",
    "\n",
    "### 2.2 A class of 20 students\n",
    "\n",
    "A class has 20 students. At the end of the year 12 passed and 8 failed. A model predicted the result of every student at the start of the year. Now the predictions are compared with the truth:\n",
    "\n",
    "- of the 12 students who passed, the model predicted \"passes\" for 10, and \"fails\" for the other 2;\n",
    "- of the 8 students who failed, the model predicted \"fails\" for 5, and \"passes\" for the other 3.\n",
    "\n",
    "The positive class is \"passes\". Every student falls into exactly one of four groups:\n",
    "\n",
    "| Group | The truth | The model said | Students |\n",
    "| --- | --- | --- | --- |\n",
    "| True positive (TP) | passed | passes | 10 |\n",
    "| False negative (FN) | passed | fails | 2 |\n",
    "| True negative (TN) | failed | fails | 5 |\n",
    "| False positive (FP) | failed | passes | 3 |\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{TP} + \\text{FN} + \\text{TN} + \\text{FP} &= 10 + 2 + 5 + 3 \\\\\n",
    "&= 20\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "All 20 students are in the table, each one once.\n",
    "\n",
    "### 2.3 How to read the names\n",
    "\n",
    "Every name has two words, and each word answers one question:\n",
    "\n",
    "- The second word is what the model said: positive or negative.\n",
    "- The first word says whether the model was right: true or false.\n",
    "\n",
    "So a false positive is: the model said positive, and that was false. The student really failed. A false negative: the model said negative, and that was false. The student really passed.\n",
    "\n",
    "Read the name from the back: first what the model said, then whether it was right.\n",
    "\n",
    "| Name | The model said | Was it right? | So the truth is |\n",
    "| --- | --- | --- | --- |\n",
    "| True positive | positive | yes | positive |\n",
    "| True negative | negative | yes | negative |\n",
    "| False positive | positive | no | negative |\n",
    "| False negative | negative | no | positive |\n",
    "\n",
    "Two sums are worth seeing at once:\n",
    "\n",
    "|  | Sum | Who |\n",
    "| --- | --- | --- |\n",
    "| really positive | $\\text{TP} + \\text{FN} = 10 + 2 = 12$ | the students who passed |\n",
    "| really negative | $\\text{TN} + \\text{FP} = 5 + 3 = 8$ | the students who failed |\n",
    "| predicted positive | $\\text{TP} + \\text{FP} = 10 + 3 = 13$ | the model said \"passes\" |\n",
    "| predicted negative | $\\text{TN} + \\text{FN} = 5 + 2 = 7$ | the model said \"fails\" |\n",
    "\n",
    "The model said \"passes\" 13 times, although only 12 students passed, and it was right in 10 of the 13.\n",
    "\n",
    "## 3. The confusion matrix\n",
    "\n",
    "### 3.1 Drawing it\n",
    "\n",
    "The four counts are written as a table with two rows and two columns, the confusion matrix. It shows where the model confuses the classes.\n",
    "\n",
    "- The rows are the truth (the actual class).\n",
    "- The columns are the prediction of the model.\n",
    "- Class 0, the negative class, comes first, in the rows and in the columns.\n",
    "\n",
    "This is the layout of scikit-learn, and this lesson uses it everywhere.\n",
    "\n",
    "As a plain table:\n",
    "\n",
    "|  | Predicted 0 (fails) | Predicted 1 (passes) | Sum |\n",
    "| --- | --- | --- | --- |\n",
    "| Actual 0 (failed) | $\\text{TN} = 5$ | $\\text{FP} = 3$ | 8 |\n",
    "| Actual 1 (passed) | $\\text{FN} = 2$ | $\\text{TP} = 10$ | 12 |\n",
    "| Sum | 7 | 13 | 20 |\n",
    "\n",
    "### 3.2 Reading it\n",
    "\n",
    "- The diagonal from the top left to the bottom right holds the right predictions: TN and TP. Here $5 + 10 = 15$.\n",
    "- The other two cells hold the mistakes: FP and FN. Here $3 + 2 = 5$.\n",
    "- The sum of a row is the number of rows that really belong to the class: 8 failed, 12 passed.\n",
    "- The sum of a column is the number of times the model said this class: 7 times \"fails\", 13 times \"passes\".\n",
    "\n",
    "A perfect model has numbers only on the diagonal.\n",
    "\n",
    "### 3.3 Tricks to remember what stands where\n",
    "\n",
    "1. Rows are real. The rows are the reality, the columns are the prediction. (In scikit-learn the truth also comes first inside the brackets: `confusion_matrix(y_test, predicted)`.)\n",
    "2. Zero comes first. Class 0 is the first row and the first column, as numbers are counted: 0, then 1.\n",
    "3. True is on the diagonal. Both \"true\" cells lie on the diagonal: TN at the top left (0 and 0), TP at the bottom right (1 and 1).\n",
    "4. The column gives the second word. Everything in the column \"predicted 1\" ends with \"positive\" (FP, TP). Everything in the column \"predicted 0\" ends with \"negative\" (TN, FN).\n",
    "5. Read it like a text. Line by line, from left to right: TN, FP, FN, TP. This is the order in which scikit-learn gives the four numbers.\n",
    "\n",
    "A warning: some books and websites put the positive class first, or the prediction in the rows. The four numbers are the same; only their places change. Always read the labels of a confusion matrix before reading its numbers.\n",
    "\n",
    "## 4. The two types of error\n",
    "\n",
    "### 4.1 Type I and Type II\n",
    "\n",
    "The two wrong cells have names of their own:\n",
    "\n",
    "|  | The model said | The truth | Also called |\n",
    "| --- | --- | --- | --- |\n",
    "| Type I error | positive | negative | false positive, false alarm |\n",
    "| Type II error | negative | positive | false negative, miss |\n",
    "\n",
    "In the class of 20 students the model made 3 errors of Type I (it said \"passes\" for students who failed) and 2 errors of Type II (it said \"fails\" for students who passed).\n",
    "\n",
    "The names come from statistics. In Topic 19 a Type I error was rejecting a null hypothesis that is true, and a Type II error was keeping one that is false. It is the same idea: \"nothing special\" is the negative class.\n",
    "\n",
    "### 4.2 Cases\n",
    "\n",
    "| Task (positive class) | Type I error: false positive | Type II error: false negative |\n",
    "| --- | --- | --- |\n",
    "| Medical test (sick) | a healthy person is told \"sick\": worry, more tests | a sick person is told \"healthy\": no treatment |\n",
    "| Spam filter (spam) | a good e-mail lands in the spam folder | a spam e-mail lands in the inbox |\n",
    "| Bank, churn (leaves) | a loyal customer gets a call or an offer he did not need | a customer leaves and nobody tried to keep him |\n",
    "| Bank, fraud (fraud) | an honest payment is blocked | a fraud goes through |\n",
    "| Fire alarm (fire) | the alarm rings without a fire | there is a fire and the alarm is silent |\n",
    "| Court (guilty) | an innocent person is convicted | a guilty person goes free |\n",
    "\n",
    "Which error is worse? It depends on the task. For the medical test and the fire alarm the miss is far worse. For the spam filter and the court the false alarm is worse. The choice of the measure follows from this question, and Part 6 returns to it.\n",
    "\n",
    "### 4.3 How to remember which is which\n",
    "\n",
    "- The boy who cried wolf. In the old story the boy shouts \"wolf!\" and there is no wolf. The villagers believe him: a false alarm, Type I. Later a wolf really comes, he shouts again, and the villagers do not believe him: a miss, Type II. The two errors happen in the order of their numbers.\n",
    "- Count the strokes. The letter P of \"false Positive\" has one vertical stroke: Type I. The letter N of \"false Negative\" has two vertical strokes: Type II.\n",
    "\n",
    "## 5. The measures\n",
    "\n",
    "Every measure is a fraction made of the four counts. The class of 20 students is used for all of them: $\\text{TP} = 10$, $\\text{TN} = 5$, $\\text{FP} = 3$, $\\text{FN} = 2$.\n",
    "\n",
    "### 5.1 Accuracy\n",
    "\n",
    "The share of all predictions that are right:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{accuracy} &= \\frac{\\text{TP} + \\text{TN}}{\\text{TP} + \\text{TN} + \\text{FP} + \\text{FN}} \\\\[8pt]\n",
    "&= \\frac{10 + 5}{20} = \\frac{15}{20} = 0.75\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "The model is right for 75 percent of the students. The accuracy uses the diagonal of the matrix, divided by everything.\n",
    "\n",
    "### 5.2 Precision\n",
    "\n",
    "Of the students for whom the model said \"passes\", how many really passed?\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{precision} &= \\frac{\\text{TP}}{\\text{TP} + \\text{FP}} \\\\[8pt]\n",
    "&= \\frac{10}{10 + 3} = \\frac{10}{13} = 0.769\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "When this model says \"passes\", it is right in 77 of 100 cases. Precision answers the question: can I trust a positive answer of the model? It is lowered by false positives.\n",
    "\n",
    "### 5.3 Recall\n",
    "\n",
    "Of the students who really passed, how many did the model find?\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{recall} &= \\frac{\\text{TP}}{\\text{TP} + \\text{FN}} \\\\[8pt]\n",
    "&= \\frac{10}{10 + 2} = \\frac{10}{12} = 0.833\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "The model found 83 percent of the students who passed. Recall answers the question: how many of the positives did the model find? It is lowered by false negatives. Recall has two other names: sensitivity (in medicine) and true positive rate (for the ROC curve).\n",
    "\n",
    "### 5.4 Specificity\n",
    "\n",
    "The same as recall, for the negative class. Of the students who really failed, how many did the model recognise?\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{specificity} &= \\frac{\\text{TN}}{\\text{TN} + \\text{FP}} \\\\[8pt]\n",
    "&= \\frac{5}{5 + 3} = \\frac{5}{8} = 0.625\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "The model recognised only 62.5 percent of the students who failed. Its other name is the true negative rate.\n",
    "\n",
    "### 5.5 Where each measure lives in the matrix\n",
    "\n",
    "The picture for this part is on the lesson page: the matrix of the 20 students once for every measure, with the cells that the measure uses in colour.\n",
    "\n",
    "- Precision is a column: the column of the positive predictions. TP at the bottom, divided by the sum of the column.\n",
    "- Recall is a row: the row of the real positives. TP on the right, divided by the sum of the row.\n",
    "- Specificity is the other row: the row of the real negatives.\n",
    "\n",
    "### 5.6 Tricks to remember precision and recall\n",
    "\n",
    "- PREcision looks at what the model PREdicted as positive. REcall looks at what is REally positive.\n",
    "- Both have TP on top. Only the second number below differs: precision adds the false Positives, recall adds the false negatives.\n",
    "- Precision: \"when the model raises its hand, is it right?\" Recall: \"of all the cases where it should have raised its hand, how often did it?\"\n",
    "\n",
    "### 5.7 Precision and recall pull against each other\n",
    "\n",
    "A model that says \"positive\" for everybody has a recall of 1: it misses nobody. Its precision is poor, because most of its alarms are false. A model that says \"positive\" only when it is completely sure has a high precision, and it misses many positives: a low recall.\n",
    "\n",
    "Between these two ends, raising one usually lowers the other. That is why neither is enough alone, and why they are reported together.\n",
    "\n",
    "### 5.8 The F1-score\n",
    "\n",
    "The F1-score makes one number of the two. It is their harmonic mean:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "F_1 &= \\frac{2 \\times \\text{precision} \\times \\text{recall}}{\\text{precision} + \\text{recall}} \\\\[8pt]\n",
    "&= \\frac{2 \\times 0.769 \\times 0.833}{0.769 + 0.833} \\\\[8pt]\n",
    "&= \\frac{1.281}{1.602} = 0.800\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "The same number comes directly from the counts:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "F_1 &= \\frac{2 \\times \\text{TP}}{2 \\times \\text{TP} + \\text{FP} + \\text{FN}} \\\\[8pt]\n",
    "&= \\frac{2 \\times 10}{2 \\times 10 + 3 + 2} = \\frac{20}{25} = 0.8\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why not the ordinary mean? Take a model with a precision of 1.0 and a recall of 0.1: it is sure of its few alarms and misses nine positives in ten.\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{ordinary mean} &= \\frac{1.0 + 0.1}{2} = 0.55 \\\\[8pt]\n",
    "F_1 &= \\frac{2 \\times 1.0 \\times 0.1}{1.0 + 0.1} = \\frac{0.2}{1.1} = 0.182\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "The ordinary mean calls this model \"medium\". The F1-score calls it poor, which is right. The harmonic mean stays close to the smaller of the two numbers: the F1-score is high only when precision and recall are both high.\n",
    "\n",
    "Notice also what is missing in the F1-score: the true negatives. It looks only at the positive class. That makes it useful when the negative class is very large.\n",
    "\n",
    "### 5.9 The balanced accuracy\n",
    "\n",
    "The mean of the recall of the two classes:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\text{balanced accuracy} \\\\[4pt]\n",
    "&= \\frac{\\text{recall} + \\text{specificity}}{2} \\\\[8pt]\n",
    "&= \\frac{0.833 + 0.625}{2} = \\frac{1.458}{2} = 0.729\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Each class counts for one half, however many rows it has. A model that always answers with one class gets a recall of 1 for that class and 0 for the other: a balanced accuracy of exactly 0.5, whatever its accuracy is.\n",
    "\n",
    "### 5.10 All measures of the example\n",
    "\n",
    "| Measure | Formula | The class of 20 students |\n",
    "| --- | --- | --- |\n",
    "| Accuracy | $\\frac{\\text{TP} + \\text{TN}}{\\text{all}}$ | $\\frac{15}{20} = 0.75$ |\n",
    "| Precision | $\\frac{\\text{TP}}{\\text{TP} + \\text{FP}}$ | $\\frac{10}{13} = 0.769$ |\n",
    "| Recall (sensitivity) | $\\frac{\\text{TP}}{\\text{TP} + \\text{FN}}$ | $\\frac{10}{12} = 0.833$ |\n",
    "| Specificity | $\\frac{\\text{TN}}{\\text{TN} + \\text{FP}}$ | $\\frac{5}{8} = 0.625$ |\n",
    "| F1-score | $\\frac{2 \\times \\text{TP}}{2 \\times \\text{TP} + \\text{FP} + \\text{FN}}$ | $\\frac{20}{25} = 0.8$ |\n",
    "| Balanced accuracy | $\\frac{\\text{recall} + \\text{specificity}}{2}$ | 0.729 |\n",
    "\n",
    "One model, six numbers between 0.625 and 0.833. Each one answers a different question.\n",
    "\n",
    "## 6. Which measure for which task\n",
    "\n",
    "### 6.1 The question to ask\n",
    "\n",
    "Before choosing a measure, ask: which mistake costs more here, a false alarm or a miss?\n",
    "\n",
    "- If a miss (false negative) is the expensive mistake, the model must find as many positives as possible: watch the recall.\n",
    "- If a false alarm (false positive) is the expensive mistake, a positive answer must be trustworthy: watch the precision.\n",
    "- If both matter, or you need one number: the F1-score.\n",
    "- If the classes have very different sizes, do not trust the accuracy: use the balanced accuracy or the F1-score.\n",
    "- If the classes are about equal in size and both mistakes cost the same, the accuracy is fine.\n",
    "\n",
    "### 6.2 Banking\n",
    "\n",
    "- Churn. A customer who leaves takes years of income with him. A call or a small offer to a customer who would have stayed costs little. The miss is the expensive mistake: recall comes first. The precision still matters, because the bank cannot call everybody.\n",
    "- Fraud. A fraud that goes through costs money directly; a payment that is checked once too often costs a moment. Again recall, with an eye on the precision: a bank that blocks too many honest payments loses its customers.\n",
    "- Loans. The positive class is \"will not pay back\". Giving a loan to such a customer is a miss, and it is expensive: recall. Refusing a good customer is a false alarm: lost business, so the precision is watched too.\n",
    "\n",
    "In all three cases the positive class is rare, so the accuracy says little. Banks also compare their models with the ROC-AUC and the Gini coefficient of Part 9.\n",
    "\n",
    "### 6.3 Healthcare\n",
    "\n",
    "- A screening test (the first test for a dangerous disease) must not send sick people home. A miss can cost a life, a false alarm costs a second test. The measure is the recall, which doctors call sensitivity.\n",
    "- A confirming test, before a hard treatment or an operation, must not treat healthy people. Here a positive answer has to be trustworthy: precision and specificity.\n",
    "\n",
    "Medicine often works in exactly this order: a first test with a high recall, then a second test with a high precision for those who were positive.\n",
    "\n",
    "### 6.4 Other tasks\n",
    "\n",
    "| Task | The expensive mistake | Watch |\n",
    "| --- | --- | --- |\n",
    "| Spam filter | a good e-mail in the spam folder (false positive) | precision |\n",
    "| Court, \"guilty\" | an innocent person convicted (false positive) | precision |\n",
    "| Fire or gas alarm | a fire without an alarm (false negative) | recall |\n",
    "| Search for a rare defect in a factory | a broken part that is delivered (false negative) | recall |\n",
    "| Recommending a film | a recommendation the viewer dislikes (false positive) | precision |\n",
    "| Classes of equal size, mistakes of equal cost | none in particular | accuracy |\n",
    "\n",
    "### 6.5 Unbalanced data\n",
    "\n",
    "When one class is much larger than the other, the data is unbalanced (or imbalanced). Then:\n",
    "\n",
    "- the accuracy is high for a model that does nothing (Topic 27: 0.80 for \"always stays\");\n",
    "- the balanced accuracy gives such a model 0.5;\n",
    "- the recall of such a model is 0, and so is its F1-score.\n",
    "\n",
    "So for unbalanced data: report the balanced accuracy or the F1-score, and always look at the confusion matrix itself. Topic 41 is about unbalanced data and what can be done with the data; here only the measuring is the subject.\n",
    "\n",
    "### 6.6 Summary of the choice\n",
    "\n",
    "| Situation | Measure |\n",
    "| --- | --- |\n",
    "| A miss is expensive (banking, screening, alarms) | recall |\n",
    "| A false alarm is expensive (spam, a confirming test, court) | precision |\n",
    "| Both matter, one number wanted | F1-score |\n",
    "| Unbalanced classes | balanced accuracy, F1-score |\n",
    "| Balanced classes, equal costs | accuracy |\n",
    "| Comparing models without fixing a threshold | ROC-AUC (Part 9) |\n",
    "\n",
    "## 7. The project: from the file to the model\n",
    "\n",
    "Now the data. The file is `Bank Customer Churn Prediction.csv`, as in Topic 27: 10,000 customers of a bank, and the column `churn` says who left (1) and who stayed (0). The positive class is \"leaves\".\n",
    "\n",
    "This part repeats every step up to the trained model, shortly, as a revision. The cells continue from each other like the cells of a notebook.\n",
    "\n",
    "### 7.1 Step 1: read and look"
   ],
   "id": "t28-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())"
   ],
   "id": "t28-002"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "10,000 rows and 12 columns: an identification number, ten features and the target `churn`.\n",
    "\n",
    "### 7.2 Step 2: check"
   ],
   "id": "t28-003"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.isna().sum().sum())\n",
    "print(df.duplicated().sum())\n",
    "print(df.dtypes)"
   ],
   "id": "t28-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "No missing values and no repeated rows (Topic 11). Two columns are text: `country` and `gender`. They must become numbers before a model can use them.\n",
    "\n",
    "### 7.3 Step 3: drop what carries no information"
   ],
   "id": "t28-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = df.drop(columns=[\"customer_id\"])\n",
    "\n",
    "print(df.shape)"
   ],
   "id": "t28-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "An identification number says nothing about a customer (Topic 24).\n",
    "\n",
    "### 7.4 Step 4: the target"
   ],
   "id": "t28-007"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df[\"churn\"].value_counts())\n",
    "print(df[\"churn\"].mean())"
   ],
   "id": "t28-008"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "2,037 of the 10,000 customers left: about 20 percent. The data is unbalanced, four to one. After Part 6 this is a clear sign: the accuracy alone will not be enough here.\n",
    "\n",
    "### 7.5 Step 5: encode\n",
    "\n",
    "`gender` has two values and becomes 0 and 1. `country` has three values without an order and gets one-hot encoding (Topic 25). `products_number` is one-hot encoded too: Topic 27 found that its effect is not in order (customers with 2 products leave least), and that this encoding raised the accuracy from 0.811 to 0.843."
   ],
   "id": "t28-009"
  },
  {
   "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(df.columns.tolist())"
   ],
   "id": "t28-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The outliers were looked at in Topic 27: they are real customers and stay in the data.\n",
    "\n",
    "### 7.6 Step 6: split"
   ],
   "id": "t28-011"
  },
  {
   "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)\n",
    "print(y_test.sum())"
   ],
   "id": "t28-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "8,000 customers for training and 2,000 for the test (Topic 23). Of the 2,000 test customers, 393 left and 1,607 stayed.\n",
    "\n",
    "### 7.7 Step 7: scale"
   ],
   "id": "t28-013"
  },
  {
   "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": "t28-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The scaler is fitted on the training data and applied to both parts (Topic 24).\n",
    "\n",
    "### 7.8 Step 8: train"
   ],
   "id": "t28-015"
  },
  {
   "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",
    "predicted = model.predict(X_test_scaled)\n",
    "\n",
    "print(predicted[:10])\n",
    "print(round(model.score(X_test_scaled, y_test), 4))"
   ],
   "id": "t28-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`predicted` holds the class the model gives to each of the 2,000 test customers. The accuracy is 0.843, as in Topic 27. Everything from here on asks: what is behind this number?\n",
    "\n",
    "## 8. The measures in code\n",
    "\n",
    "All measures are in `sklearn.metrics`. Every function takes the truth first and the prediction second: `(y_test, predicted)`.\n",
    "\n",
    "### 8.1 The confusion matrix\n",
    "\n",
    "Change it and run: write `confusion_matrix(predicted, y_test)` and run: the two wrong cells change places. The truth must come first."
   ],
   "id": "t28-017"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import confusion_matrix\n",
    "\n",
    "print(confusion_matrix(y_test, predicted))"
   ],
   "id": "t28-018"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The layout is the one of Part 3: rows are the truth, columns the prediction, class 0 first.\n",
    "\n",
    "|  | Predicted 0 (stays) | Predicted 1 (leaves) |\n",
    "| --- | --- | --- |\n",
    "| Actual 0 (stayed) | $\\text{TN} = 1543$ | $\\text{FP} = 64$ |\n",
    "| Actual 1 (left) | $\\text{FN} = 250$ | $\\text{TP} = 143$ |\n",
    "\n",
    "- 1,543 customers stayed and the model said so.\n",
    "- 64 customers stayed, and the model said \"leaves\": false alarms.\n",
    "- 250 customers left, and the model said \"stays\": misses.\n",
    "- 143 customers left and the model found them.\n",
    "\n",
    "This is what the accuracy of 0.843 was hiding. The model is right very often, because it is right about the many customers who stay. Of the 393 customers who left it found only 143.\n",
    "\n",
    "`ravel()` lays the matrix out as one line, in the reading order TN, FP, FN, TP, so that the four numbers get names:"
   ],
   "id": "t28-019"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tn, fp, fn, tp = confusion_matrix(y_test, predicted).ravel()\n",
    "\n",
    "print(tn, fp, fn, tp)"
   ],
   "id": "t28-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 8.2 The matrix as a picture"
   ],
   "id": "t28-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "from sklearn.metrics import ConfusionMatrixDisplay\n",
    "\n",
    "ConfusionMatrixDisplay.from_predictions(y_test, predicted, display_labels=[\"stays\", \"leaves\"], cmap=\"Blues\")\n",
    "plt.title(\"Confusion matrix of the model\")\n",
    "plt.show()"
   ],
   "id": "t28-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`from_predictions` draws the same four numbers, a darker cell for a larger count. `display_labels` gives the two classes their names.\n",
    "\n",
    "### 8.3 The measures by hand\n",
    "\n",
    "With the four counts, every formula of Part 5 is one line:"
   ],
   "id": "t28-023"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(round((tp + tn) / (tp + tn + fp + fn), 4))\n",
    "print(round(tp / (tp + fp), 4))\n",
    "print(round(tp / (tp + fn), 4))\n",
    "print(round(tn / (tn + fp), 4))"
   ],
   "id": "t28-024"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The accuracy, the precision, the recall and the specificity.\n",
    "\n",
    "- Precision 0.6908: when the model says \"leaves\", it is right in 69 of 100 cases.\n",
    "- Recall 0.3639: the model finds only 36 of 100 customers who leave. It misses almost two thirds of them.\n",
    "- Specificity 0.9602: of the customers who stay, it recognises 96 of 100.\n",
    "\n",
    "### 8.4 The measures with scikit-learn"
   ],
   "id": "t28-025"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
    "\n",
    "print(round(accuracy_score(y_test, predicted), 4))\n",
    "print(round(precision_score(y_test, predicted), 4))\n",
    "print(round(recall_score(y_test, predicted), 4))\n",
    "print(round(f1_score(y_test, predicted), 4))"
   ],
   "id": "t28-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The same numbers as by hand, and the F1-score: 0.4767. It is low because the recall is low: the harmonic mean stays close to the smaller number."
   ],
   "id": "t28-027"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import balanced_accuracy_score\n",
    "\n",
    "print(round(balanced_accuracy_score(y_test, predicted), 4))\n",
    "print(round((tp / (tp + fn) + tn / (tn + fp)) / 2, 4))"
   ],
   "id": "t28-028"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The balanced accuracy is 0.662. The second line calculates it from the counts, as the mean of the recall (0.3639) and the specificity (0.9602), and gives the same number. The accuracy said 0.843, the balanced accuracy says 0.662. The difference is the size of the class \"stays\".\n",
    "\n",
    "### 8.5 Everything in one report"
   ],
   "id": "t28-029"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import classification_report\n",
    "\n",
    "print(classification_report(y_test, predicted, target_names=[\"stays\", \"leaves\"]))"
   ],
   "id": "t28-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "How to read the report:\n",
    "\n",
    "- One line for each class. The line \"leaves\" holds the precision, the recall and the F1-score of this lesson: 0.69, 0.36, 0.48.\n",
    "- The line \"stays\" holds the same measures with \"stays\" taken as the positive class. Its recall, 0.96, is the specificity.\n",
    "- `support` is the number of test rows of each class: 1,607 and 393.\n",
    "- `macro avg` is the plain mean of the two lines. The macro average of the recall, 0.66, is the balanced accuracy.\n",
    "- `weighted avg` is the mean weighted with the support, so the large class dominates it.\n",
    "\n",
    "### 8.6 The baseline with the new measures\n",
    "\n",
    "Topic 27 compared every accuracy with the model that always answers \"stays\". What do the other measures say about it?"
   ],
   "id": "t28-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "always_stays = np.zeros(len(y_test), dtype=int)\n",
    "\n",
    "print(round(accuracy_score(y_test, always_stays), 4))\n",
    "print(round(recall_score(y_test, always_stays), 4))\n",
    "print(round(balanced_accuracy_score(y_test, always_stays), 4))"
   ],
   "id": "t28-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`np.zeros(len(y_test), dtype=int)` is a list of 2,000 zeros: the prediction \"stays\" for everybody (Topic 8).\n",
    "\n",
    "An accuracy of 0.8035, a recall of 0 and a balanced accuracy of 0.5. The recall and the balanced accuracy see at once that this \"model\" finds nobody. (Its precision cannot be calculated: it never says \"leaves\", so the fraction would be $\\frac{0}{0}$.)\n",
    "\n",
    "### 8.7 The balanced model, judged again\n",
    "\n",
    "Topic 27 trained a model with `class_weight=\"balanced\"` and could not decide, with the accuracy alone, whether it was better. Now it can be judged:"
   ],
   "id": "t28-033"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "balanced = LogisticRegression(class_weight=\"balanced\")\n",
    "balanced.fit(X_train_scaled, y_train)\n",
    "\n",
    "predicted_balanced = balanced.predict(X_test_scaled)\n",
    "\n",
    "print(confusion_matrix(y_test, predicted_balanced))"
   ],
   "id": "t28-034"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The misses fell from 250 to 91. The price: the false alarms rose from 64 to 378."
   ],
   "id": "t28-035"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(round(accuracy_score(y_test, predicted_balanced), 4))\n",
    "print(round(precision_score(y_test, predicted_balanced), 4))\n",
    "print(round(recall_score(y_test, predicted_balanced), 4))\n",
    "print(round(f1_score(y_test, predicted_balanced), 4))\n",
    "print(round(balanced_accuracy_score(y_test, predicted_balanced), 4))"
   ],
   "id": "t28-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| Measure | The first model | The balanced model |\n",
    "| --- | --- | --- |\n",
    "| Accuracy | 0.843 | 0.7655 |\n",
    "| Precision | 0.6908 | 0.4441 |\n",
    "| Recall | 0.3639 | 0.7684 |\n",
    "| F1-score | 0.4767 | 0.5629 |\n",
    "| Balanced accuracy | 0.662 | 0.7666 |\n",
    "\n",
    "The accuracy and the precision are lower. The recall is more than twice as high, and the F1-score and the balanced accuracy are higher too. For a bank that wants to find the customers who are about to leave (Part 6: the miss is the expensive mistake), the balanced model is the better one: it finds 302 of the 393 leaving customers, where the first model found 143. The accuracy pointed in the wrong direction.\n",
    "\n",
    "### 8.8 The threshold moves precision and recall\n",
    "\n",
    "`predict` uses the threshold 0.5 on the probability of leaving (Topic 27). With `predict_proba` the threshold can be chosen:\n",
    "\n",
    "Change it and run: add `0.1` and `0.9` to the list and run."
   ],
   "id": "t28-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "leaving = model.predict_proba(X_test_scaled)[:, 1]\n",
    "\n",
    "for threshold in [0.2, 0.3, 0.4, 0.5, 0.6, 0.7]:\n",
    "    marked = (leaving >= threshold).astype(int)\n",
    "    print(threshold, round(precision_score(y_test, marked), 4), round(recall_score(y_test, marked), 4))"
   ],
   "id": "t28-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every line shows the threshold, the precision and the recall.\n",
    "\n",
    "- A low threshold marks many customers as leaving: the recall is high, the precision low.\n",
    "- A high threshold marks only the surest cases: the precision is high, the recall low.\n",
    "\n",
    "This is the pull between precision and recall of Part 5, in numbers. The model is the same in all six lines; only the place of the cut changes. With the threshold 0.2 the first model has almost the precision and the recall of the balanced model: `class_weight=\"balanced\"` and a lower threshold do much the same thing.\n",
    "\n",
    "So a single pair of precision and recall describes a model at one threshold. To judge the model itself, at all thresholds at once, there is the ROC curve.\n",
    "\n",
    "## 9. The ROC curve, the AUC and the Gini coefficient\n",
    "\n",
    "### 9.1 Two rates\n",
    "\n",
    "The ROC curve is drawn from two measures:\n",
    "\n",
    "| Rate | Formula | In words |\n",
    "| --- | --- | --- |\n",
    "| true positive rate (TPR) | $\\frac{\\text{TP}}{\\text{TP} + \\text{FN}}$ | the recall |\n",
    "| false positive rate (FPR) | $\\frac{\\text{FP}}{\\text{FP} + \\text{TN}}$ | the share of false alarms among the real negatives |\n",
    "\n",
    "The false positive rate is the opposite of the specificity: $\\text{FPR} = 1 - \\text{specificity}$. For the class of 20 students:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{TPR} &= \\frac{10}{10 + 2} = \\frac{10}{12} = 0.833 \\\\[8pt]\n",
    "\\text{FPR} &= \\frac{3}{3 + 5} = \\frac{3}{8} = 0.375\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "A good model has a high TPR (it finds the positives) and a low FPR (it gives few false alarms).\n",
    "\n",
    "### 9.2 A curve from thresholds, by hand\n",
    "\n",
    "A model gave eight students a probability of passing. Four of them passed (P) and four failed (N):\n",
    "\n",
    "| Student | A | B | C | D | E | F | G | H |\n",
    "| --- | --- | --- | --- | --- | --- | --- | --- | --- |\n",
    "| Probability | 0.9 | 0.8 | 0.7 | 0.6 | 0.4 | 0.3 | 0.2 | 0.1 |\n",
    "| Truth | P | P | N | P | N | P | N | N |\n",
    "\n",
    "For a threshold, every student with a probability at or above it is predicted \"passes\". Three thresholds:\n",
    "\n",
    "| Threshold | Predicted \"passes\" | TP | FP | $\\text{TPR} = \\frac{\\text{TP}}{4}$ | $\\text{FPR} = \\frac{\\text{FP}}{4}$ |\n",
    "| --- | --- | --- | --- | --- | --- |\n",
    "| 0.75 | A, B | 2 | 0 | 0.5 | 0 |\n",
    "| 0.5 | A, B, C, D | 3 | 1 | 0.75 | 0.25 |\n",
    "| 0.25 | A to F | 4 | 2 | 1 | 0.5 |\n",
    "\n",
    "Each threshold gives one point (FPR, TPR). A threshold above 0.9 marks nobody: the point (0, 0). A threshold of 0 marks everybody: the point (1, 1). The ROC curve joins the points of all thresholds, from (0, 0) to (1, 1). ROC stands for \"receiver operating characteristic\", a name from radar engineering.\n",
    "\n",
    "The picture of this curve is on the lesson page. It is a staircase through the points (0, 0), (0, 0.5), (0.25, 0.5), (0.25, 0.75), (0.5, 0.75), (0.5, 1) and (1, 1), drawn in a square that is cut into 16 small squares.\n",
    "\n",
    "### 9.3 The area under the curve: AUC\n",
    "\n",
    "The AUC (\"area under the curve\") is the area under the ROC curve. The whole square has the area 1. In the picture the square is cut into 16 small squares, and 13 of them lie under the curve:\n",
    "\n",
    "$$\n",
    "\\text{AUC} = \\frac{13}{16} = 0.8125\n",
    "$$\n",
    "\n",
    "The AUC has a simple meaning. Take one student who passed and one who failed, at random. The AUC is the probability that the model gave the higher number to the one who passed. It can be counted directly. There are $4 \\times 4 = 16$ pairs of one P and one N:\n",
    "\n",
    "| Student who passed | Is above | Pairs |\n",
    "| --- | --- | --- |\n",
    "| A (0.9) | all 4 students who failed | 4 |\n",
    "| B (0.8) | all 4 | 4 |\n",
    "| D (0.6) | E, G and H, but below C | 3 |\n",
    "| F (0.3) | G and H only | 2 |\n",
    "\n",
    "$$\n",
    "\\text{AUC} = \\frac{4 + 4 + 3 + 2}{16} = \\frac{13}{16} = 0.8125\n",
    "$$\n",
    "\n",
    "The same number as the area. So the AUC measures how well the model puts the positives above the negatives, without choosing any threshold.\n",
    "\n",
    "### 9.4 Which curve is better, and why\n",
    "\n",
    "The picture with the four curves (perfect, good, weak and guessing) is on the lesson page.\n",
    "\n",
    "- The diagonal is a model that guesses: it marks rows as positive at random, so it catches the same share of the positives and of the negatives. $\\text{TPR} = \\text{FPR}$ at every threshold, and the AUC is 0.5.\n",
    "- The perfect model gives every positive a higher probability than every negative. Its curve goes straight up to the top left corner, the point with $\\text{TPR} = 1$ and $\\text{FPR} = 0$, and then to the right. Its AUC is 1.\n",
    "- Real models lie in between. The closer a curve comes to the top left corner, the better: at the same rate of false alarms it finds more of the positives. A curve that lies above another one everywhere belongs to the better model, and it has the larger area.\n",
    "- A curve below the diagonal (AUC under 0.5) means the model puts the classes the wrong way round.\n",
    "\n",
    "A rough guide for reading an AUC (the borders are habits, not laws):\n",
    "\n",
    "| AUC | Reading |\n",
    "| --- | --- |\n",
    "| 0.5 | no better than guessing |\n",
    "| 0.6 to 0.7 | weak |\n",
    "| 0.7 to 0.8 | fair |\n",
    "| 0.8 to 0.9 | good |\n",
    "| above 0.9 | very good (and worth a second look: is a column leaking the answer?) |\n",
    "\n",
    "### 9.5 The points of the bank model, with the measures you know\n",
    "\n",
    "Back to the project. The ROC curve needs the probabilities, not the classes: `leaving` holds the probability of leaving of every test customer. For five thresholds, the cell calculates the two rates from the confusion matrix:"
   ],
   "id": "t28-039"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fpr_points = []\n",
    "tpr_points = []\n",
    "\n",
    "for threshold in [0.1, 0.3, 0.5, 0.7, 0.9]:\n",
    "    marked = (leaving >= threshold).astype(int)\n",
    "    tn, fp, fn, tp = confusion_matrix(y_test, marked).ravel()\n",
    "    fpr_points.append(fp / (fp + tn))\n",
    "    tpr_points.append(tp / (tp + fn))\n",
    "    print(threshold, round(fp / (fp + tn), 4), round(tp / (tp + fn), 4))"
   ],
   "id": "t28-040"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every line shows a threshold, its false positive rate and its true positive rate. With the threshold 0.1 the model finds nine of ten leaving customers, and it gives a false alarm for almost half of the customers who stay. With 0.9 it gives almost no false alarm and finds only one leaving customer in ten.\n",
    "\n",
    "Five points are already the outline of a curve:"
   ],
   "id": "t28-041"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.plot(fpr_points, tpr_points, marker=\"o\")\n",
    "plt.plot([0, 1], [0, 1], linestyle=\"--\")\n",
    "plt.xlabel(\"False positive rate\")\n",
    "plt.ylabel(\"True positive rate (recall)\")\n",
    "plt.title(\"Five points of the ROC curve\")\n",
    "plt.show()"
   ],
   "id": "t28-042"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 9.6 The whole curve with scikit-learn\n",
    "\n",
    "`roc_curve` does the same for every useful threshold. It takes the truth and the probabilities and returns three arrays: the false positive rates, the true positive rates and the thresholds.\n",
    "\n",
    "Change it and run: write `roc_curve(y_test, predicted)` and run: with classes in the place of probabilities only one point is left between the two corners."
   ],
   "id": "t28-043"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import roc_curve\n",
    "\n",
    "fpr, tpr, thresholds = roc_curve(y_test, leaving)\n",
    "\n",
    "plt.plot(fpr, tpr, label=\"the model\")\n",
    "plt.plot([0, 1], [0, 1], linestyle=\"--\", label=\"guessing\")\n",
    "plt.xlabel(\"False positive rate\")\n",
    "plt.ylabel(\"True positive rate (recall)\")\n",
    "plt.title(\"ROC curve\")\n",
    "plt.legend()\n",
    "plt.show()"
   ],
   "id": "t28-044"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The curve lies well above the diagonal and far from the top left corner: a good model, not a perfect one.\n",
    "\n",
    "### 9.7 The AUC in code"
   ],
   "id": "t28-045"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import roc_auc_score\n",
    "\n",
    "auc = roc_auc_score(y_test, leaving)\n",
    "\n",
    "print(round(auc, 4))"
   ],
   "id": "t28-046"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "An AUC of 0.837: take a customer who left and one who stayed, and in about 84 of 100 such pairs the model gives the higher probability to the one who left.\n",
    "\n",
    "Give `roc_auc_score` the probabilities (`leaving`), not the classes (`predicted`). With classes there is only one threshold, and the curve shrinks to a single point.\n",
    "\n",
    "### 9.8 Comparing models\n",
    "\n",
    "A weaker model for comparison: one that knows only the age and the balance of a customer.\n",
    "\n",
    "Change it and run: change the list to `[\"credit_score\", \"tenure\"]` and run: the AUC falls to about 0.52, hardly better than guessing."
   ],
   "id": "t28-047"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "columns = [\"age\", \"balance\"]\n",
    "\n",
    "small_scaler = StandardScaler()\n",
    "small_train = small_scaler.fit_transform(X_train[columns])\n",
    "small_test = small_scaler.transform(X_test[columns])\n",
    "\n",
    "small = LogisticRegression()\n",
    "small.fit(small_train, y_train)\n",
    "\n",
    "small_leaving = small.predict_proba(small_test)[:, 1]\n",
    "\n",
    "print(round(roc_auc_score(y_test, small_leaving), 4))"
   ],
   "id": "t28-048"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "small_fpr, small_tpr, small_thresholds = roc_curve(y_test, small_leaving)\n",
    "\n",
    "plt.plot(fpr, tpr, label=\"all 13 features\")\n",
    "plt.plot(small_fpr, small_tpr, label=\"age and balance only\")\n",
    "plt.plot([0, 1], [0, 1], linestyle=\"--\", label=\"guessing\")\n",
    "plt.xlabel(\"False positive rate\")\n",
    "plt.ylabel(\"True positive rate (recall)\")\n",
    "plt.title(\"Two models, two ROC curves\")\n",
    "plt.legend()\n",
    "plt.show()"
   ],
   "id": "t28-049"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The AUC of the small model is 0.7461, against 0.837. The curve of the full model lies above the curve of the small model almost everywhere: at the same rate of false alarms it finds more of the leaving customers. Its area is larger. The full model is the better one whatever threshold is chosen, and the AUC says so in one number.\n",
    "\n",
    "And the balanced model?"
   ],
   "id": "t28-050"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "balanced_leaving = balanced.predict_proba(X_test_scaled)[:, 1]\n",
    "\n",
    "print(round(roc_auc_score(y_test, balanced_leaving), 4))"
   ],
   "id": "t28-051"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Almost the same AUC as the first model. That is an important result. The two models put the customers in almost the same order; they only cut the list at different places. `class_weight=\"balanced\"` did not make a better model in the sense of the AUC: it moved the model to another point of nearly the same curve, a point with more recall. The AUC judges the order, the recall and the precision judge one cut.\n",
    "\n",
    "### 9.9 The Gini coefficient\n",
    "\n",
    "Banks often report the Gini coefficient in the place of the AUC. It is the same information on another scale:\n",
    "\n",
    "$$\n",
    "\\text{Gini} = 2 \\times \\text{AUC} - 1\n",
    "$$\n",
    "\n",
    "|  | AUC | Gini |\n",
    "| --- | --- | --- |\n",
    "| Guessing | 0.5 | 0 |\n",
    "| Perfect model | 1 | 1 |\n",
    "\n",
    "The Gini coefficient runs from 0 (guessing) to 1 (perfect), which many people find easier to read than \"from 0.5 to 1\". For the eight students:\n",
    "\n",
    "$$\n",
    "\\text{Gini} = 2 \\times 0.8125 - 1 = 1.625 - 1 = 0.625\n",
    "$$\n",
    "\n",
    "For the bank model:"
   ],
   "id": "t28-052"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gini = 2 * auc - 1\n",
    "\n",
    "print(round(gini, 4))"
   ],
   "id": "t28-053"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the picture, the Gini coefficient is the area between the ROC curve and the diagonal, compared with the same area for the perfect model. (The Gini coefficient of economics, which measures the inequality of incomes, is a relative of it with the same name.)\n",
    "\n",
    "### 9.10 What the AUC does not tell\n",
    "\n",
    "- The AUC does not choose a threshold. To use a model, a threshold is still needed, and with it come a precision and a recall.\n",
    "- With a very rare positive class, the false positive rate stays small even when the false alarms outnumber the hits, so the ROC curve can look better than the model feels in use. Look at the precision as well.\n",
    "\n",
    "### 9.11 More than two classes\n",
    "\n",
    "With three or more classes the confusion matrix has one row and one column for every class, and the diagonal still holds the right predictions. Precision, recall and F1 are calculated for every class in turn (this class against all the others), as the lines of `classification_report` did, and then averaged. This lesson stays with two classes.\n",
    "\n",
    "## 10. The workflow, step by step\n",
    "\n",
    "| Step | What is done | In this project |\n",
    "| --- | --- | --- |\n",
    "| 1. Look and check | shape, missing values, text columns | 10,000 customers, nothing missing |\n",
    "| 2. Drop | columns without information | `customer_id` |\n",
    "| 3. Target | the share of each class | 20 percent left: unbalanced |\n",
    "| 4. Encode | text and unordered numbers | `gender`, `country`, `products_number` |\n",
    "| 5. Split | training and test data | 8,000 and 2,000 |\n",
    "| 6. Scale | fit on the training data | `StandardScaler` |\n",
    "| 7. Train | the model | `LogisticRegression` |\n",
    "| 8. Confusion matrix | the four counts | 1543, 64, 250, 143 |\n",
    "| 9. Choose the measure | which mistake costs more? | a miss: recall |\n",
    "| 10. Measures | precision, recall, F1, balanced accuracy | 0.69, 0.36, 0.48, 0.66 |\n",
    "| 11. Threshold or class weights | move along the curve | recall 0.77 with balanced classes |\n",
    "| 12. ROC-AUC and Gini | the model at all thresholds | 0.837 and 0.674 |\n",
    "\n",
    "Steps 1 to 7 are the workflow of Topic 27. Steps 8 to 12 are new: judging a classifier is a piece of work of its own, not one line.\n",
    "\n",
    "## 11. Common mistakes\n",
    "\n",
    "| Mistake | Why it is wrong | Right |\n",
    "| --- | --- | --- |\n",
    "| Judging a model on unbalanced data with the accuracy alone. | A model that finds nobody can have a high accuracy. | Confusion matrix, recall, precision, balanced accuracy. |\n",
    "| Mixing up precision and recall. | They divide by different sums. | Precision: by what was predicted positive. Recall: by what is really positive. |\n",
    "| Reading a confusion matrix without its labels. | Books and libraries place the cells differently. | In scikit-learn: rows are the truth, class 0 first: TN, FP, FN, TP. |\n",
    "| Writing `confusion_matrix(predicted, y_test)`. | The matrix is turned round: FP and FN change places. | The truth first: `(y_test, predicted)`. |\n",
    "| \"Positive means good.\" | The positive class is the one being looked for, often the bad news. | Decide and say which class is positive. |\n",
    "| Reporting only the precision, or only the recall. | Each can be made high alone: mark nobody, or mark everybody. | Report both, or the F1-score. |\n",
    "| Taking the ordinary mean of precision and recall. | It hides a very low value. | The harmonic mean: the F1-score. |\n",
    "| Giving `roc_auc_score` the predicted classes. | Only one threshold is used; the result is not the AUC of the model. | Give the probabilities: `predict_proba(...)[:, 1]`. |\n",
    "| \"An AUC of 0.5 is a model that is half right.\" | 0.5 is guessing: the model cannot order the classes at all. | The scale of the AUC starts at 0.5; the Gini starts at 0. |\n",
    "| Choosing the threshold with the test data. | The test data then takes part in building the model. | Choose it on training data, with cross-validation. |\n",
    "| Thinking `class_weight=\"balanced\"` makes a better model. | It mainly moves the cut: more recall, less precision. | Compare the AUC, and judge the cut by the costs. |\n",
    "| Comparing an F1-score with an accuracy. | They measure different things on different scales. | Compare the same measure between models. |\n",
    "\n",
    "## 12. 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 another split.\n",
    "\n",
    "Problem 1. From a story to the matrix\n",
    "\n",
    "A spam filter checked 200 e-mails. 50 of them were spam. The filter marked 40 e-mails as spam, and 30 of those really were spam. Find TP, FP, FN and TN. The positive class is \"spam\".\n",
    "\n",
    "Idea. Start with what the model said and whether it was right (Part 2). The rest follows from the sums.\n",
    "\n",
    "| Count | Calculation | In words |\n",
    "| --- | --- | --- |\n",
    "| $\\text{TP}$ | 30 | marked as spam, and spam |\n",
    "| $\\text{FP}$ | $40 - 30 = 10$ | marked as spam, but good |\n",
    "| $\\text{FN}$ | $50 - 30 = 20$ | spam that was not marked |\n",
    "| $\\text{TN}$ | $200 - 30 - 10 - 20 = 140$ | good, and not marked |\n",
    "\n",
    "|  | Predicted 0 (good) | Predicted 1 (spam) |\n",
    "| --- | --- | --- |\n",
    "| Actual 0 (good) | $\\text{TN} = 140$ | $\\text{FP} = 10$ |\n",
    "| Actual 1 (spam) | $\\text{FN} = 20$ | $\\text{TP} = 30$ |\n",
    "\n",
    "Why: the column \"predicted 1\" adds up to the 40 marked e-mails, the row \"actual 1\" to the 50 spam e-mails, and all four cells to 200.\n",
    "\n",
    "Problem 2. The measures of the spam filter\n",
    "\n",
    "For the filter of Problem 1 ($\\text{TP} = 30$, $\\text{FP} = 10$, $\\text{FN} = 20$, $\\text{TN} = 140$), calculate the accuracy, the precision, the recall and the F1-score.\n",
    "\n",
    "Idea. Every measure is a fraction of the four counts (Part 5).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{accuracy} &= \\frac{30 + 140}{200} = \\frac{170}{200} = 0.85 \\\\[6pt]\n",
    "\\text{precision} &= \\frac{30}{30 + 10} = \\frac{30}{40} = 0.75 \\\\[6pt]\n",
    "\\text{recall} &= \\frac{30}{30 + 20} = \\frac{30}{50} = 0.6 \\\\[6pt]\n",
    "F_1 &= \\frac{2 \\times 0.75 \\times 0.6}{0.75 + 0.6} = \\frac{0.9}{1.35} = 0.667\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: the accuracy looks good, 0.85. The recall shows the weakness: 40 percent of the spam still reaches the inbox. For a spam filter the precision matters most (a good e-mail in the spam folder is the expensive mistake), and 0.75 means that one marked e-mail in four was a good one. That is too many.\n",
    "\n",
    "Problem 3. The trap of the accuracy\n",
    "\n",
    "A disease is found in 10 of 1,000 people. A \"model\" says \"healthy\" for everybody. Calculate its accuracy, its recall and its balanced accuracy. The positive class is \"sick\".\n",
    "\n",
    "Idea. Write down the four counts first (Parts 2 and 5).\n",
    "\n",
    "$$\n",
    "\\text{TP} = 0 \\qquad \\text{FN} = 10 \\qquad \\text{FP} = 0 \\qquad \\text{TN} = 990\n",
    "$$\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{accuracy} &= \\frac{0 + 990}{1000} = 0.99 \\\\[6pt]\n",
    "\\text{recall} &= \\frac{0}{0 + 10} = 0 \\\\[6pt]\n",
    "\\text{specificity} &= \\frac{990}{990 + 0} = 1 \\\\[6pt]\n",
    "\\text{balanced accuracy} &= \\frac{0 + 1}{2} = 0.5\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: an accuracy of 0.99 for a model that finds no sick person at all. The recall, 0, and the balanced accuracy, 0.5, show the truth. With unbalanced classes the accuracy must never be read alone.\n",
    "\n",
    "Problem 4. A ROC curve by hand\n",
    "\n",
    "A model gave six customers a probability of leaving. Three left (P): 0.9, 0.7 and 0.4. Three stayed (N): 0.6, 0.3 and 0.2. (a) Calculate the TPR and the FPR for the threshold 0.5. (b) Calculate the AUC by counting pairs. (c) Calculate the Gini coefficient.\n",
    "\n",
    "Idea. A threshold gives one point of the curve. The AUC is the share of the pairs (one P, one N) in which the P has the higher number (Part 9).\n",
    "\n",
    "(a) At or above 0.5 are 0.9 (P), 0.7 (P) and 0.6 (N), so $\\text{TP} = 2$ and $\\text{FP} = 1$.\n",
    "\n",
    "$$\n",
    "\\text{TPR} = \\frac{2}{3} = 0.667 \\qquad \\text{FPR} = \\frac{1}{3} = 0.333\n",
    "$$\n",
    "\n",
    "(b) There are $3 \\times 3 = 9$ pairs. 0.9 is above 0.6, 0.3 and 0.2: 3 pairs. 0.7 is above 0.6, 0.3 and 0.2: 3 pairs. 0.4 is above 0.3 and 0.2: 2 pairs.\n",
    "\n",
    "$$\n",
    "\\text{AUC} = \\frac{3 + 3 + 2}{9} = \\frac{8}{9} = 0.889\n",
    "$$\n",
    "\n",
    "(c) The Gini coefficient:\n",
    "\n",
    "$$\n",
    "\\text{Gini} = 2 \\times 0.889 - 1 = 1.778 - 1 = 0.778\n",
    "$$\n",
    "\n",
    "Why: only one pair is in the wrong order: the customer with 0.4 who left and the customer with 0.6 who stayed. A model with no such pair would have an AUC of 1.\n",
    "\n",
    "Problem 5. Read and check\n",
    "\n",
    "Read the file. Print its shape, the number of missing values and the share of customers who left.\n",
    "\n",
    "Idea. The first steps of the workflow (Part 7)."
   ],
   "id": "t28-054"
  },
  {
   "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())\n",
    "print(df[\"churn\"].mean())"
   ],
   "id": "t28-055"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: one customer in five left. The classes are unbalanced, so the accuracy will not be enough.\n",
    "\n",
    "Problem 6. Drop and encode\n",
    "\n",
    "Drop `customer_id`. 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. A column without information is dropped; text and numbers without order are encoded (Part 7)."
   ],
   "id": "t28-056"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = df.drop(columns=[\"customer_id\"])\n",
    "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": "t28-057"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: 14 columns: 13 features and the target.\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 number of test customers and how many of them left.\n",
    "\n",
    "Idea. The split comes before everything that learns from the rows (Part 7)."
   ],
   "id": "t28-058"
  },
  {
   "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(len(y_test), y_test.sum())"
   ],
   "id": "t28-059"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: these two numbers are the sums of the confusion matrix: all its cells add up to 2,500, and its row \"actual 1\" to 510.\n",
    "\n",
    "Problem 8. Scale and train\n",
    "\n",
    "Scale the features with a `StandardScaler` fitted on the training data. Train a `LogisticRegression` and print its test accuracy, rounded to 4 decimals.\n",
    "\n",
    "Idea. `fit_transform` on the training data, `transform` on the test data, then `fit` and `score` (Part 7)."
   ],
   "id": "t28-060"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import StandardScaler\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "\n",
    "scaler = StandardScaler()\n",
    "X_train_scaled = scaler.fit_transform(X_train)\n",
    "X_test_scaled = scaler.transform(X_test)\n",
    "\n",
    "model = LogisticRegression()\n",
    "model.fit(X_train_scaled, y_train)\n",
    "\n",
    "print(round(model.score(X_test_scaled, y_test), 4))"
   ],
   "id": "t28-061"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: an accuracy of about 0.84. The following problems look behind it.\n",
    "\n",
    "Problem 9. The confusion matrix\n",
    "\n",
    "Predict the classes of the test customers and print the confusion matrix.\n",
    "\n",
    "Idea. `confusion_matrix(y_test, predicted)`: the truth first (Part 8)."
   ],
   "id": "t28-062"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import confusion_matrix\n",
    "\n",
    "predicted = model.predict(X_test_scaled)\n",
    "\n",
    "print(confusion_matrix(y_test, predicted))"
   ],
   "id": "t28-063"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: read it like a text: TN, FP, FN, TP. The model is right about almost all customers who stayed, and it misses most of the customers who left: the number at the bottom left is larger than the number at the bottom right.\n",
    "\n",
    "Problem 10. The four counts and the recall by hand\n",
    "\n",
    "Give the four counts names with `ravel()`. Print the number of misses and the number of false alarms, then the recall calculated from the counts, rounded to 4 decimals.\n",
    "\n",
    "Idea. `ravel()` gives TN, FP, FN, TP; $\\text{recall} = \\frac{\\text{TP}}{\\text{TP} + \\text{FN}}$ (Parts 5 and 8)."
   ],
   "id": "t28-064"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tn, fp, fn, tp = confusion_matrix(y_test, predicted).ravel()\n",
    "\n",
    "print(fn, fp)\n",
    "print(round(tp / (tp + fn), 4))"
   ],
   "id": "t28-065"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: many more misses than false alarms. This model is careful: it says \"leaves\" rarely, so it finds only about a third of the customers who leave.\n",
    "\n",
    "Problem 11. Precision, recall and F1\n",
    "\n",
    "Print the precision, the recall and the F1-score with the functions of scikit-learn, rounded to 4 decimals.\n",
    "\n",
    "Idea. `precision_score`, `recall_score`, `f1_score`, each with `(y_test, predicted)` (Part 8)."
   ],
   "id": "t28-066"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import precision_score, recall_score, f1_score\n",
    "\n",
    "print(round(precision_score(y_test, predicted), 4))\n",
    "print(round(recall_score(y_test, predicted), 4))\n",
    "print(round(f1_score(y_test, predicted), 4))"
   ],
   "id": "t28-067"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the recall is the number of Problem 10. The F1-score lies between the precision and the recall, closer to the smaller one.\n",
    "\n",
    "Problem 12. The balanced accuracy\n",
    "\n",
    "Print the balanced accuracy of the model, and the balanced accuracy of always answering 0, both rounded to 4 decimals.\n",
    "\n",
    "Idea. The mean of the recall of the two classes; a model that always gives one class gets 0.5 (Parts 5 and 8)."
   ],
   "id": "t28-068"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from sklearn.metrics import balanced_accuracy_score\n",
    "\n",
    "always_stays = np.zeros(len(y_test), dtype=int)\n",
    "\n",
    "print(round(balanced_accuracy_score(y_test, predicted), 4))\n",
    "print(round(balanced_accuracy_score(y_test, always_stays), 4))"
   ],
   "id": "t28-069"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: on this scale the model is clearly above the \"model\" that finds nobody, and still far from 1. The balanced accuracy is the honest relative of the accuracy for unbalanced data.\n",
    "\n",
    "Problem 13. A lower threshold\n",
    "\n",
    "Take the probability of leaving of every test customer. With the threshold 0.3, print the precision and the recall, rounded to 4 decimals.\n",
    "\n",
    "Idea. `predict_proba(...)[:, 1]`, compared with the threshold (Part 8)."
   ],
   "id": "t28-070"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "leaving = model.predict_proba(X_test_scaled)[:, 1]\n",
    "marked = (leaving >= 0.3).astype(int)\n",
    "\n",
    "print(round(precision_score(y_test, marked), 4))\n",
    "print(round(recall_score(y_test, marked), 4))"
   ],
   "id": "t28-071"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: compared with Problem 11 the recall is much higher and the precision lower. The model did not change; the cut moved.\n",
    "\n",
    "Problem 14. The balanced model\n",
    "\n",
    "Train a model with `class_weight=\"balanced\"`. Print its confusion matrix, then its recall and its F1-score, rounded to 4 decimals.\n",
    "\n",
    "Idea. Mistakes on the rare class weigh more, so the model marks more customers (Part 8)."
   ],
   "id": "t28-072"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "balanced = LogisticRegression(class_weight=\"balanced\")\n",
    "balanced.fit(X_train_scaled, y_train)\n",
    "\n",
    "predicted_balanced = balanced.predict(X_test_scaled)\n",
    "\n",
    "print(confusion_matrix(y_test, predicted_balanced))\n",
    "print(round(recall_score(y_test, predicted_balanced), 4))\n",
    "print(round(f1_score(y_test, predicted_balanced), 4))"
   ],
   "id": "t28-073"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: far fewer misses, many more false alarms. The recall and the F1-score are higher than in Problem 11. For a bank that wants to keep its customers this is the better model.\n",
    "\n",
    "Problem 15. AUC and Gini\n",
    "\n",
    "Print the AUC of the first model and its Gini coefficient, rounded to 4 decimals.\n",
    "\n",
    "Idea. `roc_auc_score` with the probabilities; $\\text{Gini} = 2 \\times \\text{AUC} - 1$ (Part 9)."
   ],
   "id": "t28-074"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import roc_auc_score\n",
    "\n",
    "auc = roc_auc_score(y_test, leaving)\n",
    "\n",
    "print(round(auc, 4))\n",
    "print(round(2 * auc - 1, 4))"
   ],
   "id": "t28-075"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: an AUC above 0.8: in more than four of five pairs of one leaving and one staying customer, the model gives the higher probability to the one who left.\n",
    "\n",
    "Problem 16. The ROC curve\n",
    "\n",
    "Draw the ROC curve of the first model, with the diagonal of guessing.\n",
    "\n",
    "Idea. `roc_curve` returns the false positive rates and the true positive rates of all thresholds (Part 9)."
   ],
   "id": "t28-076"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "from sklearn.metrics import roc_curve\n",
    "\n",
    "fpr, tpr, thresholds = roc_curve(y_test, leaving)\n",
    "\n",
    "plt.plot(fpr, tpr, label=\"the model\")\n",
    "plt.plot([0, 1], [0, 1], linestyle=\"--\", label=\"guessing\")\n",
    "plt.xlabel(\"False positive rate\")\n",
    "plt.ylabel(\"True positive rate (recall)\")\n",
    "plt.title(\"ROC curve\")\n",
    "plt.legend()\n",
    "plt.show()"
   ],
   "id": "t28-077"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the curve lies clearly above the diagonal. The area between the two, doubled, is the Gini coefficient of Problem 15.\n",
    "\n",
    "## 15. Summary\n",
    "\n",
    "|  | Predicted 0 | Predicted 1 |\n",
    "| --- | --- | --- |\n",
    "| Actual 0 | TN | FP (Type I error) |\n",
    "| Actual 1 | FN (Type II error) | TP |\n",
    "\n",
    "| Measure | Formula | Question it answers |\n",
    "| --- | --- | --- |\n",
    "| Accuracy | $\\frac{\\text{TP} + \\text{TN}}{\\text{all}}$ | how often is the model right? |\n",
    "| Precision | $\\frac{\\text{TP}}{\\text{TP} + \\text{FP}}$ | can a positive answer be trusted? |\n",
    "| Recall (sensitivity, TPR) | $\\frac{\\text{TP}}{\\text{TP} + \\text{FN}}$ | how many positives are found? |\n",
    "| Specificity | $\\frac{\\text{TN}}{\\text{TN} + \\text{FP}}$ | how many negatives are recognised? |\n",
    "| F1-score | $\\frac{2 \\times \\text{precision} \\times \\text{recall}}{\\text{precision} + \\text{recall}}$ | precision and recall in one number |\n",
    "| Balanced accuracy | $\\frac{\\text{recall} + \\text{specificity}}{2}$ | the accuracy with equal weight for both classes |\n",
    "| False positive rate | $\\frac{\\text{FP}}{\\text{FP} + \\text{TN}}$ | the share of false alarms among the negatives |\n",
    "| AUC | the area under the ROC curve | how well are positives put above negatives? |\n",
    "| Gini | $2 \\times \\text{AUC} - 1$ | the AUC on a scale from 0 to 1 |\n",
    "\n",
    "| Code | What it does |\n",
    "| --- | --- |\n",
    "| `confusion_matrix(y_test, predicted)` | the matrix: rows the truth, class 0 first |\n",
    "| `tn, fp, fn, tp = confusion_matrix(y_test, predicted).ravel()` | the four counts with names |\n",
    "| `ConfusionMatrixDisplay.from_predictions(y_test, predicted)` | the matrix as a picture |\n",
    "| `accuracy_score`, `precision_score`, `recall_score`, `f1_score` | the measures, each with `(y_test, predicted)` |\n",
    "| `balanced_accuracy_score(y_test, predicted)` | the balanced accuracy |\n",
    "| `classification_report(y_test, predicted)` | all measures of every class |\n",
    "| `leaving = model.predict_proba(X_test_scaled)[:, 1]` | the probability of class 1 |\n",
    "| `(leaving >= 0.3).astype(int)` | the classes for another threshold |\n",
    "| `roc_curve(y_test, leaving)` | the points of the ROC curve |\n",
    "| `roc_auc_score(y_test, leaving)` | the AUC (give the probabilities) |\n",
    "\n",
    "### Rules to keep\n",
    "\n",
    "1. A classifier can be wrong in two ways. Look at the confusion matrix before any single number.\n",
    "2. The second word of TP, TN, FP, FN is what the model said; the first word says whether it was right.\n",
    "3. Precision divides by what was predicted positive, recall by what is really positive.\n",
    "4. Ask which mistake costs more. A miss: recall. A false alarm: precision. Both: F1.\n",
    "5. With unbalanced classes the accuracy misleads. Use the balanced accuracy or the F1-score.\n",
    "6. The threshold trades precision for recall. The ROC curve shows the model at all thresholds, and the AUC is its area.\n",
    "7. The closer the curve comes to the top left corner, the better. $\\text{Gini} = 2 \\times \\text{AUC} - 1$.\n",
    "\n",
    "### What comes next\n",
    "\n",
    "Every model so far was a weighted sum of the features. Topic 29 starts a different family: decision trees, which ask a row of yes-or-no questions. They are judged with the measures of this lesson.\n",
    "\n",
    "Next: the practice notebook (topic-28-practice.ipynb), then Topic 29: Decision Trees."
   ],
   "id": "t28-078"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
