{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 34: Naive Bayes\n",
    "\n",
    "Asiman Data School, Module 3: Comprehensive Machine Learning. Week 17, 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-34-practice.ipynb.\n",
    "\n",
    "The cells continue from each other: a cell uses the variables of the cells above it. Parts 6 to 9 are one project that starts from the raw file, 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. Cells late in the project take a few seconds.\n",
    "\n",
    "This notebook reads the file heart_disease.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 Naive Bayes is\n",
    "2. How it decides: an example with ten patients\n",
    "3. The kinds of Naive Bayes\n",
    "4. The hyperparameters\n",
    "5. Preprocessing for Naive Bayes, and for the models still to come\n",
    "6. The project: from the raw file to the data for the models\n",
    "7. Gaussian Naive Bayes on the numbers\n",
    "8. Categorical Naive Bayes on the categories\n",
    "9. Tuning, the threshold, and the other models\n",
    "10. The workflow, step by step\n",
    "11. Common mistakes\n",
    "12. Solved problems\n",
    "13. Practice (in topic-34-practice.ipynb)\n",
    "14. Check yourself (on the website)\n",
    "15. Summary"
   ],
   "id": "t34-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction: the doctor's arithmetic\n",
    "\n",
    "What matters most in this lesson. Five things matter most today. First, Naive Bayes multiplies the prior of each class by the likelihood of every feature value and picks the class with the larger product; \"naive\" means that it treats the features as independent inside each class. Second, a value never seen in a class makes a whole product 0, so the counts are smoothed with `alpha`. Third, the kind follows the features: Gaussian for numbers, Categorical for categories, Bernoulli for yes/no, Multinomial for counts. Fourth, it needs no scaling, but the gaps must be filled, impossible zeros are gaps, and Categorical needs codes. Fifth, its decisions are often good but its probabilities are too extreme; a lower threshold or other priors raise the recall.\n",
    "\n",
    "The fourteenth lesson of Module 3. k-nearest neighbours (Topics 32 and 33) decided by distances; trees and forests (Topics 29 to 31) by questions. Naive Bayes decides by probabilities. It takes Bayes' rule from Topic 16, applies it to every feature of a row, and multiplies the evidence together. It is one of the oldest models of machine learning, it trains in a blink, it needs very little data, and on many problems it is surprisingly good.\n",
    "\n",
    "Its name says what it assumes: it is \"naive\" because it pretends that the features are independent of each other inside each class. That is almost never exactly true, and yet the decisions it makes are often right.\n",
    "\n",
    "The lesson has two steps. On paper: what Naive Bayes is and where it is used, Bayes' rule again, how the model decides (worked by hand with ten patients), the zero-frequency problem and its cure, the different kinds of Naive Bayes for different kinds of features, the Gaussian version worked by hand, the hyperparameters, and what preprocessing the model needs. Then the project on a new data file, `heart_disease.csv`: 920 patients of four hospitals, from the raw file to several Naive Bayes models, their measures, and a comparison with the models of earlier topics.\n",
    "\n",
    "You need: conditional probability and Bayes' rule (Topic 16), the normal distribution (Topic 17), the mean and the variance (Topic 18), the train/test split and cross-validation (Topic 23), encoding (Topic 25), and the measures of Topic 28.\n",
    "\n",
    "| Word | Meaning |\n",
    "| --- | --- |\n",
    "| Prior | the probability of a class before looking at the features: the share of the class in the training data |\n",
    "| Likelihood | the probability of a feature value inside a class, for example $P(\\text{chest pain} \\mid \\text{disease})$ |\n",
    "| Posterior | the probability of a class after looking at the features: what the model predicts |\n",
    "| Naive assumption | inside each class, the features are independent, so their likelihoods can be multiplied |\n",
    "| Zero-frequency problem | a value never seen in a class gets the likelihood 0, and the whole product becomes 0 |\n",
    "| Laplace smoothing | adding a small count (`alpha`) to every value, so that no likelihood is 0 |\n",
    "| Gaussian Naive Bayes | for numbers: each feature follows a normal curve inside each class |\n",
    "| Categorical Naive Bayes | for categories: each feature has its own table of probabilities inside each class |\n",
    "\n",
    "## 1. What Naive Bayes is\n",
    "\n",
    "### 1.1 The idea\n",
    "\n",
    "A doctor sees a new patient. The doctor knows that about half of all patients in the clinic have heart disease, and then looks at the symptoms one by one: chest pain during exercise makes disease more likely; a high maximum heart rate makes it less likely. Each symptom moves the estimate up or down. In the end the doctor compares: is disease or health the more likely explanation of everything the doctor has seen?\n",
    "\n",
    "Naive Bayes does exactly this, with numbers:\n",
    "\n",
    "1. Start with the prior: how common is each class? (In the training data, 54 percent of the patients have the disease.)\n",
    "2. Multiply by the likelihood of every feature value inside each class: how often does a patient with the disease have this kind of chest pain? And a healthy patient?\n",
    "3. Compare the products of the classes. The class with the larger product wins; dividing each product by their sum gives the probabilities.\n",
    "\n",
    "### 1.2 Why \"naive\"\n",
    "\n",
    "Step 2 multiplies the likelihoods of the features as if they were independent inside each class: as if knowing a patient's chest pain told nothing about the same patient's heart rate, once we know whether the patient is ill. In reality symptoms are related. The assumption is \"naive\", and it makes the probabilities too extreme (too close to 0 or 1). But the decision, which class has the larger product, is often still right, because the errors of the assumption push both classes in a similar way.\n",
    "\n",
    "### 1.3 Where Naive Bayes is used\n",
    "\n",
    "- Medicine: a first estimate of a diagnosis from symptoms and test results (the project of this lesson).\n",
    "- Banking and insurance: a fast first screening of credit applications or of suspicious transactions.\n",
    "- Weather and sensors: will it rain tomorrow, from today's temperature, pressure and humidity; is a machine about to fail, from its sensor readings.\n",
    "- Recommendation and real-time sorting: very fast predictions for millions of items, because a prediction is only a few multiplications.\n",
    "- Text: spam filters, sorting news by topic, the mood of a review. This was its most famous use, and the NLP topics (from Topic 49 on) come back to it; Topic 16 already built a tiny spam filter by hand.\n",
    "- As a baseline: it trains in milliseconds and needs no tuning, so it is a good first model to compare the others with.\n",
    "\n",
    "### 1.4 Strengths and weaknesses\n",
    "\n",
    "| Strengths | Weaknesses |\n",
    "| --- | --- |\n",
    "| Extremely fast to train and to predict | The independence assumption is almost never true |\n",
    "| Works with small data: it only needs counts, means and variances | Its probabilities are often too extreme: use them for ranking, not as exact chances |\n",
    "| Handles many features easily, also thousands of words | A value never seen in a class makes trouble (the zero-frequency problem), unless smoothed |\n",
    "| No scaling needed | The Gaussian version assumes bell-shaped numbers; skewed numbers fit badly |\n",
    "| Few hyperparameters, little to tune | Usually less accurate than well-tuned forests or boosting on rich tables of data |\n",
    "\n",
    "### 1.5 Two ways to learn a class\n",
    "\n",
    "Logistic regression (Topic 27) and k-nearest neighbours (Topic 32) learn the border between the classes directly: which rows lie on which side. Naive Bayes learns something else: what a typical member of each class looks like (how common the class is, how its blood pressure is spread, how often it has each kind of chest pain), and decides which class a new row most likely came from. Models of the first kind are called *discriminative*, models of the second kind *generative*. Because Naive Bayes only has to estimate a few counts, means and variances per class, it needs little data; because it describes every feature on its own, it misses how features work together.\n",
    "\n",
    "## 2. How it decides: an example with ten patients\n",
    "\n",
    "### 2.1 Bayes' rule again\n",
    "\n",
    "Topic 16 gave Bayes' rule. For a class (disease) and the evidence (the features of a patient):\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& P(\\text{disease} \\mid \\text{features}) \\\\[4pt]\n",
    "&= \\frac{P(\\text{disease}) \\times P(\\text{features} \\mid \\text{disease})}{P(\\text{features})}\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "The denominator $P(\\text{features})$ is the same for both classes, so to compare the classes it can be left out: the class with the larger $P(\\text{class}) \\times P(\\text{features} \\mid \\text{class})$ wins. The naive assumption then splits $P(\\text{features} \\mid \\text{class})$ into a product, one factor per feature:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& P(\\text{features} \\mid \\text{disease}) \\\\[4pt]\n",
    "&= P(\\text{feature 1} \\mid \\text{disease}) \\\\\n",
    "&\\quad \\times P(\\text{feature 2} \\mid \\text{disease}) \\times \\dots\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "### 2.2 Ten patients\n",
    "\n",
    "Ten patients, two yes/no features: chest pain during exercise (`angina`) and the \"asymptomatic\" type of chest pain (no typical pain, a type that in this data goes with disease surprisingly often).\n",
    "\n",
    "| Patient | Angina | Asymptomatic | Disease |\n",
    "| --- | --- | --- | --- |\n",
    "| 1 | yes | yes | yes |\n",
    "| 2 | yes | yes | yes |\n",
    "| 3 | yes | no | yes |\n",
    "| 4 | no | yes | yes |\n",
    "| 5 | yes | yes | yes |\n",
    "| 6 | no | yes | yes |\n",
    "| 7 | no | no | no |\n",
    "| 8 | no | no | no |\n",
    "| 9 | yes | no | no |\n",
    "| 10 | no | no | no |\n",
    "\n",
    "### 2.3 Step 1: the priors\n",
    "\n",
    "Six of the ten patients have the disease:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "P(\\text{disease}) &= \\tfrac{6}{10} = 0.6 \\\\[4pt]\n",
    "P(\\text{healthy}) &= \\tfrac{4}{10} = 0.4\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "### 2.4 Step 2: the likelihoods\n",
    "\n",
    "Count inside each class:\n",
    "\n",
    "|  | Disease (6 patients) | Healthy (4 patients) |\n",
    "| --- | --- | --- |\n",
    "| $P(\\text{angina} = \\text{yes})$ | $\\frac{4}{6} = 0.667$ | $\\frac{1}{4} = 0.25$ |\n",
    "| $P(\\text{asymptomatic} = \\text{yes})$ | $\\frac{5}{6} = 0.833$ | $\\frac{0}{4} = 0$ |\n",
    "\n",
    "### 2.5 Step 3: a new patient with angina and no asymptomatic pain\n",
    "\n",
    "A new patient has angina = yes and asymptomatic = no. The likelihoods of \"no\" are 1 minus those of \"yes\": $\\frac{1}{6} = 0.167$ for disease and $\\frac{4}{4} = 1$ for healthy.\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{disease:}\\quad & 0.6 \\times \\tfrac{4}{6} \\times \\tfrac{1}{6} = 0.0667 \\\\[6pt]\n",
    "\\text{healthy:}\\quad & 0.4 \\times 0.25 \\times 1 = 0.1\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "The healthy product is larger: the model predicts \"healthy\". Dividing each product by their sum gives the probabilities:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& P(\\text{disease} \\mid \\text{features}) \\\\[4pt]\n",
    "&= \\frac{0.0667}{0.0667 + 0.1} = \\frac{0.0667}{0.1667} = 0.4\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "A probability of 0.4 for disease, 0.6 for healthy. Notice what happened: angina alone points to disease (0.667 against 0.25), but \"no asymptomatic pain\" points strongly to health (0.167 against 1), and together they decide.\n",
    "\n",
    "### 2.6 One piece of evidence at a time\n",
    "\n",
    "The same calculation can be read like the doctor of Part 1: start with the prior and let each feature move the estimate. After every step, divide the two products by their sum:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "&\\text{before the features:} \\\\[2pt]\n",
    "&\\quad P(\\text{disease}) = 0.6 \\\\[10pt]\n",
    "&\\text{after angina = yes:} \\\\[2pt]\n",
    "&\\quad 0.6 \\times \\tfrac{4}{6} = 0.4, \\quad 0.4 \\times 0.25 = 0.1 \\\\[4pt]\n",
    "&\\quad P(\\text{disease}) = \\frac{0.4}{0.4 + 0.1} = 0.8 \\\\[10pt]\n",
    "&\\text{after asymptomatic = no:} \\\\[2pt]\n",
    "&\\quad 0.4 \\times \\tfrac{1}{6} = 0.0667, \\quad 0.1 \\times 1 = 0.1 \\\\[4pt]\n",
    "&\\quad P(\\text{disease}) = \\frac{0.0667}{0.0667 + 0.1} = 0.4\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "The picture is on the lesson page: the probability of disease as three bars, 0.6 before the features, 0.8 after angina = yes, and 0.4 after asymptomatic = no, with a dashed line at 0.5.\n",
    "\n",
    "Angina moves the estimate up from 0.6 to 0.8; the missing asymptomatic pain moves it down to 0.4. The order of the features does not matter: the products are the same in any order.\n",
    "\n",
    "### 2.7 The zero-frequency problem\n",
    "\n",
    "Now a patient with angina = yes and asymptomatic = yes:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{disease:}\\quad & 0.6 \\times \\tfrac{4}{6} \\times \\tfrac{5}{6} = 0.333 \\\\[6pt]\n",
    "\\text{healthy:}\\quad & 0.4 \\times \\tfrac{1}{4} \\times \\tfrac{0}{4} = 0\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "The healthy product is exactly 0, because no healthy patient in the ten had asymptomatic pain. The model says \"disease with probability 1\": absolutely certain, from ten patients. One unseen combination wipes out all other evidence. With more features this happens all the time: some value is always missing from some class in a small training set.\n",
    "\n",
    "### 2.8 The cure: Laplace smoothing\n",
    "\n",
    "Add a small count, `alpha`, to every value of every feature in every class, as if each value had been seen once more. With `alpha = 1` and two possible values (yes and no):\n",
    "\n",
    "$$\n",
    "P(\\text{value} \\mid \\text{class}) = \\frac{\\text{count} + 1}{\\text{class size} + 2}\n",
    "$$\n",
    "\n",
    "|  | Disease (6 patients) | Healthy (4 patients) |\n",
    "| --- | --- | --- |\n",
    "| $P(\\text{angina} = \\text{yes})$ | $\\frac{4 + 1}{6 + 2} = 0.625$ | $\\frac{1 + 1}{4 + 2} = 0.333$ |\n",
    "| $P(\\text{asymptomatic} = \\text{yes})$ | $\\frac{5 + 1}{6 + 2} = 0.75$ | $\\frac{0 + 1}{4 + 2} = 0.167$ |\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{disease:}\\quad & 0.6 \\times 0.625 \\times 0.75 = 0.281 \\\\[6pt]\n",
    "\\text{healthy:}\\quad & 0.4 \\times 0.333 \\times 0.167 = 0.022 \\\\[10pt]\n",
    "P(\\text{disease} \\mid \\text{features}) &= \\frac{0.281}{0.281 + 0.022} \\\\[4pt]\n",
    "&= \\frac{0.281}{0.303} = 0.927\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "The patient is still very likely ill, 0.927, but no longer \"certainly\". In scikit-learn the smoothing is the hyperparameter `alpha`, with the default 1.\n",
    "\n",
    "The picture is on the lesson page: the two products for the patient with angina and asymptomatic chest pain, without smoothing (0.333 against 0) and with alpha = 1 (0.281 against 0.022).\n",
    "\n",
    "## 3. The kinds of Naive Bayes\n",
    "\n",
    "The idea is always the same: prior times the likelihoods of the features. What changes is how the likelihood of a feature is computed, and that depends on the kind of feature:\n",
    "\n",
    "| Kind | In scikit-learn | Features | The likelihood of a value | Typical use |\n",
    "| --- | --- | --- | --- | --- |\n",
    "| Gaussian | `GaussianNB` | numbers | a normal curve per feature and class, with the class's mean and variance | measurements: blood pressure, temperature, sensor readings |\n",
    "| Categorical | `CategoricalNB` | categories, coded 0, 1, 2, ... | the share of the value inside the class, smoothed with `alpha` | symptoms, types, colours, yes/no |\n",
    "| Bernoulli | `BernoulliNB` | yes/no (0 and 1) | the share of 1s inside the class; a 0 counts too | yes/no features; whether a word appears or not |\n",
    "| Multinomial | `MultinomialNB` | counts | the share of each count in the class's total | word counts in texts (the NLP topics) |\n",
    "| Complement | `ComplementNB` | counts | like Multinomial, computed from all the other classes | texts with very unbalanced classes |\n",
    "\n",
    "The ten patients above used the Categorical (or Bernoulli) kind. The project uses Gaussian for the numbers, Categorical for the categories, and also shows how the two can be combined.\n",
    "\n",
    "### 3.1 The Gaussian kind, by hand\n",
    "\n",
    "For a number, there are too many possible values to count. The Gaussian kind assumes that inside each class the feature follows a normal curve (Topic 17) with the class's own mean $\\mu$ and standard deviation $\\sigma$, and uses the height of the curve as the likelihood:\n",
    "\n",
    "$$\n",
    "f(x) = \\frac{1}{\\sigma \\sqrt{2\\pi}} \\, e^{-\\frac{(x - \\mu)^2}{2\\sigma^2}}\n",
    "$$\n",
    "\n",
    "Take the maximum heart rate during an exercise test. Suppose that in the training data the patients with the disease reached on average $\\mu = 130$ beats per minute, the healthy ones $\\mu = 150$, both with $\\sigma = 20$, and that 55 percent have the disease. A new patient reached $x = 125$.\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "& \\frac{1}{20 \\sqrt{2\\pi}} = 0.01995 \\\\[10pt]\n",
    "\\text{disease:}\\quad & z = \\frac{125 - 130}{20} = -0.25 \\\\[4pt]\n",
    "& e^{-0.25^2/2} = e^{-0.03125} = 0.969 \\\\[10pt]\n",
    "\\text{healthy:}\\quad & z = \\frac{125 - 150}{20} = -1.25 \\\\[4pt]\n",
    "& e^{-1.25^2/2} = e^{-0.78125} = 0.458\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "f(125 \\mid \\text{disease}) &= 0.01995 \\times 0.969 = 0.01933 \\\\[4pt]\n",
    "f(125 \\mid \\text{healthy}) &= 0.01995 \\times 0.458 = 0.00914\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{disease:}\\quad & 0.55 \\times 0.01933 = 0.01063 \\\\[6pt]\n",
    "\\text{healthy:}\\quad & 0.45 \\times 0.00914 = 0.00411 \\\\[10pt]\n",
    "P(\\text{disease} \\mid 125) &= \\frac{0.01063}{0.01063 + 0.00411} \\\\[4pt]\n",
    "&= \\frac{0.01063}{0.01474} = 0.721\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "A low maximum heart rate fits the disease curve better: the probability of disease is 0.721. With more features, each one adds its own factor to the two products.\n",
    "\n",
    "The picture is on the lesson page: the normal curve of the patients with the disease (mean 130) and of the healthy ones (mean 150), both with a standard deviation of 20, and the heights 0.01933 and 0.00914 of the two curves at x = 125.\n",
    "\n",
    "### 3.2 Working with logarithms\n",
    "\n",
    "A product of many small probabilities quickly becomes too small for a computer (30 factors of 0.01 give $10^{-60}$). So scikit-learn adds the logarithms instead of multiplying: $\\log(a \\times b) = \\log a + \\log b$. The class with the larger sum of logarithms is the class with the larger product, so the decision is the same. The project uses this to combine two Naive Bayes models.\n",
    "\n",
    "The smoothed patient of Part 2 (angina = yes, asymptomatic = yes) with natural logarithms:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{disease:}\\quad & \\ln 0.6 + \\ln 0.625 + \\ln 0.75 \\\\[2pt]\n",
    "& = -0.511 - 0.470 - 0.288 = -1.269 \\\\[8pt]\n",
    "\\text{healthy:}\\quad & \\ln 0.4 + \\ln 0.333 + \\ln 0.167 \\\\[2pt]\n",
    "& = -0.916 - 1.099 - 1.792 = -3.807\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "The disease sum is larger (less negative), as the disease product was. Going back: $e^{-1.269} = 0.281$ and $e^{-3.807} = 0.022$, the two products of Part 2.\n",
    "\n",
    "## 4. The hyperparameters\n",
    "\n",
    "Naive Bayes has very few hyperparameters, and there is no `random_state`: nothing in it is random.\n",
    "\n",
    "| Hyperparameter | Default | Kind | Role |\n",
    "| --- | --- | --- | --- |\n",
    "| `priors` | `None` | Gaussian | the class priors; `None` takes the shares of the training data. Setting them, for example `[0.3, 0.7]`, moves every prediction towards a class, like a threshold. |\n",
    "| `var_smoothing` | `1e-9` | Gaussian | adds a tiny part of the largest variance to every variance, so that a feature with (almost) no spread in a class cannot divide by zero. Larger values flatten the normal curves. |\n",
    "| `alpha` | `1.0` | Categorical, Bernoulli, Multinomial, Complement | the Laplace smoothing count. 0 is no smoothing (the zero-frequency problem); larger values pull every likelihood towards equal shares. |\n",
    "| `fit_prior` | `True` | Categorical, Bernoulli, Multinomial | `True`: learn the priors from the data; `False`: equal priors for all classes. |\n",
    "| `class_prior` | `None` | Categorical, Bernoulli, Multinomial | set the priors by hand |\n",
    "| `binarize` | `0.0` | Bernoulli | the threshold that turns numbers into 0 and 1; `None` if the features are already 0 and 1 |\n",
    "| `min_categories` | `None` | Categorical | the number of categories of each feature, for values that appear only in the test data |\n",
    "\n",
    "Which ones matter? `alpha` is the main one for the counting kinds: try a few values with cross-validation (Topic 23). `var_smoothing` rarely matters. `priors` and `class_prior` are a second way to move the decision towards one class, like the threshold of Topic 28. Most of the time Naive Bayes works well with its defaults; the larger gains come from choosing the right kind for each feature.\n",
    "\n",
    "## 5. Preprocessing for Naive Bayes, and for the models still to come\n",
    "\n",
    "- Scaling: not needed. The Gaussian kind learns a mean and a variance for each feature and class. Scaling a feature changes its mean and variance, but the normal curve of each class changes in the same way, and the decision stays the same (the project checks it). The counting kinds work with counts, not with sizes.\n",
    "- Encoding: depends on the kind. `CategoricalNB` wants each category as a whole number 0, 1, 2, ...: an ordinal code. Unlike k-nearest neighbours, the order of the codes means nothing to it: it only counts how often each code appears in each class, so no one-hot encoding is needed. `GaussianNB` can take one-hot columns, but 0s and 1s are not bell-shaped, so the Categorical or Bernoulli kind fits them better.\n",
    "- Missing values: must be filled. scikit-learn's Naive Bayes does not accept gaps. Numbers get the training median; a missing category can become a category of its own (`\"unknown\"`). (In theory Naive Bayes could simply leave out the factor of a missing feature, since every feature has its own factor; scikit-learn does not do this.)\n",
    "- Impossible values: they are missing values in disguise. A cholesterol of 0 is not a measurement but a gap that was written as 0. Left as 0, it would pull the mean and widen the normal curve of its class.\n",
    "- Outliers: they matter for the Gaussian kind, because they pull the mean and the variance. The counting kinds do not care.\n",
    "- Skewed numbers fit a normal curve badly. A logarithm can help (Topic 24).\n",
    "- Correlated or repeated features break the naive assumption more than anything: two copies of the same symptom are counted twice, and the probabilities become even more extreme. Drop near-copies.\n",
    "- Unbalanced classes: the priors take care of the class sizes; a lower threshold or other priors raise the recall (Topic 28). Topic 41 goes further.\n",
    "\n",
    "| Model (topic) | Scaling | Encoding of text | Outliers in the features | Missing values |\n",
    "| --- | --- | --- | --- | --- |\n",
    "| Linear regression (22) | not needed for the predictions | needed | sensitive | fill |\n",
    "| Ridge, Lasso, logistic regression (26, 27) | needed | needed | sensitive | fill |\n",
    "| Decision tree, random forest, bagged trees (29, 30, 31) | not needed | needed | robust | fill (recent scikit-learn can handle them) |\n",
    "| k-nearest neighbours (32, 33) | essential: distances | needed; few, useful columns | sensitive | fill |\n",
    "| Naive Bayes (34) | not needed | codes for Categorical, one-hot for Gaussian | sensitive (Gaussian), robust (counting kinds) | fill |\n",
    "| Support vector machines, voting (35, 36) | needed for the support vector machine; voting as the models inside | needed | sensitive | fill |\n",
    "| Gradient boosting, XGBoost, LightGBM, CatBoost (37 to 40) | not needed | needed (CatBoost and LightGBM can also take categories directly) | robust | XGBoost, LightGBM and CatBoost handle them |\n",
    "| k-means, DBSCAN, PCA (43, 44) | essential: distances and variances | needed | sensitive | fill |\n",
    "\n",
    "Topic 42 will put the preprocessing and the model into one object, so that every step is fitted on the right rows.\n",
    "\n",
    "## 6. The project: from the raw file to the data for the models\n",
    "\n",
    "Now the data: `heart_disease.csv`, 920 patients of four hospitals (Cleveland, Budapest, Zurich and Long Beach), from the UCI Machine Learning Repository's well-known Heart Disease data set. The data was collected by Andras Janosi (Hungarian Institute of Cardiology, Budapest), William Steinbrunn (University Hospital, Zurich), Matthias Pfisterer (University Hospital, Basel) and Robert Detrano (V.A. Medical Center, Long Beach, and Cleveland Clinic Foundation), and the UCI Machine Learning Repository publishes it under the licence CC BY 4.0; the Swiss patients are written as Zurich in the file. There are no names, dates or other personal data in it.\n",
    "\n",
    "The column `disease` says whether a coronary artery was narrowed by more than half (1) or not (0). The codes of the original data are written as words, so that the encoding can be done in the lesson; nothing else was cleaned: the missing values, the impossible zeros and the repeated rows are all still in the file. Every step is done again and explained as if it were new. The cells continue from each other like the cells of a notebook.\n",
    "\n",
    "### 6.1 Step 1: read and look"
   ],
   "id": "t34-001"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"heart_disease.csv\")\n",
    "\n",
    "print(df.shape)\n",
    "print(df.head())"
   ],
   "id": "t34-002"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "920 patients and 15 columns:\n",
    "\n",
    "| Column | Meaning |\n",
    "| --- | --- |\n",
    "| `age`, `sex` | age in years, male or female |\n",
    "| `chest_pain` | the type of chest pain: typical angina, atypical angina, non-anginal pain, asymptomatic |\n",
    "| `resting_bp` | blood pressure at rest (mm Hg) |\n",
    "| `cholesterol` | cholesterol in the blood (mg/dl) |\n",
    "| `fasting_sugar_high` | 1 when the fasting blood sugar is above 120 mg/dl |\n",
    "| `rest_ecg` | the result of the ECG at rest |\n",
    "| `max_heart_rate` | the highest heart rate reached in an exercise test |\n",
    "| `exercise_angina` | chest pain during the exercise test: yes or no |\n",
    "| `st_depression`, `st_slope` | two measurements of the ECG during exercise |\n",
    "| `major_vessels`, `thal` | the number of major vessels coloured in an X-ray, and the result of a thallium test |\n",
    "| `hospital` | where the patient was examined |\n",
    "| `disease` | the target: 1 for heart disease, 0 for none |\n",
    "\n",
    "### 6.2 Step 2: check"
   ],
   "id": "t34-003"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.isna().sum())\n",
    "print(df.duplicated().sum())"
   ],
   "id": "t34-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Many gaps: in `major_vessels` two thirds of the values are missing, in `thal` more than half, in `st_slope` a third; smaller gaps elsewhere. And 2 repeated rows.\n",
    "\n",
    "### 6.3 Step 3: drop the repeated rows"
   ],
   "id": "t34-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = df.drop_duplicates()\n",
    "\n",
    "print(df.shape)"
   ],
   "id": "t34-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A repeated patient in the training and the test data would make the test score too good (Topic 31).\n",
    "\n",
    "### 6.4 Step 4: impossible values and outliers"
   ],
   "id": "t34-007"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df[[\"resting_bp\", \"cholesterol\"]].describe().round(1))\n",
    "print((df[\"cholesterol\"] == 0).sum(), (df[\"resting_bp\"] == 0).sum())"
   ],
   "id": "t34-008"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A cholesterol of 0 and a blood pressure of 0 are impossible for a living patient: these are missing measurements that were written as 0 (most of them come from one hospital that did not measure the cholesterol). They are turned into real gaps, `NaN`, so that they are filled like the other gaps and do not pull the means down:"
   ],
   "id": "t34-009"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "df.loc[df[\"cholesterol\"] == 0, \"cholesterol\"] = np.nan\n",
    "df.loc[df[\"resting_bp\"] == 0, \"resting_bp\"] = np.nan\n",
    "\n",
    "print(df[\"cholesterol\"].isna().sum(), df[\"resting_bp\"].isna().sum())"
   ],
   "id": "t34-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then the outliers of the five number columns, with the rule of Topic 25: a value more than 1.5 IQR below the first quartile or above the third."
   ],
   "id": "t34-011"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for column in [\"age\", \"resting_bp\", \"cholesterol\", \"max_heart_rate\", \"st_depression\"]:\n",
    "    q1 = df[column].quantile(0.25)\n",
    "    q3 = df[column].quantile(0.75)\n",
    "    iqr = q3 - q1\n",
    "    outside = ((df[column] < q1 - 1.5 * iqr) | (df[column] > q3 + 1.5 * iqr)).sum()\n",
    "    print(column, outside)"
   ],
   "id": "t34-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A few dozen values lie outside, for example blood pressures up to 200 and cholesterol values up to 603. They are rare but real: very ill patients do have such values, and the target depends on them. They stay. For the Gaussian kind they widen the normal curve of their class a little (Part 5); the categories are not affected.\n",
    "\n",
    "### 6.5 Step 5: drop the columns that cannot help"
   ],
   "id": "t34-013"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = df.drop(columns=[\"major_vessels\", \"thal\", \"hospital\"])\n",
    "\n",
    "print(df.shape)"
   ],
   "id": "t34-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- `major_vessels` and `thal` are missing for most patients: filling two thirds of a column with one value would invent most of it.\n",
    "- `hospital` is not a fact about the patient. The share of sick patients differs strongly between the hospitals (in Zurich almost all patients in the data were ill), because each hospital collected different patients. A model should judge a patient by the patient's own measurements, not by the place of the examination.\n",
    "\n",
    "### 6.6 Step 6: the target"
   ],
   "id": "t34-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df[\"disease\"].value_counts())\n",
    "print(round(df[\"disease\"].mean(), 4))"
   ],
   "id": "t34-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "55 percent of the patients have the disease: the classes are almost balanced. In medicine a missed disease is the expensive mistake (a false negative, Topic 28), so the recall matters most.\n",
    "\n",
    "### 6.7 Step 7: split\n",
    "\n",
    "Change it and run: change `test_size` to `0.3` and run: 276 patients become test data."
   ],
   "id": "t34-017"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "X = df.drop(columns=[\"disease\"])\n",
    "y = df[\"disease\"]\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": "t34-018"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "734 patients for training and 184 for the test.\n",
    "\n",
    "### 6.8 Step 8: fill the gaps with values of the training data"
   ],
   "id": "t34-019"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [\"age\", \"resting_bp\", \"cholesterol\", \"max_heart_rate\", \"st_depression\"]\n",
    "\n",
    "medians = X_train[numbers].median()\n",
    "X_train[numbers] = X_train[numbers].fillna(medians)\n",
    "X_test[numbers] = X_test[numbers].fillna(medians)\n",
    "\n",
    "print(medians)"
   ],
   "id": "t34-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The five number columns get the medians of the training patients."
   ],
   "id": "t34-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "categories = [\"sex\", \"chest_pain\", \"fasting_sugar_high\", \"rest_ecg\", \"exercise_angina\", \"st_slope\"]\n",
    "\n",
    "X_train[categories] = X_train[categories].fillna(\"unknown\")\n",
    "X_test[categories] = X_test[categories].fillna(\"unknown\")\n",
    "\n",
    "print(X_train.isna().sum().sum(), X_test.isna().sum().sum())"
   ],
   "id": "t34-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A missing category becomes a category of its own, `\"unknown\"`: for a third of the patients the ECG slope was not recorded, and \"not recorded\" can itself say something. `fasting_sugar_high` is written as 1.0 and 0.0; after the filling it is a column of the values 0.0, 1.0 and `\"unknown\"`, which the encoding of the next part treats as three categories.\n",
    "\n",
    "### 6.9 Step 9: no scaling\n",
    "\n",
    "Naive Bayes needs no scaling (Part 5); the project checks it in Part 7.\n",
    "\n",
    "## 7. Gaussian Naive Bayes on the numbers\n",
    "\n",
    "### 7.1 Train and judge"
   ],
   "id": "t34-023"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.naive_bayes import GaussianNB\n",
    "\n",
    "gauss = GaussianNB()\n",
    "gauss.fit(X_train[numbers], y_train)\n",
    "\n",
    "print(round(gauss.score(X_train[numbers], y_train), 4))\n",
    "print(round(gauss.score(X_test[numbers], y_test), 4))"
   ],
   "id": "t34-024"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`GaussianNB` lives in `sklearn.naive_bayes`. On the five numbers it reaches an accuracy of about 0.69 on the test patients. The training accuracy is not much higher: Naive Bayes is a simple model that hardly overfits.\n",
    "\n",
    "### 7.2 Inside the model"
   ],
   "id": "t34-025"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(gauss.class_prior_.round(3))\n",
    "print(gauss.theta_.round(1))\n",
    "print(np.sqrt(gauss.var_).round(1))"
   ],
   "id": "t34-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Everything the model learned is in these three tables:\n",
    "\n",
    "- `class_prior_`: the priors, the shares of healthy (0) and ill (1) patients in the training data.\n",
    "- `theta_`: the mean of each of the five numbers in each class (one row per class, in the order age, resting blood pressure, cholesterol, maximum heart rate, ST depression).\n",
    "- `var_`: the variances; their square roots are the standard deviations $\\sigma$ of the normal curves.\n",
    "\n",
    "The ill patients are older on average, reach a lower maximum heart rate (about 129 against 148) and have a larger ST depression. These differences are what the model uses.\n",
    "\n",
    "### 7.3 One patient\n",
    "\n",
    "Change it and run: change both `[[0]]` and `iloc[0]` to the position 3 and look at another patient."
   ],
   "id": "t34-027"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "patient = X_test[numbers].iloc[[0]]\n",
    "\n",
    "print(patient)\n",
    "print(gauss.predict_proba(patient).round(3))\n",
    "print(y_test.iloc[0])"
   ],
   "id": "t34-028"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The model multiplies the prior of each class by the heights of five normal curves, one per number, exactly as in Part 3, and turns the two products into probabilities.\n",
    "\n",
    "### 7.4 The same patient by hand\n",
    "\n",
    "The formula of Part 3 with the model's own means and variances gives the same answer. First the heights of the ten normal curves (one row per class, one column per number):"
   ],
   "id": "t34-029"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "heights = np.exp(-(patient.values - gauss.theta_) ** 2 / (2 * gauss.var_)) / np.sqrt(2 * np.pi * gauss.var_)\n",
    "\n",
    "print(heights.round(4))"
   ],
   "id": "t34-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then prior times the five heights for each class, and the two products divided by their sum:"
   ],
   "id": "t34-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "products = gauss.class_prior_ * heights.prod(axis=1)\n",
    "\n",
    "print(products)\n",
    "print((products / products.sum()).round(3))"
   ],
   "id": "t34-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The products are tiny (written with `e-11`, that is $\\times\\, 10^{-11}$), which is why scikit-learn works with logarithms, but their ratio is the probability of `predict_proba`. The biggest difference comes from the last column, the ST depression of 2.6: its height is far larger for the disease curve.\n",
    "\n",
    "### 7.5 Are the numbers bell-shaped?\n",
    "\n",
    "The Gaussian kind assumes a normal curve for every number in every class. A quick look:"
   ],
   "id": "t34-033"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(X_train[numbers].skew().round(2))"
   ],
   "id": "t34-034"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A skewness near 0 means a symmetric shape. The age and the maximum heart rate are close to symmetric; the cholesterol and the ST depression are skewed to the right (many small values, a long tail of large ones), so a normal curve describes them less well."
   ],
   "id": "t34-035"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "plt.hist(X_train.loc[y_train == 0, \"max_heart_rate\"], bins=20, alpha=0.6, label=\"healthy\")\n",
    "plt.hist(X_train.loc[y_train == 1, \"max_heart_rate\"], bins=20, alpha=0.6, label=\"disease\")\n",
    "plt.xlabel(\"maximum heart rate\")\n",
    "plt.legend()\n",
    "plt.show()"
   ],
   "id": "t34-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The maximum heart rate of each class forms a rough hill, and the two hills are shifted: this is the picture behind the Gaussian kind. They overlap a lot, so the heart rate alone cannot separate the classes. (The tall bars at 140 are partly made by Step 8: the training patients without a recorded heart rate all got the training median 140, which makes the curves of the Gaussian kind a little narrower.)\n",
    "\n",
    "### 7.6 What the border looks like\n",
    "\n",
    "With two numbers, age and maximum heart rate, the border of a Gaussian Naive Bayes model can be drawn. Each class has its own normal curves with its own variances, so the border is a curve, not a straight line.\n",
    "\n",
    "The picture is on the lesson page: 300 training patients by age and maximum heart rate, and the area where a Gaussian Naive Bayes model on these two numbers predicts disease (older patients with a low maximum heart rate), separated from the rest by a curved border.\n",
    "\n",
    "In the orange area the model predicts disease: older patients with a low maximum heart rate. The border bends, because the spread of each number differs a little between the classes.\n",
    "\n",
    "### 7.7 The measures of Topic 28"
   ],
   "id": "t34-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score, roc_auc_score\n",
    "\n",
    "predicted = gauss.predict(X_test[numbers])\n",
    "\n",
    "print(confusion_matrix(y_test, predicted))\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))\n",
    "print(round(roc_auc_score(y_test, gauss.predict_proba(X_test[numbers])[:, 1]), 4))"
   ],
   "id": "t34-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The numbers alone find about two thirds of the ill patients (the recall), with an AUC of about 0.77. The categories, above all the type of chest pain, are still missing.\n",
    "\n",
    "### 7.8 Scaling changes nothing"
   ],
   "id": "t34-039"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "scaler = StandardScaler()\n",
    "scaled_train = scaler.fit_transform(X_train[numbers])\n",
    "scaled_test = scaler.transform(X_test[numbers])\n",
    "\n",
    "gauss_scaled = GaussianNB()\n",
    "gauss_scaled.fit(scaled_train, y_train)\n",
    "\n",
    "print((gauss_scaled.predict(scaled_test) == predicted).mean())"
   ],
   "id": "t34-040"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The model on scaled numbers makes exactly the same predictions (a share of 1.0 agree): each normal curve is stretched together with its feature. No scaling is needed.\n",
    "\n",
    "## 8. Categorical Naive Bayes on the categories\n",
    "\n",
    "### 8.1 Encoding as codes\n",
    "\n",
    "`CategoricalNB` needs every category as a whole number. `OrdinalEncoder` (Topic 25) gives each category of each column a code 0, 1, 2, ... in alphabetical order:"
   ],
   "id": "t34-041"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import OrdinalEncoder\n",
    "\n",
    "encoder = OrdinalEncoder()\n",
    "codes_train = encoder.fit_transform(X_train[categories].astype(str))\n",
    "codes_test = encoder.transform(X_test[categories].astype(str))\n",
    "\n",
    "print(encoder.categories_[1])\n",
    "print(codes_train[:3])"
   ],
   "id": "t34-042"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The second column, `chest_pain`, has four categories: `\"asymptomatic\"` became 0, `\"atypical angina\"` 1, and so on. `.astype(str)` makes every value text first, so that the numbers 0.0 and 1.0 and the text `\"unknown\"` of `fasting_sugar_high` can be coded together. For Naive Bayes the order of the codes does not matter: it only counts how often each code appears in each class.\n",
    "\n",
    "### 8.2 Train and judge"
   ],
   "id": "t34-043"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.naive_bayes import CategoricalNB\n",
    "\n",
    "cat_nb = CategoricalNB()\n",
    "cat_nb.fit(codes_train, y_train)\n",
    "\n",
    "predicted_cat = cat_nb.predict(codes_test)\n",
    "\n",
    "print(round(cat_nb.score(codes_test, y_test), 4))\n",
    "print(round(recall_score(y_test, predicted_cat), 4))\n",
    "print(round(roc_auc_score(y_test, cat_nb.predict_proba(codes_test)[:, 1]), 4))"
   ],
   "id": "t34-044"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The six categories alone are better than the five numbers: an accuracy of about 0.77 and an AUC of about 0.87.\n",
    "\n",
    "### 8.3 Inside the model: the likelihoods of the chest pain\n",
    "\n",
    "Change it and run: change both `[1]` to `[5]` and run: the likelihoods of the ST slope."
   ],
   "id": "t34-045"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "chest = np.exp(cat_nb.feature_log_prob_[1]).round(3)\n",
    "\n",
    "print(pd.DataFrame(chest, index=[\"healthy\", \"disease\"], columns=encoder.categories_[1]))"
   ],
   "id": "t34-046"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`feature_log_prob_[1]` holds the logarithms of the likelihoods of the second feature, the chest pain, for each class; `np.exp` turns them back into probabilities. Each row adds up to 1. Among the ill patients about three quarters had \"asymptomatic\" chest pain, among the healthy only about a quarter: this one table carries much of the model's power. (The values are smoothed with `alpha = 1`, as in Part 2.)\n",
    "\n",
    "### 8.4 Is the naive assumption true here?\n",
    "\n",
    "The model treats the chest pain and the angina during exercise as independent inside each class. Among the ill training patients:"
   ],
   "id": "t34-047"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ill = X_train[y_train == 1]\n",
    "\n",
    "print(pd.crosstab(ill[\"chest_pain\"], ill[\"exercise_angina\"]))"
   ],
   "id": "t34-048"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If the two were independent, angina would be about equally common in every row. It is not: with asymptomatic chest pain 190 of 308 ill patients had angina, with the other types far fewer. The two symptoms are related, so Naive Bayes counts part of the same evidence twice. This is the price of the naive assumption, and one reason why its probabilities come out too extreme.\n",
    "\n",
    "### 8.5 Both models together\n",
    "\n",
    "The numbers and the categories each gave a product per class. The naive assumption says: multiply them. In logarithms (Part 3) that means adding the two models' sums, and subtracting the logarithm of the prior once, because each model already contains it:"
   ],
   "id": "t34-049"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "joint = gauss.predict_joint_log_proba(X_test[numbers]) + cat_nb.predict_joint_log_proba(codes_test) - np.log(gauss.class_prior_)\n",
    "\n",
    "predicted_both = joint.argmax(axis=1)\n",
    "\n",
    "print(round((predicted_both == y_test).mean(), 4))\n",
    "print(round(recall_score(y_test, predicted_both), 4))"
   ],
   "id": "t34-050"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`predict_joint_log_proba` gives, for every patient and class, the logarithm of prior times likelihoods. `argmax(axis=1)` takes the class with the larger sum. Together, the numbers and the categories reach an accuracy of 0.78 and a recall of 0.80: better than each part alone. This is the whole idea of Naive Bayes in one line: the evidence of every feature is combined by multiplying.\n",
    "\n",
    "### 8.6 Gaussian Naive Bayes on everything, with one-hot columns\n",
    "\n",
    "A simpler way to use all features is to one-hot encode the categories (Topic 25) and give everything to `GaussianNB`:"
   ],
   "id": "t34-051"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_all = pd.get_dummies(X_train.astype({\"fasting_sugar_high\": str}), drop_first=True, dtype=int)\n",
    "test_all = pd.get_dummies(X_test.astype({\"fasting_sugar_high\": str}), drop_first=True, dtype=int)\n",
    "test_all = test_all.reindex(columns=train_all.columns, fill_value=0)\n",
    "\n",
    "gauss_all = GaussianNB()\n",
    "gauss_all.fit(train_all, y_train)\n",
    "\n",
    "print(train_all.shape)\n",
    "print(round(gauss_all.score(test_all, y_test), 4))\n",
    "print(round(roc_auc_score(y_test, gauss_all.predict_proba(test_all)[:, 1]), 4))"
   ],
   "id": "t34-052"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`reindex(columns=train_all.columns, fill_value=0)` makes sure that the test data has exactly the training columns in the same order, even if a category is missing in one of the parts.\n",
    "\n",
    "The result is a lesson in itself: with all the features the Gaussian model is hardly better than with the five numbers (an accuracy of about 0.71), although its AUC of about 0.86 shows that it ranks the patients well. A 0/1 column is not bell-shaped: a normal curve fitted to 0s and 1s gives strange heights, and its probabilities around 0.5 become unreliable. The right kind for 0/1 columns is Bernoulli.\n",
    "\n",
    "### 8.7 Bernoulli Naive Bayes on the yes/no columns"
   ],
   "id": "t34-053"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.naive_bayes import BernoulliNB\n",
    "\n",
    "yes_no_train = pd.get_dummies(X_train[categories].astype(str), drop_first=True, dtype=int)\n",
    "yes_no_test = pd.get_dummies(X_test[categories].astype(str), drop_first=True, dtype=int)\n",
    "yes_no_test = yes_no_test.reindex(columns=yes_no_train.columns, fill_value=0)\n",
    "\n",
    "bernoulli = BernoulliNB()\n",
    "bernoulli.fit(yes_no_train, y_train)\n",
    "\n",
    "print(yes_no_train.shape)\n",
    "print(round(bernoulli.score(yes_no_test, y_test), 4))\n",
    "print(round(roc_auc_score(y_test, bernoulli.predict_proba(yes_no_test)[:, 1]), 4))"
   ],
   "id": "t34-054"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The six categories became 14 yes/no columns. `BernoulliNB` learns, for each column and class, the share of 1s, and it also uses the 0s: \"this patient does not have asymptomatic chest pain\" is evidence too. It does about as well as `CategoricalNB`, which is no surprise: both describe the same categories, once as codes and once as yes/no columns.\n",
    "\n",
    "## 9. Tuning, the threshold, and the other models\n",
    "\n",
    "### 9.1 `alpha` with cross-validation\n",
    "\n",
    "Change it and run: add `0` to the list of `alpha` values and run: scikit-learn warns and uses a tiny alpha instead."
   ],
   "id": "t34-055"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import cross_val_score\n",
    "\n",
    "sizes = [len(values) for values in encoder.categories_]\n",
    "print(sizes)\n",
    "\n",
    "for alpha in [0.1, 1, 10, 100]:\n",
    "    scores = cross_val_score(CategoricalNB(alpha=alpha, min_categories=sizes), codes_train, y_train, cv=5)\n",
    "    print(alpha, round(scores.mean(), 4))"
   ],
   "id": "t34-056"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`sizes` is the number of categories of each feature. It is needed for `min_categories`: a rare category, such as the `\"unknown\"` of `rest_ecg` (only 2 patients), can be missing from the training part of a fold and appear in its validation part. Without `min_categories` the model would not know that code, and the fold would fail (its score would be `nan`). With it, every model knows all the categories from the start, and an unseen one simply gets the smoothed share of `alpha`.\n",
    "\n",
    "Every line shows `alpha` and the mean accuracy of five folds. The differences are small: with 734 patients and only a few categories per feature, every value is seen often, and the smoothing changes little. `alpha` matters more with small data or many rare values, above all in texts.\n",
    "\n",
    "### 9.2 `var_smoothing`"
   ],
   "id": "t34-057"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for smoothing in [1e-9, 1e-3, 1e-1]:\n",
    "    scores = cross_val_score(GaussianNB(var_smoothing=smoothing), X_train[numbers], y_train, cv=5)\n",
    "    print(smoothing, round(scores.mean(), 4))"
   ],
   "id": "t34-058"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The default `1e-9` is best here; a large `var_smoothing` flattens all the normal curves and hides the differences between the classes.\n",
    "\n",
    "### 9.3 More recall: a lower threshold\n",
    "\n",
    "For a doctor a missed disease is worse than a false alarm. Naive Bayes gives probabilities, so the threshold can be lowered (Topic 28):\n",
    "\n",
    "Change it and run: change `0.3` to `0.4` and run."
   ],
   "id": "t34-059"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "disease_prob = cat_nb.predict_proba(codes_test)[:, 1]\n",
    "predicted_03 = (disease_prob >= 0.3).astype(int)\n",
    "\n",
    "print(round(recall_score(y_test, predicted_cat), 4), round(precision_score(y_test, predicted_cat), 4))\n",
    "print(round(recall_score(y_test, predicted_03), 4), round(precision_score(y_test, predicted_03), 4))"
   ],
   "id": "t34-060"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The first line is the threshold 0.5 (recall, then precision), the second the threshold 0.3. With 0.3 the Categorical model finds about 92 of every 100 ill patients instead of 77, and its precision hardly falls: on this split the extra alarms are mostly right.\n",
    "\n",
    "### 9.4 Other priors do the same\n",
    "\n",
    "The prior is a factor in every product, so changing it moves every decision, like a threshold. `class_prior` sets it by hand:\n",
    "\n",
    "Change it and run: change the priors to `[0.5, 0.5]` and run."
   ],
   "id": "t34-061"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cat_prior = CategoricalNB(class_prior=[0.3, 0.7])\n",
    "cat_prior.fit(codes_train, y_train)\n",
    "\n",
    "predicted_prior = cat_prior.predict(codes_test)\n",
    "\n",
    "print(round(recall_score(y_test, predicted_prior), 4), round(precision_score(y_test, predicted_prior), 4))"
   ],
   "id": "t34-062"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With the priors 0.3 for healthy and 0.7 for disease the recall rises to about 0.91, much like the threshold 0.3. The two are two handles on the same thing: how much evidence is needed before the model says \"disease\".\n",
    "\n",
    "### 9.5 How sure is the model?\n",
    "\n",
    "Part 1 said that the probabilities of Naive Bayes are often too extreme. Look at the patients for whom it is very sure:"
   ],
   "id": "t34-063"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sure = disease_prob > 0.9\n",
    "\n",
    "print(sure.sum())\n",
    "print(round(disease_prob[sure].mean(), 3))\n",
    "print(round(y_test[sure].mean(), 3))"
   ],
   "id": "t34-064"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The model gave 61 test patients a probability of disease above 0.9, on average 0.967. If these were exact chances, about 97 of every 100 of them would be ill; in fact 0.885 of them, about 88 of every 100, were. The model is more sure than it should be: its decisions are good, but its probabilities are not exact chances.\n",
    "\n",
    "### 9.6 Naive Bayes against the models of earlier topics\n",
    "\n",
    "The same one-hot data, now scaled, for logistic regression (Topic 27) and k-nearest neighbours (Topic 32), which need scaling:"
   ],
   "id": "t34-065"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "\n",
    "scaler_all = StandardScaler()\n",
    "train_scaled = scaler_all.fit_transform(train_all)\n",
    "test_scaled = scaler_all.transform(test_all)\n",
    "\n",
    "logistic = LogisticRegression()\n",
    "logistic.fit(train_scaled, y_train)\n",
    "\n",
    "knn = KNeighborsClassifier(n_neighbors=15)\n",
    "knn.fit(train_scaled, y_train)\n",
    "\n",
    "print(round(roc_auc_score(y_test, logistic.predict_proba(test_scaled)[:, 1]), 4))\n",
    "print(round(roc_auc_score(y_test, knn.predict_proba(test_scaled)[:, 1]), 4))"
   ],
   "id": "t34-066"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The AUC of logistic regression and of k-nearest neighbours on the same patients: about 0.87, the same as the AUC of `CategoricalNB` (0.87). In ranking the patients, Naive Bayes with no tuning is as good as both.\n",
    "\n",
    "### 9.7 The scores of every model"
   ],
   "id": "t34-067"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "models = [\n",
    "    (\"Gaussian, five numbers\", gauss.predict(X_test[numbers])),\n",
    "    (\"Categorical, six categories\", predicted_cat),\n",
    "    (\"both combined\", predicted_both),\n",
    "    (\"Gaussian, one-hot, all\", gauss_all.predict(test_all)),\n",
    "    (\"Bernoulli, yes/no columns\", bernoulli.predict(yes_no_test)),\n",
    "    (\"logistic regression\", logistic.predict(test_scaled)),\n",
    "    (\"k-nearest neighbours\", knn.predict(test_scaled)),\n",
    "]\n",
    "\n",
    "for name, model_predicted in models:\n",
    "    print(name, round((model_predicted == y_test).mean(), 4), round(recall_score(y_test, model_predicted), 4))"
   ],
   "id": "t34-068"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every line shows a model, its test accuracy and its recall on the same 184 patients."
   ],
   "id": "t34-069"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "names = [name for name, model_predicted in models]\n",
    "recalls = [recall_score(y_test, model_predicted) for name, model_predicted in models]\n",
    "\n",
    "plt.barh(names, recalls)\n",
    "plt.xlim(0.5, 0.9)\n",
    "plt.xlabel(\"test recall\")\n",
    "plt.title(\"Naive Bayes and the models of earlier topics\")\n",
    "plt.show()"
   ],
   "id": "t34-070"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "What the comparison shows:\n",
    "\n",
    "- The numbers alone are the weakest; the categories carry more information about this disease.\n",
    "- The right kind for each feature matters: the Gaussian model on one-hot columns is weak, the Categorical and Bernoulli models on the same categories are good, and the combined model (Gaussian for the numbers, Categorical for the categories) is the best Naive Bayes model.\n",
    "- In accuracy and recall at the threshold 0.5, logistic regression and k-nearest neighbours are better on this data; in AUC they are equal. The naive assumption costs a little: chest pain, exercise angina and the ST slope are related symptoms, and Naive Bayes counts their evidence as if they were separate.\n",
    "- With a lower threshold (0.3), the Categorical model reaches a recall above all the others at 0.5. Naive Bayes is a fast, solid first model; the later topics bring models that usually pull ahead on rich data.\n",
    "\n",
    "## 10. 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 | 920 patients, 15 columns |\n",
    "| 2. Check | missing values, repeated rows | many gaps, 2 copies |\n",
    "| 3. Repeated rows | drop them before the split | 918 patients left |\n",
    "| 4. Impossible values | zeros that are really gaps | cholesterol and blood pressure of 0 become `NaN` |\n",
    "| 5. Useless columns | mostly missing, or not about the patient | `major_vessels`, `thal`, `hospital` |\n",
    "| 6. Target | the share of each class | 55 percent ill: almost balanced; recall matters |\n",
    "| 7. Split | training and test data | 734 and 184 |\n",
    "| 8. Fill | training medians; `\"unknown\"` for categories | after the split |\n",
    "| 9. Scale | not needed for Naive Bayes | checked: the same predictions |\n",
    "| 10. Model | `GaussianNB` on the numbers | accuracy about 0.69 |\n",
    "| 11. Encode and model | `OrdinalEncoder`, `CategoricalNB`; `BernoulliNB` on yes/no columns | accuracy about 0.77, AUC about 0.87 |\n",
    "| 12. Combine | add the joint logarithms | accuracy 0.78, recall 0.80 |\n",
    "| 13. Tune | `alpha` (with `min_categories`), `var_smoothing` with cross-validation; threshold | small differences; recall 0.77 to 0.92 with 0.3 |\n",
    "| 14. Compare | the same test data, the same measures | the same AUC as logistic regression and k-nearest neighbours, a lower accuracy |\n",
    "\n",
    "## 11. Common mistakes\n",
    "\n",
    "| Mistake | Why it is wrong | Right |\n",
    "| --- | --- | --- |\n",
    "| Treating the probabilities as exact chances. | The naive assumption makes them too extreme. | Use them to rank and to decide; check them before trusting them as chances. |\n",
    "| Setting `alpha=0`. | One unseen value makes a whole class impossible. | Keep a small `alpha`, 1 by default. |\n",
    "| Scaling the features \"to be safe\". | It changes nothing for Naive Bayes. | Save the step; scale for the models that need it. |\n",
    "| Leaving impossible zeros in. | They pull the means and widen the normal curves. | Turn them into gaps and fill them. |\n",
    "| Giving text columns to `GaussianNB` or `CategoricalNB`. | scikit-learn needs numbers. | One-hot for Gaussian, codes for Categorical. |\n",
    "| Fitting the encoder or the medians on all the data. | The test data then helps to build the model. | Fit them on the training data. |\n",
    "| Using `GaussianNB` on strongly skewed numbers without a look. | A normal curve fits them badly. | Look at the histogram; a logarithm can help. |\n",
    "| Keeping two copies of the same information. | The naive assumption counts the evidence twice. | Drop near-copies. |\n",
    "| Using `MultinomialNB` for measurements. | It is made for counts, such as words. | Gaussian for measurements, Categorical for categories. |\n",
    "| Judging a medical model by its accuracy only. | Missed diseases are the costly mistakes. | Look at the recall; lower the threshold if needed. |\n",
    "\n",
    "## 12. Solved problems\n",
    "\n",
    "The first four problems are short and solved by hand. Problems 5 to 16 are one project on `heart_disease.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. Prior times likelihood\n",
    "\n",
    "In a training set, 30 percent of the emails of a company's support desk are complaints. The word \"refund\" appears in 60 percent of the complaints and in 10 percent of the other emails. What is the probability that an email with \"refund\" is a complaint?\n",
    "\n",
    "Idea. Prior times likelihood for each class, then divide by the sum (Part 2).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{complaint:}\\quad & 0.3 \\times 0.6 = 0.18 \\\\[4pt]\n",
    "\\text{other:}\\quad & 0.7 \\times 0.1 = 0.07 \\\\[8pt]\n",
    "& P(\\text{complaint} \\mid \\text{refund}) \\\\[4pt]\n",
    "& = \\frac{0.18}{0.18 + 0.07} = \\frac{0.18}{0.25} = 0.72\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: the word is six times more common in complaints, which turns a prior of 0.3 into 0.72.\n",
    "\n",
    "Problem 2. Two features\n",
    "\n",
    "Patients with the disease: 70 percent have high blood pressure and 40 percent smoke. Healthy patients: 30 percent and 20 percent. The prior of the disease is 0.5. A new patient has high blood pressure and smokes. Find the probability of disease with the naive assumption.\n",
    "\n",
    "Idea. Multiply the likelihoods of both features in each class (Part 2).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{disease:}\\quad & 0.5 \\times 0.7 \\times 0.4 = 0.14 \\\\[4pt]\n",
    "\\text{healthy:}\\quad & 0.5 \\times 0.3 \\times 0.2 = 0.03 \\\\[8pt]\n",
    "& P(\\text{disease} \\mid \\text{both}) \\\\[4pt]\n",
    "& = \\frac{0.14}{0.14 + 0.03} = \\frac{0.14}{0.17} = 0.824\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: both features point to disease, and the naive product strengthens them.\n",
    "\n",
    "Problem 3. Laplace smoothing\n",
    "\n",
    "In 8 healthy patients, the value \"typical angina\" of a feature with 4 categories appeared 0 times. Find its likelihood among the healthy (a) without smoothing, (b) with `alpha = 1`.\n",
    "\n",
    "Idea. With smoothing: $\\frac{\\text{count} + \\alpha}{\\text{class size} + \\alpha \\times \\text{categories}}$, where $\\alpha$ is `alpha` (Part 2).\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\text{without smoothing:}\\quad & \\tfrac{0}{8} = 0 \\\\[6pt]\n",
    "\\text{with alpha} = 1\\text{:}\\quad & \\frac{0 + 1}{8 + 4} = \\frac{1}{12} = 0.083\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: without smoothing one unseen value would make \"healthy\" impossible for every patient with typical angina; with smoothing it only makes it less likely.\n",
    "\n",
    "Problem 4. The Gaussian likelihood\n",
    "\n",
    "Healthy patients have a resting blood pressure with $\\mu = 130$ and $\\sigma = 15$. Compute the height of their normal curve at $x = 145$.\n",
    "\n",
    "Idea. The normal curve of Part 3.\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "z &= \\frac{145 - 130}{15} = 1 \\\\[6pt]\n",
    "\\frac{1}{15 \\sqrt{2\\pi}} &= 0.0266 \\\\[6pt]\n",
    "f(145) &= 0.0266 \\times e^{-0.5} \\\\[2pt]\n",
    "&= 0.0266 \\times 0.607 = 0.0161\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "Why: one standard deviation from the mean the curve has about 61 percent of its highest value.\n",
    "\n",
    "Problem 5. Read and check\n",
    "\n",
    "Read the file. Print its shape, the number of repeated rows and the number of patients with a cholesterol of 0.\n",
    "\n",
    "Idea. The first look (Part 6)."
   ],
   "id": "t34-071"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"heart_disease.csv\")\n",
    "\n",
    "print(df.shape)\n",
    "print(df.duplicated().sum())\n",
    "print((df[\"cholesterol\"] == 0).sum())"
   ],
   "id": "t34-072"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: copies to drop, and many impossible zeros to turn into gaps.\n",
    "\n",
    "Problem 6. Clean\n",
    "\n",
    "Drop the repeated rows, turn the zeros of `cholesterol` and `resting_bp` into `NaN`, and drop `major_vessels`, `thal` and `hospital`. Print the shape.\n",
    "\n",
    "Idea. Impossible values are gaps in disguise; columns that are mostly missing or not about the patient go (Part 6)."
   ],
   "id": "t34-073"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "df = df.drop_duplicates()\n",
    "df.loc[df[\"cholesterol\"] == 0, \"cholesterol\"] = np.nan\n",
    "df.loc[df[\"resting_bp\"] == 0, \"resting_bp\"] = np.nan\n",
    "df = df.drop(columns=[\"major_vessels\", \"thal\", \"hospital\"])\n",
    "\n",
    "print(df.shape)"
   ],
   "id": "t34-074"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: 918 patients, eleven 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 shapes.\n",
    "\n",
    "Idea. The split comes before any value is learned from the data."
   ],
   "id": "t34-075"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "X = df.drop(columns=[\"disease\"])\n",
    "y = df[\"disease\"]\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": "t34-076"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: 688 patients to learn from and 230 to judge with.\n",
    "\n",
    "Problem 8. Fill\n",
    "\n",
    "Fill the five number columns with the training medians and the six category columns with `\"unknown\"`. Print the number of gaps left in `X_train` and `X_test`.\n",
    "\n",
    "Idea. Medians from the training data; missing categories as a category of their own (Part 6)."
   ],
   "id": "t34-077"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [\"age\", \"resting_bp\", \"cholesterol\", \"max_heart_rate\", \"st_depression\"]\n",
    "categories = [\"sex\", \"chest_pain\", \"fasting_sugar_high\", \"rest_ecg\", \"exercise_angina\", \"st_slope\"]\n",
    "\n",
    "medians = X_train[numbers].median()\n",
    "X_train[numbers] = X_train[numbers].fillna(medians)\n",
    "X_test[numbers] = X_test[numbers].fillna(medians)\n",
    "\n",
    "X_train[categories] = X_train[categories].fillna(\"unknown\")\n",
    "X_test[categories] = X_test[categories].fillna(\"unknown\")\n",
    "\n",
    "print(X_train.isna().sum().sum(), X_test.isna().sum().sum())"
   ],
   "id": "t34-078"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: no gaps are left, and the test data did not help to compute the medians.\n",
    "\n",
    "Problem 9. Gaussian Naive Bayes\n",
    "\n",
    "Train a `GaussianNB` on the five numbers. Print its test accuracy and its recall, rounded to 4 decimals.\n",
    "\n",
    "Idea. The Gaussian kind for numbers (Part 7)."
   ],
   "id": "t34-079"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.naive_bayes import GaussianNB\n",
    "from sklearn.metrics import recall_score, roc_auc_score\n",
    "\n",
    "gauss = GaussianNB()\n",
    "gauss.fit(X_train[numbers], y_train)\n",
    "\n",
    "print(round(gauss.score(X_test[numbers], y_test), 4))\n",
    "print(round(recall_score(y_test, gauss.predict(X_test[numbers])), 4))"
   ],
   "id": "t34-080"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the numbers alone give a fair but modest model.\n",
    "\n",
    "Problem 10. The means of the classes\n",
    "\n",
    "Print `theta_` of the model, rounded to 1 decimal.\n",
    "\n",
    "Idea. The mean of every number in every class (Part 7)."
   ],
   "id": "t34-081"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(gauss.theta_.round(1))"
   ],
   "id": "t34-082"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the second row (disease) has the higher age and ST depression and the lower maximum heart rate.\n",
    "\n",
    "Problem 11. Codes\n",
    "\n",
    "Encode the six category columns with an `OrdinalEncoder` fitted on the training data (with `.astype(str)`). Print the shape of the coded training data.\n",
    "\n",
    "Idea. Categorical Naive Bayes needs codes (Part 8)."
   ],
   "id": "t34-083"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import OrdinalEncoder\n",
    "\n",
    "encoder = OrdinalEncoder()\n",
    "codes_train = encoder.fit_transform(X_train[categories].astype(str))\n",
    "codes_test = encoder.transform(X_test[categories].astype(str))\n",
    "\n",
    "print(codes_train.shape)"
   ],
   "id": "t34-084"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: six coded columns, one per category feature.\n",
    "\n",
    "Problem 12. Categorical Naive Bayes\n",
    "\n",
    "Train a `CategoricalNB` on the codes. Print its test accuracy, recall and AUC, rounded to 4 decimals.\n",
    "\n",
    "Idea. The Categorical kind for categories (Part 8)."
   ],
   "id": "t34-085"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.naive_bayes import CategoricalNB\n",
    "\n",
    "cat_nb = CategoricalNB()\n",
    "cat_nb.fit(codes_train, y_train)\n",
    "\n",
    "print(round(cat_nb.score(codes_test, y_test), 4))\n",
    "print(round(recall_score(y_test, cat_nb.predict(codes_test)), 4))\n",
    "print(round(roc_auc_score(y_test, cat_nb.predict_proba(codes_test)[:, 1]), 4))"
   ],
   "id": "t34-086"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: on this split too the categories beat the numbers.\n",
    "\n",
    "Problem 13. Both together\n",
    "\n",
    "Combine the two models by adding their joint logarithms and subtracting the logarithm of the prior once. Print the accuracy of the combined decision, rounded to 4 decimals.\n",
    "\n",
    "Idea. The naive product of all features, in logarithms (Part 8)."
   ],
   "id": "t34-087"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "joint = gauss.predict_joint_log_proba(X_test[numbers]) + cat_nb.predict_joint_log_proba(codes_test) - np.log(gauss.class_prior_)\n",
    "\n",
    "predicted_both = joint.argmax(axis=1)\n",
    "\n",
    "print(round((predicted_both == y_test).mean(), 4))"
   ],
   "id": "t34-088"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: all eleven features together; on this split the combination is a little better than the categories alone (0.80).\n",
    "\n",
    "Problem 14. `alpha` with cross-validation\n",
    "\n",
    "For `alpha` = 0.1, 1 and 10, print `alpha` and the mean accuracy of a 5-fold cross-validation of `CategoricalNB` on the coded training data, rounded to 4 decimals. Give the model `min_categories`: the number of categories of each feature.\n",
    "\n",
    "Idea. The smoothing count chosen without the test data (Part 9)."
   ],
   "id": "t34-089"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import cross_val_score\n",
    "\n",
    "sizes = [len(values) for values in encoder.categories_]\n",
    "\n",
    "for alpha in [0.1, 1, 10]:\n",
    "    scores = cross_val_score(CategoricalNB(alpha=alpha, min_categories=sizes), codes_train, y_train, cv=5)\n",
    "    print(alpha, round(scores.mean(), 4))"
   ],
   "id": "t34-090"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: small differences: every category is seen often enough. `min_categories` keeps a fold from failing on a category its training part has not seen.\n",
    "\n",
    "Problem 15. A lower threshold\n",
    "\n",
    "Predict \"disease\" when the probability of `cat_nb` is at least 0.3. Print the recall and the precision, rounded to 4 decimals.\n",
    "\n",
    "Idea. More recall for a medical model (Part 9)."
   ],
   "id": "t34-091"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import precision_score\n",
    "\n",
    "disease_prob = cat_nb.predict_proba(codes_test)[:, 1]\n",
    "predicted_03 = (disease_prob >= 0.3).astype(int)\n",
    "\n",
    "print(round(recall_score(y_test, predicted_03), 4))\n",
    "print(round(precision_score(y_test, predicted_03), 4))"
   ],
   "id": "t34-092"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: fewer missed patients, more false alarms.\n",
    "\n",
    "Problem 16. Scaling changes nothing\n",
    "\n",
    "Train a `GaussianNB` on the five numbers scaled with a `StandardScaler` fitted on the training data. Print the share of test patients for which it predicts the same as `gauss`.\n",
    "\n",
    "Idea. The normal curves stretch together with their features (Part 7)."
   ],
   "id": "t34-093"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "scaler = StandardScaler()\n",
    "gauss_scaled = GaussianNB()\n",
    "gauss_scaled.fit(scaler.fit_transform(X_train[numbers]), y_train)\n",
    "\n",
    "same = gauss_scaled.predict(scaler.transform(X_test[numbers])) == gauss.predict(X_test[numbers])\n",
    "\n",
    "print(same.mean())"
   ],
   "id": "t34-094"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: 1.0: every prediction is the same.\n",
    "\n",
    "## 15. Summary\n",
    "\n",
    "|  | Formula or rule | Meaning |\n",
    "| --- | --- | --- |\n",
    "| Bayes' rule | $P(c \\mid x) = \\frac{P(c)\\,P(x \\mid c)}{P(x)}$ | the posterior from prior and likelihood |\n",
    "| Naive assumption | $P(x \\mid c) = P(x_1 \\mid c) \\times P(x_2 \\mid c) \\times \\dots$ | the features are independent inside each class |\n",
    "| Decision | the class with the largest prior times likelihoods | the probabilities are the products divided by their sum |\n",
    "| Laplace smoothing | $\\frac{\\text{count} + \\alpha}{\\text{class size} + \\alpha \\times \\text{categories}}$ | no likelihood is 0 |\n",
    "| Gaussian likelihood | $\\frac{1}{\\sigma\\sqrt{2\\pi}}\\, e^{-\\frac{(x - \\mu)^2}{2\\sigma^2}}$ | the height of the class's normal curve |\n",
    "| Logarithms | $\\log(ab) = \\log a + \\log b$ | sums instead of tiny products |\n",
    "\n",
    "| Code | What it does |\n",
    "| --- | --- |\n",
    "| `GaussianNB()` | Naive Bayes for numbers |\n",
    "| `CategoricalNB(alpha=1)` | Naive Bayes for coded categories |\n",
    "| `BernoulliNB()`, `MultinomialNB()`, `ComplementNB()` | for yes/no, for counts, for unbalanced counts |\n",
    "| `OrdinalEncoder()` | categories to codes 0, 1, 2, ... |\n",
    "| `gauss.theta_`, `gauss.var_`, `class_prior_` | the means, the variances, the priors |\n",
    "| `cat_nb.feature_log_prob_` | the logarithms of the likelihoods of the categories |\n",
    "| `predict_joint_log_proba(X)` | the logarithm of prior times likelihoods, per class |\n",
    "\n",
    "### Rules to keep\n",
    "\n",
    "1. Naive Bayes multiplies the prior by the likelihood of every feature inside each class and takes the class with the larger product.\n",
    "2. Use Laplace smoothing (`alpha`) so that an unseen value cannot make a class impossible.\n",
    "3. Choose the kind for the features: Gaussian for numbers, Categorical for categories, Bernoulli for yes/no, Multinomial for counts.\n",
    "4. No scaling; fill the gaps; turn impossible values into gaps; codes for `CategoricalNB`.\n",
    "5. Trust its decisions more than its exact probabilities; lower the threshold when the recall matters.\n",
    "\n",
    "### What comes next\n",
    "\n",
    "Topic 35 brings support vector machines, which draw the widest possible border between the classes, and voting, which lets several different models decide together.\n",
    "\n",
    "Next: the practice notebook (topic-34-practice.ipynb), then Topic 35: Support Vector Machines and Voting - Classification."
   ],
   "id": "t34-095"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
