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.
Lesson notebook
The lesson as a Jupyter notebook: the heart project cell by cell, from the raw file and every preprocessing step to the Gaussian, Categorical and Bernoulli models, the threshold and the comparison, and the sixteen solved problems.
topic-34-naive-bayes.ipynb, 81 KB
Practice notebook
The same project on the heart data in twelve steps, from reading the raw file to a Categorical model, both models together, alpha and a lower threshold, with a hint and a hidden solution for each step.
topic-34-practice.ipynb, 19 KB
Data file: the heart patients
920 patients of four hospitals with 15 columns, the UCI Heart Disease data set (Janosi, Steinbrunn, Pfisterer and Detrano; UCI Machine Learning Repository, licence CC BY 4.0) with its codes written as words. Not cleaned: missing values, impossible zeros and repeated rows are still in it.
heart_disease.csv, 79 KB
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.What Naive Bayes is, where it is used, and why it is called naive
- 2.How it decides: prior times likelihoods, for each class, then the class with the larger product
- 3.The zero-frequency problem and Laplace smoothing
- 4.The kinds of Naive Bayes: Gaussian, Categorical, Bernoulli, Multinomial and Complement, and which features each one takes
- 5.The Gaussian version: a normal curve per feature and class, worked by hand
- 6.The hyperparameters (
var_smoothing,alpha,priors,fit_prior,binarize) and their roles - 7.What scaling, encoding, missing values, outliers and correlated features mean for Naive Bayes, and for the models still to come
- 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
| Word | Meaning |
|---|---|
| Prior | the probability of a class before looking at the features: the share of the class in the training data |
| Likelihood | the probability of a feature value inside a class, for example |
| Posterior | the probability of a class after looking at the features: what the model predicts |
| Naive assumption | inside each class, the features are independent, so their likelihoods can be multiplied |
| Zero-frequency problem | a value never seen in a class gets the likelihood 0, and the whole product becomes 0 |
| Laplace smoothing | adding a small count (alpha) to every value, so that no likelihood is 0 |
| Gaussian Naive Bayes | for numbers: each feature follows a normal curve inside each class |
| Categorical Naive Bayes | for 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:
- Start with the prior: how common is each class? (In the training data, 54 percent of the patients have the disease.)
- 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?
- 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 | Weaknesses |
|---|---|
| Extremely fast to train and to predict | The independence assumption is almost never true |
| 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 |
| Handles many features easily, also thousands of words | A value never seen in a class makes trouble (the zero-frequency problem), unless smoothed |
| No scaling needed | The Gaussian version assumes bell-shaped numbers; skewed numbers fit badly |
| Few hyperparameters, little to tune | Usually 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
Show a hint
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):
The denominator is the same for both classes, so to compare the classes it can be left out: the class with the larger wins. The naive assumption then splits into a product, one factor per feature:
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).
| Patient | Angina | Asymptomatic | Disease |
|---|---|---|---|
| 1 | yes | yes | yes |
| 2 | yes | yes | yes |
| 3 | yes | no | yes |
| 4 | no | yes | yes |
| 5 | yes | yes | yes |
| 6 | no | yes | yes |
| 7 | no | no | no |
| 8 | no | no | no |
| 9 | yes | no | no |
| 10 | no | no | no |
2.3Step 1: the priors
Six of the ten patients have the disease:
2.4Step 2: the likelihoods
Count inside each class:
| Disease (6 patients) | Healthy (4 patients) | |
|---|---|---|
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": for disease and for healthy.
The healthy product is larger: the model predicts "healthy". Dividing each product by their sum gives the probabilities:
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:
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:
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):
| Disease (6 patients) | Healthy (4 patients) | |
|---|---|---|
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.
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
Try it yourself
Show a hint
Show the solution
Answer: (a) 0.167; (b) 1; (c) 0.792.
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:
| Kind | In scikit-learn | Features | The likelihood of a value | Typical use |
|---|---|---|---|---|
| Gaussian | GaussianNB | numbers | a normal curve per feature and class, with the class's mean and variance | measurements: blood pressure, temperature, sensor readings |
| Categorical | CategoricalNB | categories, coded 0, 1, 2, ... | the share of the value inside the class, smoothed with alpha | symptoms, types, colours, yes/no |
| 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 |
| Multinomial | MultinomialNB | counts | the share of each count in the class's total | word counts in texts (the NLP topics) |
| Complement | ComplementNB | counts | like Multinomial, computed from all the other classes | texts 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 and standard deviation , and uses the height of the curve as the likelihood:
Take the maximum heart rate during an exercise test. Suppose that in the training data the patients with the disease reached on average beats per minute, the healthy ones , both with , and that 55 percent have the disease. A new patient reached .
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.
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.
- disease: μ = 130
- healthy: μ = 150
3.2Working with logarithms
A product of many small probabilities quickly becomes too small for a computer (30 factors of 0.01 give ). So scikit-learn adds the logarithms instead of multiplying: . 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:
The disease sum is larger (less negative), as the disease product was. Going back: and , the two products of Part 2.
Try it yourself
Show a hint
Show the solution
Answer: (a) 0.00648; (b) 0.01761; (c) 0.31; (d) healthy.
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.
| Hyperparameter | Default | Kind | Role |
|---|---|---|---|
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. |
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. |
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. |
fit_prior | True | Categorical, Bernoulli, Multinomial | True: learn the priors from the data; False: equal priors for all classes. |
class_prior | None | Categorical, Bernoulli, Multinomial | set the priors by hand |
binarize | 0.0 | Bernoulli | the threshold that turns numbers into 0 and 1; None if the features are already 0 and 1 |
min_categories | None | Categorical | the 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
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
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.
CategoricalNBwants 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.GaussianNBcan 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.
| Model (topic) | Scaling | Encoding of text | Outliers in the features | Missing values |
|---|---|---|---|---|
| Linear regression (22) | not needed for the predictions | needed | sensitive | fill |
| Ridge, Lasso, logistic regression (26, 27) | needed | needed | sensitive | fill |
| Decision tree, random forest, bagged trees (29, 30, 31) | not needed | needed | robust | fill (recent scikit-learn can handle them) |
| k-nearest neighbours (32, 33) | essential: distances | needed; few, useful columns | sensitive | fill |
| Naive Bayes (34) | not needed | codes for Categorical, one-hot for Gaussian | sensitive (Gaussian), robust (counting kinds) | fill |
| Support vector machines, voting (35, 36) | needed for the support vector machine; voting as the models inside | needed | sensitive | fill |
| 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 |
| k-means, DBSCAN, PCA (43, 44) | essential: distances and variances | needed | sensitive | fill |
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
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
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.
Loading the table ...
6.1Step 1: read and look
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:
| Column | Meaning |
|---|---|
age, sex | age in years, male or female |
chest_pain | the type of chest pain: typical angina, atypical angina, non-anginal pain, asymptomatic |
resting_bp | blood pressure at rest (mm Hg) |
cholesterol | cholesterol in the blood (mg/dl) |
fasting_sugar_high | 1 when the fasting blood sugar is above 120 mg/dl |
rest_ecg | the result of the ECG at rest |
max_heart_rate | the highest heart rate reached in an exercise test |
exercise_angina | chest pain during the exercise test: yes or no |
st_depression, st_slope | two measurements of the ECG during exercise |
major_vessels, thal | the number of major vessels coloured in an X-ray, and the result of a thallium test |
hospital | where the patient was examined |
disease | the target: 1 for heart disease, 0 for none |
6.2Step 2: check
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
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
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:
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.
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
df = df.drop(columns=["major_vessels", "thal", "hospital"])
print(df.shape)Output
(918, 12)
major_vesselsandthalare missing for most patients: filling two thirds of a column with one value would invent most of it.hospitalis 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
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
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
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.
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
Show a hint
df[df["sex"] == "female"] keeps the women; the mean of the column disease is the share of 1s.Show the solution
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
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
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 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
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):
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:
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 ), 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:
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.
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 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.
- disease
- healthy
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
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
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
GaussianNB on the maximum heart rate alone and print its test accuracy, rounded to 4 decimals. Is one number enough?Show a hint
X_train[["max_heart_rate"]]; the same for X_test.Show the solution
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
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
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:
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
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
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:
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:
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:
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
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
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
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
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
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):
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:
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:
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:
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
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.
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()
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
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
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
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
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
| Step | What is done | In this project |
|---|---|---|
| 1. Look | shape, first rows, the meaning of the columns | 920 patients, 15 columns |
| 2. Check | missing values, repeated rows | many gaps, 2 copies |
| 3. Repeated rows | drop them before the split | 918 patients left |
| 4. Impossible values | zeros that are really gaps | cholesterol and blood pressure of 0 become NaN |
| 5. Useless columns | mostly missing, or not about the patient | major_vessels, thal, hospital |
| 6. Target | the share of each class | 55 percent ill: almost balanced; recall matters |
| 7. Split | training and test data | 734 and 184 |
| 8. Fill | training medians; "unknown" for categories | after the split |
| 9. Scale | not needed for Naive Bayes | checked: the same predictions |
| 10. Model | GaussianNB on the numbers | accuracy about 0.69 |
| 11. Encode and model | OrdinalEncoder, CategoricalNB; BernoulliNB on yes/no columns | accuracy about 0.77, AUC about 0.87 |
| 12. Combine | add the joint logarithms | accuracy 0.78, recall 0.80 |
| 13. Tune | alpha (with min_categories), var_smoothing with cross-validation; threshold | small differences; recall 0.77 to 0.92 with 0.3 |
| 14. Compare | the same test data, the same measures | the same AUC as logistic regression and k-nearest neighbours, a lower accuracy |
Try it yourself
Show a hint
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
| Mistake | Why it is wrong | Right |
|---|---|---|
| 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).
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).
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: , where is alpha (Part 2).
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 and . Compute the height of their normal curve at .
Idea. The normal curve of Part 3.
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).
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).
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.
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).
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).
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).
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).
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).
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).
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).
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).
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).
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.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.
- 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.
- 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 . Give 3 decimals.
Show a hint
.Show one possible solution
Answer: (a) 0; (b) 0.077.
- 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=0risk?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.
MultinomialNBcounts;GaussianNBfits 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.
- 5.Read
heart_disease.csvintodf. Print the shape, then the number of patients with the disease.Show a hint
df = pd.read_csv("heart_disease.csv"), thenprint(df.shape)andprint(df["disease"].sum()).Show one possible solution
Pythonimport pandas as pd df = pd.read_csv("heart_disease.csv") print(df.shape) print(df["disease"].sum())Output
(920, 15) 509
- 6.Drop the repeated rows and turn the zeros of
cholesterolandresting_bpintoNaN. Print the number of gaps incholesterol. This step continues from Step 5.Show a hint
df = df.drop_duplicates(), thendf.loc[df["cholesterol"] == 0, "cholesterol"] = np.nan, the same forresting_bp, thendf["cholesterol"].isna().sum().Show one possible solution
Python, continues from the cells aboveimport 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
- 7.Drop the columns
major_vessels,thalandhospital. Print the number of columns.Show a hint
df = df.drop(columns=["major_vessels", "thal", "hospital"]), thenlen(df.columns).Show one possible solution
Python, continues from the cells abovedf = df.drop(columns=["major_vessels", "thal", "hospital"]) print(len(df.columns))Output
12
- 8.Make
X(all columns withoutdisease) andy. Split them withtest_size=0.3andrandom_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), thenlen(y_test)andy_test.sum().Show one possible solution
Python, continues from the cells abovefrom 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.
- 9.Fill the columns of
numberswith the training medians and the columns ofcategorieswith"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, thenmedians["cholesterol"].Show one possible solution
Python, continues from the cells abovenumbers = ["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
- 10.Train a
GaussianNBcalledgausson the five numbers. Print its test accuracy, rounded to 4 decimals.Show a hint
gauss = GaussianNB(),gauss.fit(X_train[numbers], y_train), thengauss.score(X_test[numbers], y_test).Show one possible solution
Python, continues from the cells abovefrom 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
- 11.Print the mean maximum heart rate of each class that
gausslearned (the fourth column oftheta_), 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 aboveprint(gauss.theta_[:, 3].round(1))Output
[149. 128.4]
- 12.Fit an
OrdinalEncodercalledencoderon the training categories (with.astype(str)) and code both parts intocodes_trainandcodes_test. Train aCategoricalNBcalledcat_nbon 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)), thenfitandscore.Show one possible solution
Python, continues from the cells abovefrom 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.
- 13.Print the recall, then the AUC of
cat_nbon the test data, each rounded to 4 decimals.Show a hint
recall_score(y_test, cat_nb.predict(codes_test))androc_auc_score(y_test, cat_nb.predict_proba(codes_test)[:, 1]).Show one possible solution
Python, continues from the cells abovefrom 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
- 14.Add the joint logarithms of
gaussandcat_nband 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_), thenjoint.argmax(axis=1)and its share equal toy_test.Show one possible solution
Python, continues from the cells abovejoint = 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
- 15.For
alpha= 0.1, 1 and 10, printalphaand the mean accuracy of a 5-fold cross-validation ofCategoricalNBoncodes_train, rounded to 4 decimals. Give the modelmin_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]withcross_val_score(CategoricalNB(alpha=alpha, min_categories=sizes), codes_train, y_train, cv=5).mean().Show one possible solution
Python, continues from the cells abovefrom 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
- 16.Predict "disease" when the probability of
cat_nbis 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), thenplt.hist(disease_prob, bins=20)andplt.show().Show one possible solution
Python, continues from the cells aboveimport 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

14Check yourself
Twelve questions. Every question has one right answer.
0 of 12 answered.
15Summary
| Formula or rule | Meaning | |
|---|---|---|
| Bayes' rule | the posterior from prior and likelihood | |
| Naive assumption | the features are independent inside each class | |
| Decision | the class with the largest prior times likelihoods | the probabilities are the products divided by their sum |
| Laplace smoothing | no likelihood is 0 | |
| Gaussian likelihood | the height of the class's normal curve | |
| Logarithms | sums instead of tiny products |
| Code | What 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
- Naive Bayes multiplies the prior by the likelihood of every feature inside each class and takes the class with the larger product.
- Use Laplace smoothing (
alpha) so that an unseen value cannot make a class impossible. - Choose the kind for the features: Gaussian for numbers, Categorical for categories, Bernoulli for yes/no, Multinomial for counts.
- No scaling; fill the gaps; turn impossible values into gaps; codes for
CategoricalNB. - 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.