Asiman Data School

Module 3, topic 34, week 17, Thursday

Naive Bayes

Bayes' rule for every feature: the prior times the likelihoods, why it is called naive, the zero-frequency problem and Laplace smoothing, the Gaussian, Categorical and Bernoulli kinds, and a medical project from the raw file to combined models, a lower threshold and a comparison with earlier models.

Introduction: the doctor's arithmetic

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.

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.

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.

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.

What you will learn

  1. 1.What Naive Bayes is, where it is used, and why it is called naive
  2. 2.How it decides: prior times likelihoods, for each class, then the class with the larger product
  3. 3.The zero-frequency problem and Laplace smoothing
  4. 4.The kinds of Naive Bayes: Gaussian, Categorical, Bernoulli, Multinomial and Complement, and which features each one takes
  5. 5.The Gaussian version: a normal curve per feature and class, worked by hand
  6. 6.The hyperparameters (var_smoothing, alpha, priors, fit_prior, binarize) and their roles
  7. 7.What scaling, encoding, missing values, outliers and correlated features mean for Naive Bayes, and for the models still to come
  8. 8.A whole project on medical data: from the raw file to tuned models, their measures, and a comparison with logistic regression and k-nearest neighbours
The words of this lesson
WordMeaning
Priorthe probability of a class before looking at the features: the share of the class in the training data
Likelihoodthe probability of a feature value inside a class, for example P(chest pain∣disease)P(\text{chest pain} \mid \text{disease})
Posteriorthe probability of a class after looking at the features: what the model predicts
Naive assumptioninside each class, the features are independent, so their likelihoods can be multiplied
Zero-frequency problema value never seen in a class gets the likelihood 0, and the whole product becomes 0
Laplace smoothingadding a small count (alpha) to every value, so that no likelihood is 0
Gaussian Naive Bayesfor numbers: each feature follows a normal curve inside each class
Categorical Naive Bayesfor categories: each feature has its own table of probabilities inside each class

1What Naive Bayes is

1.1The idea

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?

Naive Bayes does exactly this, with numbers:

  1. Start with the prior: how common is each class? (In the training data, 54 percent of the patients have the disease.)
  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?
  3. Compare the products of the classes. The class with the larger product wins; dividing each product by their sum gives the probabilities.

1.2Why "naive"

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.

1.3Where Naive Bayes is used

  • Medicine: a first estimate of a diagnosis from symptoms and test results (the project of this lesson).
  • Banking and insurance: a fast first screening of credit applications or of suspicious transactions.
  • Weather and sensors: will it rain tomorrow, from today's temperature, pressure and humidity; is a machine about to fail, from its sensor readings.
  • Recommendation and real-time sorting: very fast predictions for millions of items, because a prediction is only a few multiplications.
  • 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.
  • As a baseline: it trains in milliseconds and needs no tuning, so it is a good first model to compare the others with.

1.4Strengths and weaknesses

Strengths and weaknesses
StrengthsWeaknesses
Extremely fast to train and to predictThe independence assumption is almost never true
Works with small data: it only needs counts, means and variancesIts probabilities are often too extreme: use them for ranking, not as exact chances
Handles many features easily, also thousands of wordsA value never seen in a class makes trouble (the zero-frequency problem), unless smoothed
No scaling neededThe Gaussian version assumes bell-shaped numbers; skewed numbers fit badly
Few hyperparameters, little to tuneUsually less accurate than well-tuned forests or boosting on rich tables of data

1.5Two ways to learn a class

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.

Try it yourself

(a) What does "naive" stand for? (b) Does Naive Bayes learn the border between the classes, or what a typical member of each class looks like? (c) Are its probabilities exact chances? (d) Is it slow or fast to train?

Show a hint
Look at "Why naive", "Two ways to learn a class" and the table of strengths and weaknesses.
Show the solution

Answer: (a) independent features inside each class; (b) a typical member of each class; (c) no, often too extreme; (d) fast.

It multiplies the features' likelihoods as if they were independent; it describes each class with counts, means and variances, which is quick and needs little data, but makes the probabilities too extreme.

2How it decides: an example with ten patients

2.1Bayes' rule again

Topic 16 gave Bayes' rule. For a class (disease) and the evidence (the features of a patient):

P(disease∣features)=P(disease)×P(features∣disease)P(features)\begin{aligned} & P(\text{disease} \mid \text{features}) \\[4pt] &= \frac{P(\text{disease}) \times P(\text{features} \mid \text{disease})}{P(\text{features})} \end{aligned}

The denominator P(features)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(class)×P(features∣class)P(\text{class}) \times P(\text{features} \mid \text{class}) wins. The naive assumption then splits P(features∣class)P(\text{features} \mid \text{class}) into a product, one factor per feature:

P(features∣disease)=P(feature 1∣disease)×P(feature 2∣disease)×…\begin{aligned} & P(\text{features} \mid \text{disease}) \\[4pt] &= P(\text{feature 1} \mid \text{disease}) \\ &\quad \times P(\text{feature 2} \mid \text{disease}) \times \dots \end{aligned}

2.2Ten patients

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).

Ten patients
PatientAnginaAsymptomaticDisease
1yesyesyes
2yesyesyes
3yesnoyes
4noyesyes
5yesyesyes
6noyesyes
7nonono
8nonono
9yesnono
10nonono

2.3Step 1: the priors

Six of the ten patients have the disease:

P(disease)=610=0.6P(healthy)=410=0.4\begin{aligned} P(\text{disease}) &= \tfrac{6}{10} = 0.6 \\[4pt] P(\text{healthy}) &= \tfrac{4}{10} = 0.4 \end{aligned}

2.4Step 2: the likelihoods

Count inside each class:

Step 2: the likelihoods
Disease (6 patients)Healthy (4 patients)
P(angina=yes)P(\text{angina} = \text{yes})46=0.667\frac{4}{6} = 0.66714=0.25\frac{1}{4} = 0.25
P(asymptomatic=yes)P(\text{asymptomatic} = \text{yes})56=0.833\frac{5}{6} = 0.83304=0\frac{0}{4} = 0

2.5Step 3: a new patient with angina and no asymptomatic pain

A new patient has angina = yes and asymptomatic = no. The likelihoods of "no" are 1 minus those of "yes": 16=0.167\frac{1}{6} = 0.167 for disease and 44=1\frac{4}{4} = 1 for healthy.

disease:0.6×46×16=0.0667healthy:0.4×0.25×1=0.1\begin{aligned} \text{disease:}\quad & 0.6 \times \tfrac{4}{6} \times \tfrac{1}{6} = 0.0667 \\[6pt] \text{healthy:}\quad & 0.4 \times 0.25 \times 1 = 0.1 \end{aligned}

The healthy product is larger: the model predicts "healthy". Dividing each product by their sum gives the probabilities:

P(disease∣features)=0.06670.0667+0.1=0.06670.1667=0.4\begin{aligned} & P(\text{disease} \mid \text{features}) \\[4pt] &= \frac{0.0667}{0.0667 + 0.1} = \frac{0.0667}{0.1667} = 0.4 \end{aligned}

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.

2.6One piece of evidence at a time

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:

before the features:P(disease)=0.6after angina = yes:0.6×46=0.4,0.4×0.25=0.1P(disease)=0.40.4+0.1=0.8after asymptomatic = no:0.4×16=0.0667,0.1×1=0.1P(disease)=0.06670.0667+0.1=0.4\begin{aligned} &\text{before the features:} \\[2pt] &\quad P(\text{disease}) = 0.6 \\[10pt] &\text{after angina = yes:} \\[2pt] &\quad 0.6 \times \tfrac{4}{6} = 0.4, \quad 0.4 \times 0.25 = 0.1 \\[4pt] &\quad P(\text{disease}) = \frac{0.4}{0.4 + 0.1} = 0.8 \\[10pt] &\text{after asymptomatic = no:} \\[2pt] &\quad 0.4 \times \tfrac{1}{6} = 0.0667, \quad 0.1 \times 1 = 0.1 \\[4pt] &\quad P(\text{disease}) = \frac{0.0667}{0.0667 + 0.1} = 0.4 \end{aligned}
The new patient of Step 3, read the way a doctor would: the probability of disease is 0.6 before any feature (the prior), 0.8 after angina = yes, and 0.4 after asymptomatic = no. Every feature moves the estimate; above 0.5 the model would say disease.

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.

2.7The zero-frequency problem

Now a patient with angina = yes and asymptomatic = yes:

disease:0.6×46×56=0.333healthy:0.4×14×04=0\begin{aligned} \text{disease:}\quad & 0.6 \times \tfrac{4}{6} \times \tfrac{5}{6} = 0.333 \\[6pt] \text{healthy:}\quad & 0.4 \times \tfrac{1}{4} \times \tfrac{0}{4} = 0 \end{aligned}

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.

2.8The cure: Laplace smoothing

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):

P(value∣class)=count+1class size+2P(\text{value} \mid \text{class}) = \frac{\text{count} + 1}{\text{class size} + 2}
The cure: Laplace smoothing
Disease (6 patients)Healthy (4 patients)
P(angina=yes)P(\text{angina} = \text{yes})4+16+2=0.625\frac{4 + 1}{6 + 2} = 0.6251+14+2=0.333\frac{1 + 1}{4 + 2} = 0.333
P(asymptomatic=yes)P(\text{asymptomatic} = \text{yes})5+16+2=0.75\frac{5 + 1}{6 + 2} = 0.750+14+2=0.167\frac{0 + 1}{4 + 2} = 0.167
disease:0.6×0.625×0.75=0.281healthy:0.4×0.333×0.167=0.022P(disease∣features)=0.2810.281+0.022=0.2810.303=0.927\begin{aligned} \text{disease:}\quad & 0.6 \times 0.625 \times 0.75 = 0.281 \\[6pt] \text{healthy:}\quad & 0.4 \times 0.333 \times 0.167 = 0.022 \\[10pt] P(\text{disease} \mid \text{features}) &= \frac{0.281}{0.281 + 0.022} \\[4pt] &= \frac{0.281}{0.303} = 0.927 \end{aligned}

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.

A new patient for the ten patients of the table. Choose the two features and the smoothing alpha.

angina
asymptomatic
alpha

disease: 0.6 × 4/6 × 5/6 = 0.6 × 0.667 × 0.833 = 0.3333

healthy: 0.4 × 1/4 × 0/4 = 0.4 × 0.25 × 0 = 0

P(disease) = 1: the model predicts disease.

A product of exactly 0: one value never seen in a class makes the model 100 percent sure. Choose alpha = 1.

without smoothing

P(disease) = 1

with alpha = 1

P(disease) = 0.927

The two products for a patient with angina and asymptomatic chest pain. Without smoothing the healthy product is exactly 0, because no healthy patient of the ten had asymptomatic pain, and the model is 100 percent sure. With alpha = 1 the healthy product is small but not 0: the probability of disease is 0.927.

Try it yourself

The ten patients of the table again. A new patient has angina = no and asymptomatic = yes. (a) Without smoothing, what is the disease product? Give 3 decimals. (b) Without smoothing, what is the probability of disease? (c) With α=1\alpha = 1, what is the probability of disease? Give 3 decimals.

Show a hint
Without smoothing: P(angina=no∣disease)=26P(\text{angina} = \text{no} \mid \text{disease}) = \frac{2}{6} and P(asymptomatic=yes∣healthy)=04P(\text{asymptomatic} = \text{yes} \mid \text{healthy}) = \frac{0}{4}. With α=1\alpha = 1: 2+16+2\frac{2 + 1}{6 + 2}, 5+16+2\frac{5 + 1}{6 + 2}, 3+14+2\frac{3 + 1}{4 + 2} and 0+14+2\frac{0 + 1}{4 + 2}.
Show the solution

Answer: (a) 0.167; (b) 1; (c) 0.792.

no smoothing:disease: 0.6×26×56=0.167healthy: 0.4×34×04=0P(disease)=0.1670.167+0=1α=1:disease: 0.6×38×68=0.16875healthy: 0.4×46×16=0.04444P(disease)=0.168750.16875+0.04444P(disease)=0.168750.21319=0.792\begin{aligned} &\text{no smoothing:} \\[2pt] &\quad \text{disease: } 0.6 \times \tfrac{2}{6} \times \tfrac{5}{6} = 0.167 \\[2pt] &\quad \text{healthy: } 0.4 \times \tfrac{3}{4} \times \tfrac{0}{4} = 0 \\[4pt] &\quad P(\text{disease}) = \frac{0.167}{0.167 + 0} = 1 \\[10pt] &\alpha = 1\text{:} \\[2pt] &\quad \text{disease: } 0.6 \times \tfrac{3}{8} \times \tfrac{6}{8} = 0.16875 \\[2pt] &\quad \text{healthy: } 0.4 \times \tfrac{4}{6} \times \tfrac{1}{6} = 0.04444 \\[4pt] &\quad P(\text{disease}) = \frac{0.16875}{0.16875 + 0.04444} \\[4pt] &\quad \phantom{P(\text{disease})} = \frac{0.16875}{0.21319} = 0.792 \end{aligned}

Without smoothing the unseen value makes "healthy" impossible; with it, the patient is still likely ill, but not certainly.

3The kinds of Naive Bayes

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:

The kinds of Naive Bayes
KindIn scikit-learnFeaturesThe likelihood of a valueTypical use
GaussianGaussianNBnumbersa normal curve per feature and class, with the class's mean and variancemeasurements: blood pressure, temperature, sensor readings
CategoricalCategoricalNBcategories, coded 0, 1, 2, ...the share of the value inside the class, smoothed with alphasymptoms, types, colours, yes/no
BernoulliBernoulliNByes/no (0 and 1)the share of 1s inside the class; a 0 counts tooyes/no features; whether a word appears or not
MultinomialMultinomialNBcountsthe share of each count in the class's totalword counts in texts (the NLP topics)
ComplementComplementNBcountslike Multinomial, computed from all the other classestexts with very unbalanced classes

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.

Which kind of Naive Bayes fits this feature?

1 of 6

The resting blood pressure of a patient, in mm Hg.

3.1The Gaussian kind, by hand

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:

f(x)=1σ2π e−(x−μ)22σ2f(x) = \frac{1}{\sigma \sqrt{2\pi}} \, e^{-\frac{(x - \mu)^2}{2\sigma^2}}

Take the maximum heart rate during an exercise test. Suppose that in the training data the patients with the disease reached on average μ=130\mu = 130 beats per minute, the healthy ones μ=150\mu = 150, both with σ=20\sigma = 20, and that 55 percent have the disease. A new patient reached x=125x = 125.

1202π=0.01995disease:z=125−13020=−0.25e−0.252/2=e−0.03125=0.969healthy:z=125−15020=−1.25e−1.252/2=e−0.78125=0.458\begin{aligned} & \frac{1}{20 \sqrt{2\pi}} = 0.01995 \\[10pt] \text{disease:}\quad & z = \frac{125 - 130}{20} = -0.25 \\[4pt] & e^{-0.25^2/2} = e^{-0.03125} = 0.969 \\[10pt] \text{healthy:}\quad & z = \frac{125 - 150}{20} = -1.25 \\[4pt] & e^{-1.25^2/2} = e^{-0.78125} = 0.458 \end{aligned}
f(125∣disease)=0.01995×0.969=0.01933f(125∣healthy)=0.01995×0.458=0.00914\begin{aligned} f(125 \mid \text{disease}) &= 0.01995 \times 0.969 = 0.01933 \\[4pt] f(125 \mid \text{healthy}) &= 0.01995 \times 0.458 = 0.00914 \end{aligned}
disease:0.55×0.01933=0.01063healthy:0.45×0.00914=0.00411P(disease∣125)=0.010630.01063+0.00411=0.010630.01474=0.721\begin{aligned} \text{disease:}\quad & 0.55 \times 0.01933 = 0.01063 \\[6pt] \text{healthy:}\quad & 0.45 \times 0.00914 = 0.00411 \\[10pt] P(\text{disease} \mid 125) &= \frac{0.01063}{0.01063 + 0.00411} \\[4pt] &= \frac{0.01063}{0.01474} = 0.721 \end{aligned}

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.

Move the maximum heart rate of a new patient and choose the prior of disease. The two curves stay as in the text.

prior of disease
00.010.0260100140180220x = 125

Heights at 125: disease 0.01933, healthy 0.00913. Products: 0.55 × 0.01933 = 0.01063 and 0.45 × 0.00913 = 0.00411.

P(disease) = 0.721: the model predicts disease.

The curves cross at 140, halfway between the means. With equal priors that is where the decision changes; a larger prior of disease moves the point to the right. The tool does not round in between, so a last digit can differ from the hand calculation.

00.010.0260100140180220x = 125
  • disease: μ = 130
  • healthy: μ = 150
The maximum heart rate of the patients with the disease follows a normal curve with mean 130, that of the healthy ones a curve with mean 150 (both with a standard deviation of 20). At x = 125 the disease curve is higher (0.01933) than the healthy curve (0.00914): these heights are the two likelihoods.

3.2Working with logarithms

A product of many small probabilities quickly becomes too small for a computer (30 factors of 0.01 give 10−6010^{-60}). So scikit-learn adds the logarithms instead of multiplying: log⁡(a×b)=log⁡a+log⁡b\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.

The smoothed patient of Part 2 (angina = yes, asymptomatic = yes) with natural logarithms:

disease:ln⁡0.6+ln⁡0.625+ln⁡0.75=−0.511−0.470−0.288=−1.269healthy:ln⁡0.4+ln⁡0.333+ln⁡0.167=−0.916−1.099−1.792=−3.807\begin{aligned} \text{disease:}\quad & \ln 0.6 + \ln 0.625 + \ln 0.75 \\[2pt] & = -0.511 - 0.470 - 0.288 = -1.269 \\[8pt] \text{healthy:}\quad & \ln 0.4 + \ln 0.333 + \ln 0.167 \\[2pt] & = -0.916 - 1.099 - 1.792 = -3.807 \end{aligned}

The disease sum is larger (less negative), as the disease product was. Going back: e−1.269=0.281e^{-1.269} = 0.281 and e−3.807=0.022e^{-3.807} = 0.022, the two products of Part 2.

Try it yourself

The same two normal curves (disease: μ=130\mu = 130, healthy: μ=150\mu = 150, both σ=20\sigma = 20; priors 0.55 and 0.45). A patient reached x=160x = 160. (a) What is the height of the disease curve? Give 5 decimals. (b) Of the healthy curve? (c) What is the probability of disease? Give 2 decimals. (d) What does the model predict?

Show a hint
z=160−13020=1.5z = \frac{160 - 130}{20} = 1.5 for disease and z=160−15020=0.5z = \frac{160 - 150}{20} = 0.5 for healthy; the height is 0.01995×e−z2/20.01995 \times e^{-z^2/2}.
Show the solution

Answer: (a) 0.00648; (b) 0.01761; (c) 0.31; (d) healthy.

disease:0.01995×e−1.125=0.01995×0.3247=0.00648healthy:0.01995×e−0.125=0.01995×0.8825=0.01761products:0.55×0.00648=0.003560.45×0.01761=0.00792P(disease)=0.003560.00356+0.00792=0.31\begin{aligned} \text{disease:}\quad & 0.01995 \times e^{-1.125} \\[2pt] & = 0.01995 \times 0.3247 = 0.00648 \\[8pt] \text{healthy:}\quad & 0.01995 \times e^{-0.125} \\[2pt] & = 0.01995 \times 0.8825 = 0.01761 \\[8pt] \text{products:}\quad & 0.55 \times 0.00648 = 0.00356 \\[2pt] & 0.45 \times 0.01761 = 0.00792 \\[8pt] P(\text{disease}) &= \frac{0.00356}{0.00356 + 0.00792} = 0.31 \end{aligned}

A high maximum heart rate fits the healthy curve better, and the prior of 0.55 cannot change that.

4The hyperparameters

Naive Bayes has very few hyperparameters, and there is no random_state: nothing in it is random.

The hyperparameters
HyperparameterDefaultKindRole
priorsNoneGaussianthe 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.
var_smoothing1e-9Gaussianadds 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.
alpha1.0Categorical, Bernoulli, Multinomial, Complementthe Laplace smoothing count. 0 is no smoothing (the zero-frequency problem); larger values pull every likelihood towards equal shares.
fit_priorTrueCategorical, Bernoulli, MultinomialTrue: learn the priors from the data; False: equal priors for all classes.
class_priorNoneCategorical, Bernoulli, Multinomialset the priors by hand
binarize0.0Bernoullithe threshold that turns numbers into 0 and 1; None if the features are already 0 and 1
min_categoriesNoneCategoricalthe number of categories of each feature, for values that appear only in the test data

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.

Try it yourself

(a) Which hyperparameter is the Laplace smoothing count? (b) Which one of GaussianNB adds a tiny amount to every variance? (c) Which one sets the priors of CategoricalNB by hand? (d) Which one turns numbers into 0 and 1 in BernoulliNB?

Show a hint
Look at the table of hyperparameters.
Show the solution

Answer: (a) alpha; (b) var_smoothing; (c) class_prior; (d) binarize.

alpha is the main knob of the counting kinds; var_smoothing rarely matters; the priors move every decision like a threshold.

5Preprocessing for Naive Bayes, and for the models still to come

  • 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.
  • 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.
  • 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.)
  • 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.
  • Outliers: they matter for the Gaussian kind, because they pull the mean and the variance. The counting kinds do not care.
  • Skewed numbers fit a normal curve badly. A logarithm can help (Topic 24).
  • 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.
  • 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.
Preprocessing for Naive Bayes, and for the models still to come
Model (topic)ScalingEncoding of textOutliers in the featuresMissing values
Linear regression (22)not needed for the predictionsneededsensitivefill
Ridge, Lasso, logistic regression (26, 27)neededneededsensitivefill
Decision tree, random forest, bagged trees (29, 30, 31)not neededneededrobustfill (recent scikit-learn can handle them)
k-nearest neighbours (32, 33)essential: distancesneeded; few, useful columnssensitivefill
Naive Bayes (34)not neededcodes for Categorical, one-hot for Gaussiansensitive (Gaussian), robust (counting kinds)fill
Support vector machines, voting (35, 36)needed for the support vector machine; voting as the models insideneededsensitivefill
Gradient boosting, XGBoost, LightGBM, CatBoost (37 to 40)not neededneeded (CatBoost and LightGBM can also take categories directly)robustXGBoost, LightGBM and CatBoost handle them
k-means, DBSCAN, PCA (43, 44)essential: distances and variancesneededsensitivefill

Topic 42 will put the preprocessing and the model into one object, so that every step is fitted on the right rows.

Try it yourself

(a) Must the features of Gaussian Naive Bayes be scaled? (b) What does CategoricalNB need as input? (c) A cholesterol of 0 is in the data. What is it? (d) What happens when the same symptom is in the data twice?

Show a hint
Read the list of Part 5 once more.
Show the solution

Answer: (a) no; (b) whole-number codes; (c) a missing value; (d) its evidence is counted twice.

The normal curves stretch with their features; Categorical counts codes; impossible zeros are gaps; copies break the naive assumption.

6The project: from the raw file to the data for the models

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.

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.

The data file: heart_disease.csv

920 patients of four hospitals, 15 columns, not cleaned: missing values, impossible zeros and repeated rows are still in it. A cell marked "empty" has no value in the file: pandas shows it as NaN.

Download

Loading the table ...

6.1Step 1: read and look

Python
import pandas as pd

df = pd.read_csv("heart_disease.csv")

print(df.shape)
print(df.head())

Output

(920, 15)
   age     sex        chest_pain  ...               thal   hospital  disease
0   63    male    typical angina  ...       fixed defect  Cleveland        0
1   67    male      asymptomatic  ...             normal  Cleveland        1
2   67    male      asymptomatic  ...  reversible defect  Cleveland        1
3   37    male  non-anginal pain  ...             normal  Cleveland        0
4   41  female   atypical angina  ...             normal  Cleveland        0

[5 rows x 15 columns]

920 patients and 15 columns:

Step 1: read and look
ColumnMeaning
age, sexage in years, male or female
chest_painthe type of chest pain: typical angina, atypical angina, non-anginal pain, asymptomatic
resting_bpblood pressure at rest (mm Hg)
cholesterolcholesterol in the blood (mg/dl)
fasting_sugar_high1 when the fasting blood sugar is above 120 mg/dl
rest_ecgthe result of the ECG at rest
max_heart_ratethe highest heart rate reached in an exercise test
exercise_anginachest pain during the exercise test: yes or no
st_depression, st_slopetwo measurements of the ECG during exercise
major_vessels, thalthe number of major vessels coloured in an X-ray, and the result of a thallium test
hospitalwhere the patient was examined
diseasethe target: 1 for heart disease, 0 for none

6.2Step 2: check

Python, continues from the cells above
print(df.isna().sum())
print(df.duplicated().sum())

Output

age                     0
sex                     0
chest_pain              0
resting_bp             59
cholesterol            30
fasting_sugar_high     90
rest_ecg                2
max_heart_rate         55
exercise_angina        55
st_depression          62
st_slope              309
major_vessels         611
thal                  486
hospital                0
disease                 0
dtype: int64
2

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.

6.3Step 3: drop the repeated rows

Python, continues from the cells above
df = df.drop_duplicates()

print(df.shape)

Output

(918, 15)

A repeated patient in the training and the test data would make the test score too good (Topic 31).

6.4Step 4: impossible values and outliers

Python, continues from the cells above
print(df[["resting_bp", "cholesterol"]].describe().round(1))
print((df["cholesterol"] == 0).sum(), (df["resting_bp"] == 0).sum())

Output

       resting_bp  cholesterol
count       859.0        889.0
mean        132.1        199.1
std          19.1        110.8
min           0.0          0.0
25%         120.0        175.0
50%         130.0        223.0
75%         140.0        268.0
max         200.0        603.0
172 1

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:

Python, continues from the cells above
import numpy as np

df.loc[df["cholesterol"] == 0, "cholesterol"] = np.nan
df.loc[df["resting_bp"] == 0, "resting_bp"] = np.nan

print(df["cholesterol"].isna().sum(), df["resting_bp"].isna().sum())

Output

201 60

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.

Python, continues from the cells above
for column in ["age", "resting_bp", "cholesterol", "max_heart_rate", "st_depression"]:
    q1 = df[column].quantile(0.25)
    q3 = df[column].quantile(0.75)
    iqr = q3 - q1
    outside = ((df[column] < q1 - 1.5 * iqr) | (df[column] > q3 + 1.5 * iqr)).sum()
    print(column, outside)

Output

age 0
resting_bp 27
cholesterol 23
max_heart_rate 2
st_depression 16

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.

6.5Step 5: drop the columns that cannot help

Python, continues from the cells above
df = df.drop(columns=["major_vessels", "thal", "hospital"])

print(df.shape)

Output

(918, 12)
  • major_vessels and thal are missing for most patients: filling two thirds of a column with one value would invent most of it.
  • 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.

6.6Step 6: the target

Python, continues from the cells above
print(df["disease"].value_counts())
print(round(df["disease"].mean(), 4))

Output

disease
1    508
0    410
Name: count, dtype: int64
0.5534

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.

6.7Step 7: split

Python, continues from the cells above
from sklearn.model_selection import train_test_split

X = df.drop(columns=["disease"])
y = df["disease"]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

print(X_train.shape, X_test.shape)

Output

(734, 11) (184, 11)

Change it and run: change test_size to 0.3 and run: 276 patients become test data.

734 patients for training and 184 for the test.

6.8Step 8: fill the gaps with values of the training data

Python, continues from the cells above
numbers = ["age", "resting_bp", "cholesterol", "max_heart_rate", "st_depression"]

medians = X_train[numbers].median()
X_train[numbers] = X_train[numbers].fillna(medians)
X_test[numbers] = X_test[numbers].fillna(medians)

print(medians)

Output

age                54.0
resting_bp        130.0
cholesterol       238.0
max_heart_rate    140.0
st_depression       0.5
dtype: float64

The five number columns get the medians of the training patients.

Python, continues from the cells above
categories = ["sex", "chest_pain", "fasting_sugar_high", "rest_ecg", "exercise_angina", "st_slope"]

X_train[categories] = X_train[categories].fillna("unknown")
X_test[categories] = X_test[categories].fillna("unknown")

print(X_train.isna().sum().sum(), X_test.isna().sum().sum())

Output

0 0

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.

6.9Step 9: no scaling

Naive Bayes needs no scaling (Part 5); the project checks it in Part 7.

Try it yourself

This task continues from the cells of Part 6. Print the share of patients with the disease among the women, then among the men, each rounded to 4 decimals.
Show a hint
df[df["sex"] == "female"] keeps the women; the mean of the column disease is the share of 1s.
Show the solution
Python, continues from the cells above
women = df[df["sex"] == "female"]
men = df[df["sex"] == "male"]

print(round(women["disease"].mean(), 4))
print(round(men["disease"].mean(), 4))

Output

0.2591
0.6317

7Gaussian Naive Bayes on the numbers

7.1Train and judge

Python, continues from the cells above
from sklearn.naive_bayes import GaussianNB

gauss = GaussianNB()
gauss.fit(X_train[numbers], y_train)

print(round(gauss.score(X_train[numbers], y_train), 4))
print(round(gauss.score(X_test[numbers], y_test), 4))

Output

0.7316
0.6902

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.

7.2Inside the model

Python, continues from the cells above
print(gauss.class_prior_.round(3))
print(gauss.theta_.round(1))
print(np.sqrt(gauss.var_).round(1))

Output

[0.459 0.541]
[[ 50.7 129.5 239.4 148.3   0.4]
 [ 56.  133.8 248.  128.6   1.2]]
[[ 9.4 16.4 54.7 22.7  0.7]
 [ 8.5 19.  51.  23.2  1.2]]

Everything the model learned is in these three tables:

  • class_prior_: the priors, the shares of healthy (0) and ill (1) patients in the training data.
  • 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).
  • var_: the variances; their square roots are the standard deviations σ\sigma of the normal curves.

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.

7.3One patient

Python, continues from the cells above
patient = X_test[numbers].iloc[[0]]

print(patient)
print(gauss.predict_proba(patient).round(3))
print(y_test.iloc[0])

Output

     age  resting_bp  cholesterol  max_heart_rate  st_depression
669   59       125.0        238.0           175.0            2.6
[[0.054 0.946]]
1

Change it and run: change both [[0]] and iloc[0] to the position 3 and look at another patient.

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.

7.4The same patient by hand

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):

Python, continues from the cells above
heights = np.exp(-(patient.values - gauss.theta_) ** 2 / (2 * gauss.var_)) / np.sqrt(2 * np.pi * gauss.var_)

print(heights.round(4))

Output

[[0.0288 0.0235 0.0073 0.0088 0.0038]
 [0.0439 0.0188 0.0077 0.0023 0.1662]]

Then prior times the five heights for each class, and the two products divided by their sum:

Python, continues from the cells above
products = gauss.class_prior_ * heights.prod(axis=1)

print(products)
print((products / products.sum()).round(3))

Output

[7.61056914e-11 1.33781239e-09]
[0.054 0.946]

The products are tiny (written with e-11, that is × 10−11\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.

7.5Are the numbers bell-shaped?

The Gaussian kind assumes a normal curve for every number in every class. A quick look:

Python, continues from the cells above
print(X_train[numbers].skew().round(2))

Output

age              -0.19
resting_bp        0.61
cholesterol       1.54
max_heart_rate   -0.18
st_depression     1.23
dtype: float64

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.

Python, continues from the cells above
import matplotlib.pyplot as plt

plt.hist(X_train.loc[y_train == 0, "max_heart_rate"], bins=20, alpha=0.6, label="healthy")
plt.hist(X_train.loc[y_train == 1, "max_heart_rate"], bins=20, alpha=0.6, label="disease")
plt.xlabel("maximum heart rate")
plt.legend()
plt.show()
The chart this code draws

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.)

7.6What the border looks like

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.

30405060708080120160200agemaximum heart rate
  • disease
  • healthy
300 training patients by age and maximum heart rate (orange: disease, teal: healthy). In the orange area a Gaussian Naive Bayes model on these two numbers predicts disease: older patients with a low maximum heart rate. The border is a curve, because each class has its own variances; many dots lie on the wrong side, since two numbers are not enough. The row of dots at 140 are patients without a recorded heart rate, filled with the training median.

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.

7.7The measures of Topic 28

Python, continues from the cells above
from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score, roc_auc_score

predicted = gauss.predict(X_test[numbers])

print(confusion_matrix(y_test, predicted))
print(round(precision_score(y_test, predicted), 4))
print(round(recall_score(y_test, predicted), 4))
print(round(f1_score(y_test, predicted), 4))
print(round(roc_auc_score(y_test, gauss.predict_proba(X_test[numbers])[:, 1]), 4))

Output

[[51 22]
 [35 76]]
0.7755
0.6847
0.7273
0.7663

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.

7.8Scaling changes nothing

Python, continues from the cells above
from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
scaled_train = scaler.fit_transform(X_train[numbers])
scaled_test = scaler.transform(X_test[numbers])

gauss_scaled = GaussianNB()
gauss_scaled.fit(scaled_train, y_train)

print((gauss_scaled.predict(scaled_test) == predicted).mean())

Output

1.0

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.

Try it yourself

This task continues from the cells of Part 6. Train a GaussianNB on the maximum heart rate alone and print its test accuracy, rounded to 4 decimals. Is one number enough?
Show a hint
Double brackets keep a table with one column: X_train[["max_heart_rate"]]; the same for X_test.
Show the solution
Python, continues from the cells above
from sklearn.naive_bayes import GaussianNB

model = GaussianNB()
model.fit(X_train[["max_heart_rate"]], y_train)

print(round(model.score(X_test[["max_heart_rate"]], y_test), 4))

Output

0.6848

Try it yourself

This task continues from the cells of Parts 6 and 7. Take the test patient at position 5. Print the probabilities of gauss for this patient, rounded to 3 decimals, then the true class.
Show a hint
patient = X_test[numbers].iloc[[5]], then gauss.predict_proba(patient).round(3) and y_test.iloc[5].
Show the solution
Python, continues from the cells above
patient = X_test[numbers].iloc[[5]]

print(gauss.predict_proba(patient).round(3))
print(y_test.iloc[5])

Output

[[0.117 0.883]]
1

8Categorical Naive Bayes on the categories

8.1Encoding as codes

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:

Python, continues from the cells above
from sklearn.preprocessing import OrdinalEncoder

encoder = OrdinalEncoder()
codes_train = encoder.fit_transform(X_train[categories].astype(str))
codes_test = encoder.transform(X_test[categories].astype(str))

print(encoder.categories_[1])
print(codes_train[:3])

Output

['asymptomatic' 'atypical angina' 'non-anginal pain' 'typical angina']
[[1. 3. 0. 1. 0. 1.]
 [0. 2. 0. 2. 0. 1.]
 [1. 1. 0. 2. 0. 3.]]

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.

8.2Train and judge

Python, continues from the cells above
from sklearn.naive_bayes import CategoricalNB

cat_nb = CategoricalNB()
cat_nb.fit(codes_train, y_train)

predicted_cat = cat_nb.predict(codes_test)

print(round(cat_nb.score(codes_test, y_test), 4))
print(round(recall_score(y_test, predicted_cat), 4))
print(round(roc_auc_score(y_test, cat_nb.predict_proba(codes_test)[:, 1]), 4))

Output

0.7663
0.7658
0.8692

The six categories alone are better than the five numbers: an accuracy of about 0.77 and an AUC of about 0.87.

8.3Inside the model: the likelihoods of the chest pain

Python, continues from the cells above
chest = np.exp(cat_nb.feature_log_prob_[1]).round(3)

print(pd.DataFrame(chest, index=["healthy", "disease"], columns=encoder.categories_[1]))

Output

         asymptomatic  atypical angina  non-anginal pain  typical angina
healthy         0.261            0.349             0.317           0.073
disease         0.771            0.055             0.137           0.037

Change it and run: change both [1] to [5] and run: the likelihoods of the ST slope.

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.)

8.4Is the naive assumption true here?

The model treats the chest pain and the angina during exercise as independent inside each class. Among the ill training patients:

Python, continues from the cells above
ill = X_train[y_train == 1]

print(pd.crosstab(ill["chest_pain"], ill["exercise_angina"]))

Output

exercise_angina    no  unknown  yes
chest_pain                         
asymptomatic      104       14  190
atypical angina    12        1    8
non-anginal pain   25        9   20
typical angina     13        1    0

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.

8.5Both models together

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:

Python, continues from the cells above
joint = gauss.predict_joint_log_proba(X_test[numbers]) + cat_nb.predict_joint_log_proba(codes_test) - np.log(gauss.class_prior_)

predicted_both = joint.argmax(axis=1)

print(round((predicted_both == y_test).mean(), 4))
print(round(recall_score(y_test, predicted_both), 4))

Output

0.7826
0.8018

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.

8.6Gaussian Naive Bayes on everything, with one-hot columns

A simpler way to use all features is to one-hot encode the categories (Topic 25) and give everything to GaussianNB:

Python, continues from the cells above
train_all = pd.get_dummies(X_train.astype({"fasting_sugar_high": str}), drop_first=True, dtype=int)
test_all = pd.get_dummies(X_test.astype({"fasting_sugar_high": str}), drop_first=True, dtype=int)
test_all = test_all.reindex(columns=train_all.columns, fill_value=0)

gauss_all = GaussianNB()
gauss_all.fit(train_all, y_train)

print(train_all.shape)
print(round(gauss_all.score(test_all, y_test), 4))
print(round(roc_auc_score(y_test, gauss_all.predict_proba(test_all)[:, 1]), 4))

Output

(734, 19)
0.7065
0.8556

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.

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.

8.7Bernoulli Naive Bayes on the yes/no columns

Python, continues from the cells above
from sklearn.naive_bayes import BernoulliNB

yes_no_train = pd.get_dummies(X_train[categories].astype(str), drop_first=True, dtype=int)
yes_no_test = pd.get_dummies(X_test[categories].astype(str), drop_first=True, dtype=int)
yes_no_test = yes_no_test.reindex(columns=yes_no_train.columns, fill_value=0)

bernoulli = BernoulliNB()
bernoulli.fit(yes_no_train, y_train)

print(yes_no_train.shape)
print(round(bernoulli.score(yes_no_test, y_test), 4))
print(round(roc_auc_score(y_test, bernoulli.predict_proba(yes_no_test)[:, 1]), 4))

Output

(734, 14)
0.7772
0.8646

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.

Try it yourself

This task continues from the cells of Parts 6 to 8. Print the likelihoods of exercise_angina (the fifth category column, position 4) for both classes, rounded to 3 decimals, as a table like the one of the chest pain.
Show a hint
np.exp(cat_nb.feature_log_prob_[4]).round(3) in a pd.DataFrame with index=["healthy", "disease"] and columns=encoder.categories_[4].
Show the solution
Python, continues from the cells above
angina = np.exp(cat_nb.feature_log_prob_[4]).round(3)

print(pd.DataFrame(angina, index=["healthy", "disease"], columns=encoder.categories_[4]))

Output

            no  unknown    yes
healthy  0.806    0.062  0.132
disease  0.388    0.065  0.548

9Tuning, the threshold, and the other models

9.1alpha with cross-validation

Python, continues from the cells above
from sklearn.model_selection import cross_val_score

sizes = [len(values) for values in encoder.categories_]
print(sizes)

for alpha in [0.1, 1, 10, 100]:
    scores = cross_val_score(CategoricalNB(alpha=alpha, min_categories=sizes), codes_train, y_train, cv=5)
    print(alpha, round(scores.mean(), 4))

Output

[2, 4, 3, 4, 3, 4]
0.1 0.7916
1 0.7902
10 0.7916
100 0.7902

Change it and run: add 0 to the list of alpha values and run: scikit-learn warns and uses a tiny alpha instead.

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.

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.

9.2var_smoothing

Python, continues from the cells above
for smoothing in [1e-9, 1e-3, 1e-1]:
    scores = cross_val_score(GaussianNB(var_smoothing=smoothing), X_train[numbers], y_train, cv=5)
    print(smoothing, round(scores.mean(), 4))

Output

1e-09 0.7235
0.001 0.6975
0.1 0.6949

The default 1e-9 is best here; a large var_smoothing flattens all the normal curves and hides the differences between the classes.

9.3More recall: a lower threshold

For a doctor a missed disease is worse than a false alarm. Naive Bayes gives probabilities, so the threshold can be lowered (Topic 28):

Python, continues from the cells above
disease_prob = cat_nb.predict_proba(codes_test)[:, 1]
predicted_03 = (disease_prob >= 0.3).astype(int)

print(round(recall_score(y_test, predicted_cat), 4), round(precision_score(y_test, predicted_cat), 4))
print(round(recall_score(y_test, predicted_03), 4), round(precision_score(y_test, predicted_03), 4))

Output

0.7658 0.8333
0.9189 0.8293

Change it and run: change 0.3 to 0.4 and run.

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.

9.4Other priors do the same

The prior is a factor in every product, so changing it moves every decision, like a threshold. class_prior sets it by hand:

Python, continues from the cells above
cat_prior = CategoricalNB(class_prior=[0.3, 0.7])
cat_prior.fit(codes_train, y_train)

predicted_prior = cat_prior.predict(codes_test)

print(round(recall_score(y_test, predicted_prior), 4), round(precision_score(y_test, predicted_prior), 4))

Output

0.9099 0.8279

Change it and run: change the priors to [0.5, 0.5] and run.

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".

Move the threshold of the Categorical model of the project. The 184 test patients and the model stay the same.

With the threshold 0.5 the model finds 85 of the 111 ill patients and misses 26; it gives 17 false alarms.

From 0.5 down to 0.3 the recall jumps from 0.77 to 0.92 while the precision stays near 0.83: many ill patients have probabilities just below 0.5.

9.5How sure is the model?

Part 1 said that the probabilities of Naive Bayes are often too extreme. Look at the patients for whom it is very sure:

Python, continues from the cells above
sure = disease_prob > 0.9

print(sure.sum())
print(round(disease_prob[sure].mean(), 3))
print(round(y_test[sure].mean(), 3))

Output

61
0.967
0.885

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.

9.6Naive Bayes against the models of earlier topics

The same one-hot data, now scaled, for logistic regression (Topic 27) and k-nearest neighbours (Topic 32), which need scaling:

Python, continues from the cells above
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier

scaler_all = StandardScaler()
train_scaled = scaler_all.fit_transform(train_all)
test_scaled = scaler_all.transform(test_all)

logistic = LogisticRegression()
logistic.fit(train_scaled, y_train)

knn = KNeighborsClassifier(n_neighbors=15)
knn.fit(train_scaled, y_train)

print(round(roc_auc_score(y_test, logistic.predict_proba(test_scaled)[:, 1]), 4))
print(round(roc_auc_score(y_test, knn.predict_proba(test_scaled)[:, 1]), 4))

Output

0.8672
0.8673

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.

9.7The scores of every model

Python, continues from the cells above
models = [
    ("Gaussian, five numbers", gauss.predict(X_test[numbers])),
    ("Categorical, six categories", predicted_cat),
    ("both combined", predicted_both),
    ("Gaussian, one-hot, all", gauss_all.predict(test_all)),
    ("Bernoulli, yes/no columns", bernoulli.predict(yes_no_test)),
    ("logistic regression", logistic.predict(test_scaled)),
    ("k-nearest neighbours", knn.predict(test_scaled)),
]

for name, model_predicted in models:
    print(name, round((model_predicted == y_test).mean(), 4), round(recall_score(y_test, model_predicted), 4))

Output

Gaussian, five numbers 0.6902 0.6847
Categorical, six categories 0.7663 0.7658
both combined 0.7826 0.8018
Gaussian, one-hot, all 0.7065 0.6216
Bernoulli, yes/no columns 0.7772 0.7748
logistic regression 0.8315 0.8739
k-nearest neighbours 0.8207 0.8468

Every line shows a model, its test accuracy and its recall on the same 184 patients.

Python, continues from the cells above
import matplotlib.pyplot as plt

names = [name for name, model_predicted in models]
recalls = [recall_score(y_test, model_predicted) for name, model_predicted in models]

plt.barh(names, recalls)
plt.xlim(0.5, 0.9)
plt.xlabel("test recall")
plt.title("Naive Bayes and the models of earlier topics")
plt.show()
Chart: Naive Bayes and the models of earlier topics

What the comparison shows:

  • The numbers alone are the weakest; the categories carry more information about this disease.
  • 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.
  • 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.
  • 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.

Try it yourself

This task continues from the cells of Parts 6 to 9. Predict "disease" when disease_prob is at least 0.2. Print the recall, then the precision, each rounded to 4 decimals.
Show a hint
(disease_prob >= 0.2).astype(int), then recall_score and precision_score with y_test.
Show the solution
Python, continues from the cells above
predicted_02 = (disease_prob >= 0.2).astype(int)

print(round(recall_score(y_test, predicted_02), 4))
print(round(precision_score(y_test, predicted_02), 4))

Output

0.9459
0.8268

Try it yourself

This task continues from the cells of Parts 6 to 8. Train a CategoricalNB with fit_prior=False (equal priors) on codes_train and print its test recall, rounded to 4 decimals. Why does it hardly change?
Show a hint
CategoricalNB(fit_prior=False), fit(codes_train, y_train), then recall_score(y_test, ....predict(codes_test)).
Show the solution
Python, continues from the cells above
equal = CategoricalNB(fit_prior=False)
equal.fit(codes_train, y_train)

print(round(recall_score(y_test, equal.predict(codes_test)), 4))

Output

0.7568

10The workflow, step by step

The workflow, step by step
StepWhat is doneIn this project
1. Lookshape, first rows, the meaning of the columns920 patients, 15 columns
2. Checkmissing values, repeated rowsmany gaps, 2 copies
3. Repeated rowsdrop them before the split918 patients left
4. Impossible valueszeros that are really gapscholesterol and blood pressure of 0 become NaN
5. Useless columnsmostly missing, or not about the patientmajor_vessels, thal, hospital
6. Targetthe share of each class55 percent ill: almost balanced; recall matters
7. Splittraining and test data734 and 184
8. Filltraining medians; "unknown" for categoriesafter the split
9. Scalenot needed for Naive Bayeschecked: the same predictions
10. ModelGaussianNB on the numbersaccuracy about 0.69
11. Encode and modelOrdinalEncoder, CategoricalNB; BernoulliNB on yes/no columnsaccuracy about 0.77, AUC about 0.87
12. Combineadd the joint logarithmsaccuracy 0.78, recall 0.80
13. Tunealpha (with min_categories), var_smoothing with cross-validation; thresholdsmall differences; recall 0.77 to 0.92 with 0.3
14. Comparethe same test data, the same measuresthe same AUC as logistic regression and k-nearest neighbours, a lower accuracy

Try it yourself

(a) Which step comes before the split: dropping the repeated rows or filling the gaps? (b) Which step of other models is left out for Naive Bayes? (c) Which model ranked the patients as well as logistic regression? (d) Which change raised the recall most?

Show a hint
Look at Steps 3, 8, 9, 13 and 14 of the table.
Show the solution

Answer: (a) dropping the repeated rows; (b) scaling; (c) Categorical Naive Bayes; (d) a lower threshold.

Copies go before the split; the scaling is checked and left out; the Categorical model has the AUC of logistic regression; the threshold 0.3 lifted the recall from 0.77 to 0.92.

11Common mistakes

Common mistakes
MistakeWhy it is wrongRight
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.
Setting alpha=0.One unseen value makes a whole class impossible.Keep a small alpha, 1 by default.
Scaling the features "to be safe".It changes nothing for Naive Bayes.Save the step; scale for the models that need it.
Leaving impossible zeros in.They pull the means and widen the normal curves.Turn them into gaps and fill them.
Giving text columns to GaussianNB or CategoricalNB.scikit-learn needs numbers.One-hot for Gaussian, codes for Categorical.
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.
Using GaussianNB on strongly skewed numbers without a look.A normal curve fits them badly.Look at the histogram; a logarithm can help.
Keeping two copies of the same information.The naive assumption counts the evidence twice.Drop near-copies.
Using MultinomialNB for measurements.It is made for counts, such as words.Gaussian for measurements, Categorical for categories.
Judging a medical model by its accuracy only.Missed diseases are the costly mistakes.Look at the recall; lower the threshold if needed.

12Solved problems

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.

Problem 1: Prior times likelihood

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?

Idea. Prior times likelihood for each class, then divide by the sum (Part 2).

complaint:0.3×0.6=0.18other:0.7×0.1=0.07P(complaint∣refund)=0.180.18+0.07=0.180.25=0.72\begin{aligned} \text{complaint:}\quad & 0.3 \times 0.6 = 0.18 \\[4pt] \text{other:}\quad & 0.7 \times 0.1 = 0.07 \\[8pt] & P(\text{complaint} \mid \text{refund}) \\[4pt] & = \frac{0.18}{0.18 + 0.07} = \frac{0.18}{0.25} = 0.72 \end{aligned}

Why: the word is six times more common in complaints, which turns a prior of 0.3 into 0.72.

Problem 2: Two features

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.

Idea. Multiply the likelihoods of both features in each class (Part 2).

disease:0.5×0.7×0.4=0.14healthy:0.5×0.3×0.2=0.03P(disease∣both)=0.140.14+0.03=0.140.17=0.824\begin{aligned} \text{disease:}\quad & 0.5 \times 0.7 \times 0.4 = 0.14 \\[4pt] \text{healthy:}\quad & 0.5 \times 0.3 \times 0.2 = 0.03 \\[8pt] & P(\text{disease} \mid \text{both}) \\[4pt] & = \frac{0.14}{0.14 + 0.03} = \frac{0.14}{0.17} = 0.824 \end{aligned}

Why: both features point to disease, and the naive product strengthens them.

Problem 3: Laplace smoothing

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.

Idea. With smoothing: count+αclass size+α×categories\frac{\text{count} + \alpha}{\text{class size} + \alpha \times \text{categories}}, where α\alpha is alpha (Part 2).

without smoothing:08=0with alpha=1:0+18+4=112=0.083\begin{aligned} \text{without smoothing:}\quad & \tfrac{0}{8} = 0 \\[6pt] \text{with alpha} = 1\text{:}\quad & \frac{0 + 1}{8 + 4} = \frac{1}{12} = 0.083 \end{aligned}

Why: without smoothing one unseen value would make "healthy" impossible for every patient with typical angina; with smoothing it only makes it less likely.

Problem 4: The Gaussian likelihood

Healthy patients have a resting blood pressure with μ=130\mu = 130 and σ=15\sigma = 15. Compute the height of their normal curve at x=145x = 145.

Idea. The normal curve of Part 3.

z=145−13015=11152π=0.0266f(145)=0.0266×e−0.5=0.0266×0.607=0.0161\begin{aligned} z &= \frac{145 - 130}{15} = 1 \\[6pt] \frac{1}{15 \sqrt{2\pi}} &= 0.0266 \\[6pt] f(145) &= 0.0266 \times e^{-0.5} \\[2pt] &= 0.0266 \times 0.607 = 0.0161 \end{aligned}

Why: one standard deviation from the mean the curve has about 61 percent of its highest value.

Problem 5: Read and check

Read the file. Print its shape, the number of repeated rows and the number of patients with a cholesterol of 0.

Idea. The first look (Part 6).

Python
import pandas as pd

df = pd.read_csv("heart_disease.csv")

print(df.shape)
print(df.duplicated().sum())
print((df["cholesterol"] == 0).sum())

Output

(920, 15)
2
172

Why: copies to drop, and many impossible zeros to turn into gaps.

Problem 6: Clean

Drop the repeated rows, turn the zeros of cholesterol and resting_bp into NaN, and drop major_vessels, thal and hospital. Print the shape.

Idea. Impossible values are gaps in disguise; columns that are mostly missing or not about the patient go (Part 6).

Python, continues from the cells above
import numpy as np

df = df.drop_duplicates()
df.loc[df["cholesterol"] == 0, "cholesterol"] = np.nan
df.loc[df["resting_bp"] == 0, "resting_bp"] = np.nan
df = df.drop(columns=["major_vessels", "thal", "hospital"])

print(df.shape)

Output

(918, 12)

Why: 918 patients, eleven features and the target.

Problem 7: Split

Make X and y and split them with test_size=0.25 and random_state=7. Print the shapes.

Idea. The split comes before any value is learned from the data.

Python, continues from the cells above
from sklearn.model_selection import train_test_split

X = df.drop(columns=["disease"])
y = df["disease"]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=7)

print(X_train.shape, X_test.shape)

Output

(688, 11) (230, 11)

Why: 688 patients to learn from and 230 to judge with.

Problem 8: Fill

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.

Idea. Medians from the training data; missing categories as a category of their own (Part 6).

Python, continues from the cells above
numbers = ["age", "resting_bp", "cholesterol", "max_heart_rate", "st_depression"]
categories = ["sex", "chest_pain", "fasting_sugar_high", "rest_ecg", "exercise_angina", "st_slope"]

medians = X_train[numbers].median()
X_train[numbers] = X_train[numbers].fillna(medians)
X_test[numbers] = X_test[numbers].fillna(medians)

X_train[categories] = X_train[categories].fillna("unknown")
X_test[categories] = X_test[categories].fillna("unknown")

print(X_train.isna().sum().sum(), X_test.isna().sum().sum())

Output

0 0

Why: no gaps are left, and the test data did not help to compute the medians.

Problem 9: Gaussian Naive Bayes

Train a GaussianNB on the five numbers. Print its test accuracy and its recall, rounded to 4 decimals.

Idea. The Gaussian kind for numbers (Part 7).

Python, continues from the cells above
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import recall_score, roc_auc_score

gauss = GaussianNB()
gauss.fit(X_train[numbers], y_train)

print(round(gauss.score(X_test[numbers], y_test), 4))
print(round(recall_score(y_test, gauss.predict(X_test[numbers])), 4))

Output

0.7217
0.7165

Why: the numbers alone give a fair but modest model.

Problem 10: The means of the classes

Print theta_ of the model, rounded to 1 decimal.

Idea. The mean of every number in every class (Part 7).

Python, continues from the cells above
print(gauss.theta_.round(1))

Output

[[ 50.4 130.3 239.5 148.8   0.5]
 [ 56.5 134.9 251.2 129.4   1.3]]

Why: the second row (disease) has the higher age and ST depression and the lower maximum heart rate.

Problem 11: Codes

Encode the six category columns with an OrdinalEncoder fitted on the training data (with .astype(str)). Print the shape of the coded training data.

Idea. Categorical Naive Bayes needs codes (Part 8).

Python, continues from the cells above
from sklearn.preprocessing import OrdinalEncoder

encoder = OrdinalEncoder()
codes_train = encoder.fit_transform(X_train[categories].astype(str))
codes_test = encoder.transform(X_test[categories].astype(str))

print(codes_train.shape)

Output

(688, 6)

Why: six coded columns, one per category feature.

Problem 12: Categorical Naive Bayes

Train a CategoricalNB on the codes. Print its test accuracy, recall and AUC, rounded to 4 decimals.

Idea. The Categorical kind for categories (Part 8).

Python, continues from the cells above
from sklearn.naive_bayes import CategoricalNB

cat_nb = CategoricalNB()
cat_nb.fit(codes_train, y_train)

print(round(cat_nb.score(codes_test, y_test), 4))
print(round(recall_score(y_test, cat_nb.predict(codes_test)), 4))
print(round(roc_auc_score(y_test, cat_nb.predict_proba(codes_test)[:, 1]), 4))

Output

0.8
0.7953
0.8802

Why: on this split too the categories beat the numbers.

Problem 13: Both together

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.

Idea. The naive product of all features, in logarithms (Part 8).

Python, continues from the cells above
joint = gauss.predict_joint_log_proba(X_test[numbers]) + cat_nb.predict_joint_log_proba(codes_test) - np.log(gauss.class_prior_)

predicted_both = joint.argmax(axis=1)

print(round((predicted_both == y_test).mean(), 4))

Output

0.813

Why: all eleven features together; on this split the combination is a little better than the categories alone (0.80).

Problem 14: alpha with cross-validation

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.

Idea. The smoothing count chosen without the test data (Part 9).

Python, continues from the cells above
from sklearn.model_selection import cross_val_score

sizes = [len(values) for values in encoder.categories_]

for alpha in [0.1, 1, 10]:
    scores = cross_val_score(CategoricalNB(alpha=alpha, min_categories=sizes), codes_train, y_train, cv=5)
    print(alpha, round(scores.mean(), 4))

Output

0.1 0.7806
1 0.7806
10 0.7805

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.

Problem 15: A lower threshold

Predict "disease" when the probability of cat_nb is at least 0.3. Print the recall and the precision, rounded to 4 decimals.

Idea. More recall for a medical model (Part 9).

Python, continues from the cells above
from sklearn.metrics import precision_score

disease_prob = cat_nb.predict_proba(codes_test)[:, 1]
predicted_03 = (disease_prob >= 0.3).astype(int)

print(round(recall_score(y_test, predicted_03), 4))
print(round(precision_score(y_test, predicted_03), 4))

Output

0.9213
0.7748

Why: fewer missed patients, more false alarms.

Problem 16: Scaling changes nothing

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.

Idea. The normal curves stretch together with their features (Part 7).

Python, continues from the cells above
from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
gauss_scaled = GaussianNB()
gauss_scaled.fit(scaler.fit_transform(X_train[numbers]), y_train)

same = gauss_scaled.predict(scaler.transform(X_test[numbers])) == gauss.predict(X_test[numbers])

print(same.mean())

Output

1.0

Why: 1.0: every prediction is the same.

13Practice

Sixteen problems. The first four are solved on paper. Problems 5 to 16 are one project in Python on heart_disease.csv, the file of the lesson (the whole table): its steps continue from one another, like the cells of a notebook, from reading the raw file to combined models. Under every problem there is a hint and a solution.

13.1Group A: by hand

  1. 1.40 percent of the customers of a bank are risky. 50 percent of the risky customers missed a payment last year, 10 percent of the others did. A customer missed a payment. What is the probability that the customer is risky? Give 3 decimals.

    Show a hint
    Prior times likelihood for each class, then divide by the sum.
    Show one possible solution

    Answer: 0.769.

    risky:0.4×0.5=0.2other:0.6×0.1=0.06P(risky∣missed)=0.20.2+0.06=0.20.26=0.769\begin{aligned} \text{risky:}\quad & 0.4 \times 0.5 = 0.2 \\[4pt] \text{other:}\quad & 0.6 \times 0.1 = 0.06 \\[8pt] & P(\text{risky} \mid \text{missed}) \\[4pt] & = \frac{0.2}{0.2 + 0.06} = \frac{0.2}{0.26} = 0.769 \end{aligned}
  2. 2.Among patients with the disease, 80 percent have chest pain and 30 percent have high sugar; among healthy patients 20 percent and 10 percent. The prior of the disease is 0.4. A patient has chest pain and high sugar. Find the probability of disease with the naive assumption. Give 3 decimals.

    Show a hint
    Multiply the prior by both likelihoods in each class.
    Show one possible solution

    Answer: 0.889.

    disease:0.4×0.8×0.3=0.096healthy:0.6×0.2×0.1=0.012P(disease∣both)=0.0960.096+0.012=0.0960.108=0.889\begin{aligned} \text{disease:}\quad & 0.4 \times 0.8 \times 0.3 = 0.096 \\[4pt] \text{healthy:}\quad & 0.6 \times 0.2 \times 0.1 = 0.012 \\[8pt] & P(\text{disease} \mid \text{both}) \\[4pt] & = \frac{0.096}{0.096 + 0.012} = \frac{0.096}{0.108} = 0.889 \end{aligned}
  3. 3.In 10 ill patients, the value "downsloping" of a feature with 3 categories appeared 0 times. Find its likelihood among the ill patients (a) without smoothing, (b) with α=1\alpha = 1. Give 3 decimals.

    Show a hint
    count+αclass size+α×categories\frac{\text{count} + \alpha}{\text{class size} + \alpha \times \text{categories}}.
    Show one possible solution

    Answer: (a) 0; (b) 0.077.

    without smoothing:010=0α=1:0+110+3=113=0.077\begin{aligned} \text{without smoothing:}\quad & \tfrac{0}{10} = 0 \\[6pt] \alpha = 1\text{:}\quad & \frac{0 + 1}{10 + 3} = \frac{1}{13} = 0.077 \end{aligned}
  4. 4.(a) Which kind of Naive Bayes fits word counts? (b) Which kind fits measurements such as the blood pressure? (c) Does Naive Bayes need scaled features? (d) What does alpha=0 risk?

    Show a hint
    Look at the table of the kinds and at Part 5.
    Show one possible solution

    Answer: (a) Multinomial; (b) Gaussian; (c) no; (d) the zero-frequency problem.

    MultinomialNB counts; GaussianNB fits a normal curve; the curves stretch with the features, so scaling changes nothing; without smoothing one unseen value makes a class impossible.

13.2Group B: one project in Python

The same workflow as in the lesson, on the same raw file, with another split: test_size=0.3 with random_state=1. The steps continue from one another, like the cells of a notebook: every step uses what the steps before it created.

Steps 5 to 8: from the raw file to the split

Read the file, drop the copies, make the impossible zeros gaps, drop three columns, split.

  1. 5.Read heart_disease.csv into df. Print the shape, then the number of patients with the disease.
    Show a hint
    df = pd.read_csv("heart_disease.csv"), then print(df.shape) and print(df["disease"].sum()).
    Show one possible solution
    Python
    import pandas as pd
    
    df = pd.read_csv("heart_disease.csv")
    
    print(df.shape)
    print(df["disease"].sum())

    Output

    (920, 15)
    509
  2. 6.Drop the repeated rows and turn the zeros of cholesterol and resting_bp into NaN. Print the number of gaps in cholesterol. This step continues from Step 5.
    Show a hint
    df = df.drop_duplicates(), then df.loc[df["cholesterol"] == 0, "cholesterol"] = np.nan, the same for resting_bp, then df["cholesterol"].isna().sum().
    Show one possible solution
    Python, continues from the cells above
    import numpy as np
    
    df = df.drop_duplicates()
    df.loc[df["cholesterol"] == 0, "cholesterol"] = np.nan
    df.loc[df["resting_bp"] == 0, "resting_bp"] = np.nan
    
    print(df["cholesterol"].isna().sum())

    Output

    201
  3. 7.Drop the columns major_vessels, thal and hospital. Print the number of columns.
    Show a hint
    df = df.drop(columns=["major_vessels", "thal", "hospital"]), then len(df.columns).
    Show one possible solution
    Python, continues from the cells above
    df = df.drop(columns=["major_vessels", "thal", "hospital"])
    
    print(len(df.columns))

    Output

    12
  4. 8.Make X (all columns without disease) and y. Split them with test_size=0.3 and random_state=1. Print the number of test patients, then how many of them have the disease.
    Show a hint
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1), then len(y_test) and y_test.sum().
    Show one possible solution
    Python, continues from the cells above
    from sklearn.model_selection import train_test_split
    
    X = df.drop(columns=["disease"])
    y = df["disease"]
    
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)
    
    print(len(y_test))
    print(y_test.sum())

    Output

    276
    151

Steps 9 to 12: the gaps and two models

The training medians and "unknown", a Gaussian model and its class means, the codes and a Categorical model.

  1. 9.Fill the columns of numbers with the training medians and the columns of categories with "unknown", in both parts. Print the median cholesterol of the training data.
    Show a hint
    medians = X_train[numbers].median(), fillna(medians) on both parts, fillna("unknown") for the categories, then medians["cholesterol"].
    Show one possible solution
    Python, continues from the cells above
    numbers = ["age", "resting_bp", "cholesterol", "max_heart_rate", "st_depression"]
    categories = ["sex", "chest_pain", "fasting_sugar_high", "rest_ecg", "exercise_angina", "st_slope"]
    
    medians = X_train[numbers].median()
    X_train[numbers] = X_train[numbers].fillna(medians)
    X_test[numbers] = X_test[numbers].fillna(medians)
    
    X_train[categories] = X_train[categories].fillna("unknown")
    X_test[categories] = X_test[categories].fillna("unknown")
    
    print(medians["cholesterol"])

    Output

    239.0
  2. 10.Train a GaussianNB called gauss on the five numbers. Print its test accuracy, rounded to 4 decimals.
    Show a hint
    gauss = GaussianNB(), gauss.fit(X_train[numbers], y_train), then gauss.score(X_test[numbers], y_test).
    Show one possible solution
    Python, continues from the cells above
    from sklearn.naive_bayes import GaussianNB
    
    gauss = GaussianNB()
    gauss.fit(X_train[numbers], y_train)
    
    print(round(gauss.score(X_test[numbers], y_test), 4))

    Output

    0.6884
  3. 11.Print the mean maximum heart rate of each class that gauss learned (the fourth column of theta_), rounded with .round(1).
    Show a hint
    gauss.theta_[:, 3] is the fourth column, one value per class.
    Show one possible solution
    Python, continues from the cells above
    print(gauss.theta_[:, 3].round(1))

    Output

    [149.  128.4]
  4. 12.Fit an OrdinalEncoder called encoder on the training categories (with .astype(str)) and code both parts into codes_train and codes_test. Train a CategoricalNB called cat_nb on them and print its test accuracy, rounded to 4 decimals.
    Show a hint
    codes_train = encoder.fit_transform(X_train[categories].astype(str)), codes_test = encoder.transform(X_test[categories].astype(str)), then fit and score.
    Show one possible solution
    Python, continues from the cells above
    from sklearn.preprocessing import OrdinalEncoder
    from sklearn.naive_bayes import CategoricalNB
    
    encoder = OrdinalEncoder()
    codes_train = encoder.fit_transform(X_train[categories].astype(str))
    codes_test = encoder.transform(X_test[categories].astype(str))
    
    cat_nb = CategoricalNB()
    cat_nb.fit(codes_train, y_train)
    
    print(round(cat_nb.score(codes_test, y_test), 4))

    Output

    0.7246

Steps 13 to 16: measures, both models together, alpha and the threshold

Recall and AUC, the added logarithms, alpha with cross-validation, a lower threshold and a chart.

  1. 13.Print the recall, then the AUC of cat_nb on the test data, each rounded to 4 decimals.
    Show a hint
    recall_score(y_test, cat_nb.predict(codes_test)) and roc_auc_score(y_test, cat_nb.predict_proba(codes_test)[:, 1]).
    Show one possible solution
    Python, continues from the cells above
    from sklearn.metrics import recall_score, roc_auc_score
    
    print(round(recall_score(y_test, cat_nb.predict(codes_test)), 4))
    print(round(roc_auc_score(y_test, cat_nb.predict_proba(codes_test)[:, 1]), 4))

    Output

    0.7086
    0.8331
  2. 14.Add the joint logarithms of gauss and cat_nb and subtract the logarithm of the prior once. Print the accuracy of the class with the larger sum, rounded to 4 decimals.
    Show a hint
    joint = gauss.predict_joint_log_proba(X_test[numbers]) + cat_nb.predict_joint_log_proba(codes_test) - np.log(gauss.class_prior_), then joint.argmax(axis=1) and its share equal to y_test.
    Show one possible solution
    Python, continues from the cells above
    joint = gauss.predict_joint_log_proba(X_test[numbers]) + cat_nb.predict_joint_log_proba(codes_test) - np.log(gauss.class_prior_)
    
    predicted_both = joint.argmax(axis=1)
    
    print(round((predicted_both == y_test).mean(), 4))

    Output

    0.7609
  3. 15.For alpha = 0.1, 1 and 10, print alpha and the mean accuracy of a 5-fold cross-validation of CategoricalNB on codes_train, rounded to 4 decimals. Give the model min_categories=sizes, the number of categories of each feature.
    Show a hint
    sizes = [len(values) for values in encoder.categories_]; a loop over [0.1, 1, 10] with cross_val_score(CategoricalNB(alpha=alpha, min_categories=sizes), codes_train, y_train, cv=5).mean().
    Show one possible solution
    Python, continues from the cells above
    from sklearn.model_selection import cross_val_score
    
    sizes = [len(values) for values in encoder.categories_]
    
    for alpha in [0.1, 1, 10]:
        scores = cross_val_score(CategoricalNB(alpha=alpha, min_categories=sizes), codes_train, y_train, cv=5)
        print(alpha, round(scores.mean(), 4))

    Output

    0.1 0.8194
    1 0.8194
    10 0.8131
  4. 16.Predict "disease" when the probability of cat_nb is at least 0.3, and print the recall rounded to 4 decimals. Then draw the probabilities of disease of the test patients as a histogram with 20 bins.
    Show a hint
    disease_prob = cat_nb.predict_proba(codes_test)[:, 1], (disease_prob >= 0.3).astype(int), then plt.hist(disease_prob, bins=20) and plt.show().
    Show one possible solution
    Python, continues from the cells above
    import matplotlib.pyplot as plt
    
    disease_prob = cat_nb.predict_proba(codes_test)[:, 1]
    predicted_03 = (disease_prob >= 0.3).astype(int)
    
    print(round(recall_score(y_test, predicted_03), 4))
    
    plt.hist(disease_prob, bins=20)
    plt.xlabel("probability of disease")
    plt.show()

    Output

    0.8874
    The chart this code draws

14Check yourself

Twelve questions. Every question has one right answer.

Question 1

1.What does "naive" mean in Naive Bayes?

Question 2

2.How does Naive Bayes choose a class?

Question 3

3.What is the zero-frequency problem?

Question 4

4.With alpha = 1, a value seen 0 times among 6 rows of a class has the likelihood... (the feature has 2 categories)

Question 5

5.Which kind of Naive Bayes fits numbers such as the blood pressure?

Question 6

6.Does Gaussian Naive Bayes need scaled features?

Question 7

7.What does CategoricalNB need as input?

Question 8

8.Why were the zeros of the cholesterol turned into NaN?

Question 9

9.Why are the probabilities of Naive Bayes often too extreme?

Question 10

10.Why does scikit-learn add logarithms instead of multiplying probabilities?

Question 11

11.What does var_smoothing of GaussianNB do?

Question 12

12.For a medical model, a missed disease is the costly mistake. What raises the recall of Naive Bayes?

0 of 12 answered.

15Summary

Summary
Formula or ruleMeaning
Bayes' ruleP(c∣x)=P(c) P(x∣c)P(x)P(c \mid x) = \frac{P(c)\,P(x \mid c)}{P(x)}the posterior from prior and likelihood
Naive assumptionP(x∣c)=P(x1∣c)×P(x2∣c)×…P(x \mid c) = P(x_1 \mid c) \times P(x_2 \mid c) \times \dotsthe features are independent inside each class
Decisionthe class with the largest prior times likelihoodsthe probabilities are the products divided by their sum
Laplace smoothingcount+αclass size+α×categories\frac{\text{count} + \alpha}{\text{class size} + \alpha \times \text{categories}}no likelihood is 0
Gaussian likelihood1σ2π e−(x−μ)22σ2\frac{1}{\sigma\sqrt{2\pi}}\, e^{-\frac{(x - \mu)^2}{2\sigma^2}}the height of the class's normal curve
Logarithmslog⁡(ab)=log⁡a+log⁡b\log(ab) = \log a + \log bsums instead of tiny products
Summary
CodeWhat it does
GaussianNB()Naive Bayes for numbers
CategoricalNB(alpha=1)Naive Bayes for coded categories
BernoulliNB(), MultinomialNB(), ComplementNB()for yes/no, for counts, for unbalanced counts
OrdinalEncoder()categories to codes 0, 1, 2, ...
gauss.theta_, gauss.var_, class_prior_the means, the variances, the priors
cat_nb.feature_log_prob_the logarithms of the likelihoods of the categories
predict_joint_log_proba(X)the logarithm of prior times likelihoods, per class

Rules to keep

  1. Naive Bayes multiplies the prior by the likelihood of every feature inside each class and takes the class with the larger product.
  2. Use Laplace smoothing (alpha) so that an unseen value cannot make a class impossible.
  3. Choose the kind for the features: Gaussian for numbers, Categorical for categories, Bernoulli for yes/no, Multinomial for counts.
  4. No scaling; fill the gaps; turn impossible values into gaps; codes for CategoricalNB.
  5. Trust its decisions more than its exact probabilities; lower the threshold when the recall matters.

What comes next

Topic 35 brings support vector machines, which draw the widest possible border between the classes, and voting, which lets several different models decide together.