Module 3, topic 28, week 14, Thursday
Classification metrics: accuracy, precision, recall, F1-score, ROC-AUC
What the accuracy hides: the confusion matrix and the two types of error, precision, recall, the F1-score and the balanced accuracy, which measure fits which task, and the ROC curve with its AUC and the Gini coefficient, on the bank data of Topic 27.
Lesson notebook
The lesson as a Jupyter notebook: the measures on paper, the project on the bank data cell by cell with its charts, and the sixteen solved problems.
topic-28-classification-metrics.ipynb, 78 KB
Practice notebook
The same project on the bank data in twelve steps, from reading the file to the AUC and the ROC curve, with a hint and a hidden solution for each step.
topic-28-practice.ipynb, 19 KB
Data file: the bank customers
10,000 customers of a bank with 12 columns, the file of Topic 27: the data of the lesson, the solved problems and the practice. A public data set (Bank Customer Churn Dataset, Kaggle).
Bank Customer Churn Prediction.csv, 548 KB
Introduction: what the accuracy hides
The eighth lesson of Module 3. Topic 27 built a classifier and judged it with one number, the accuracy. Twice that number was not enough: a model was barely above "always answer stays", and a model with a lower accuracy looked more useful to the bank. This lesson gives the other measures of classification, and the rule for choosing among them.
The lesson has two halves. The first is done on paper: the four outcomes of a prediction, the confusion matrix, the two types of error, the measures that are calculated from them, and which measure fits which task. The second half is a project on the data file of Topic 27, Bank Customer Churn Prediction.csv: every step from reading the file to the trained model once more, as a revision, and then every measure in code. The ROC curve, its area (AUC) and the Gini coefficient come at the end.
You need: logistic regression, predict and predict_proba (Topic 27), the train/test split (Topic 23), scaling (Topic 24), encoding (Topic 25), and fractions.
What you will learn
- 1.Why a classifier needs more than one measure
- 2.The four outcomes: true positive, true negative, false positive, false negative
- 3.The confusion matrix: how to draw it, read it, and remember what stands where
- 4.The two types of error, and what each one costs
- 5.Accuracy, precision, recall, specificity, the F1-score and the balanced accuracy
- 6.Which measure fits which task: banking, healthcare, spam, unbalanced data
- 7.All of them in scikit-learn, on a real data file
- 8.The ROC curve, the AUC and the Gini coefficient
| Word | Meaning |
|---|---|
| Positive class | the class the model is looking for, coded 1 (the customer leaves, the patient is sick) |
| Negative class | the other class, coded 0 |
| True positive (TP) | the model said positive, and it is positive |
| True negative (TN) | the model said negative, and it is negative |
| False positive (FP) | the model said positive, but it is negative: a false alarm |
| False negative (FN) | the model said negative, but it is positive: a miss |
| Confusion matrix | the table of these four counts |
| Accuracy | the share of all predictions that are right |
| Precision | of the rows the model called positive, the share that are positive |
| Recall | of the rows that are positive, the share the model found |
| F1-score | one number made of precision and recall |
| ROC curve | recall against the rate of false alarms, for every threshold |
| AUC | the area under the ROC curve |
1Why one measure is not enough
1.1What the accuracy hides
The accuracy counts right answers and nothing else. It does not say which answers were wrong, and in real tasks the two kinds of mistake are rarely equally bad.
Two results of Topic 27 showed it:
- The first model had an accuracy of 0.811. Always answering "stays" gave 0.8035. Almost the same number, for a model and for no model at all.
- The model with
class_weight="balanced"had a lower accuracy and found many more of the customers who leave. For a bank that wants to keep its customers, it was the more useful model.
A regression model has its error in one direction of meaning: the prediction is too high or too low by some amount. A classifier is right or wrong, and it can be wrong in two different ways. Telling a healthy person "you are sick" and telling a sick person "you are healthy" are both one mistake for the accuracy. For the person they are not the same at all.
1.2Many measures, one table
There are many measures for classification: accuracy, precision, recall, specificity, F1-score, balanced accuracy, ROC-AUC, and more. They look like a long list, but all of them come from one small table with four numbers. Learn the table, and every measure is a fraction of its cells.
Try it yourself
Show a hint
Show the solution
Answer: (a) 0.99; (b) 0; (c) two.
An accuracy of 0.99, and not one positive row found. A classifier can say "positive" where the truth is negative, or "negative" where the truth is positive: two different mistakes, and the accuracy cannot tell them apart.
2The four outcomes
2.1Positive and negative
First decide which class is the positive one. It is the class the model is looking for, and it is coded 1. "Positive" does not mean "good": in medicine a positive test means the disease was found. Usually the positive class is the rare and important one: the customer who leaves, the payment that is a fraud, the patient who is sick.
2.2A class of 20 students
A class has 20 students. At the end of the year 12 passed and 8 failed. A model predicted the result of every student at the start of the year. Now the predictions are compared with the truth:
- of the 12 students who passed, the model predicted "passes" for 10, and "fails" for the other 2;
- of the 8 students who failed, the model predicted "fails" for 5, and "passes" for the other 3.
The positive class is "passes". Every student falls into exactly one of four groups:
| Group | The truth | The model said | Students |
|---|---|---|---|
| True positive (TP) | passed | passes | 10 |
| False negative (FN) | passed | fails | 2 |
| True negative (TN) | failed | fails | 5 |
| False positive (FP) | failed | passes | 3 |
All 20 students are in the table, each one once.
2.3How to read the names
Every name has two words, and each word answers one question:
- The second word is what the model said: positive or negative.
- The first word says whether the model was right: true or false.
So a false positive is: the model said positive, and that was false. The student really failed. A false negative: the model said negative, and that was false. The student really passed.
Read the name from the back: first what the model said, then whether it was right.
| Name | The model said | Was it right? | So the truth is |
|---|---|---|---|
| True positive | positive | yes | positive |
| True negative | negative | yes | negative |
| False positive | positive | no | negative |
| False negative | negative | no | positive |
Two sums are worth seeing at once:
| Sum | Who | |
|---|---|---|
| really positive | the students who passed | |
| really negative | the students who failed | |
| predicted positive | the model said "passes" | |
| predicted negative | the model said "fails" |
The model said "passes" 13 times, although only 12 students passed, and it was right in 10 of the 13.
Try it yourself
Show a hint
Show the solution
Answer: (a) FP; (b) FN; (c) TP; (d) TN.
(a) The test said positive and was wrong: a false positive, a false alarm. (b) The test said negative and was wrong: a false negative, a miss. (c) and (d) are the two right outcomes: a true positive and a true negative.
3The confusion matrix
3.1Drawing it
The four counts are written as a table with two rows and two columns, the confusion matrix. It shows where the model confuses the classes.
- The rows are the truth (the actual class).
- The columns are the prediction of the model.
- Class 0, the negative class, comes first, in the rows and in the columns.
This is the layout of scikit-learn, and this lesson uses it everywhere.
As a plain table:
| Predicted 0 (fails) | Predicted 1 (passes) | Sum | |
|---|---|---|---|
| Actual 0 (failed) | 8 | ||
| Actual 1 (passed) | 12 | ||
| Sum | 7 | 13 | 20 |
3.2Reading it
- The diagonal from the top left to the bottom right holds the right predictions: TN and TP. Here .
- The other two cells hold the mistakes: FP and FN. Here .
- The sum of a row is the number of rows that really belong to the class: 8 failed, 12 passed.
- The sum of a column is the number of times the model said this class: 7 times "fails", 13 times "passes".
A perfect model has numbers only on the diagonal.
3.3Tricks to remember what stands where
- Rows are real. The rows are the reality, the columns are the prediction. (In scikit-learn the truth also comes first inside the brackets:
confusion_matrix(y_test, predicted).) - Zero comes first. Class 0 is the first row and the first column, as numbers are counted: 0, then 1.
- True is on the diagonal. Both "true" cells lie on the diagonal: TN at the top left (0 and 0), TP at the bottom right (1 and 1).
- The column gives the second word. Everything in the column "predicted 1" ends with "positive" (FP, TP). Everything in the column "predicted 0" ends with "negative" (TN, FN).
- Read it like a text. Line by line, from left to right: TN, FP, FN, TP. This is the order in which scikit-learn gives the four numbers.
A warning: some books and websites put the positive class first, or the prediction in the rows. The four numbers are the same; only their places change. Always read the labels of a confusion matrix before reading its numbers.
Try it yourself
Show a hint
Show the solution
Answer: (a) 50; (b) 10; (c) 5; (d) 35; (e) 40; (f) 45.
The second row is the row "actual 1", and the second column is the column "predicted 1".
4The two types of error
4.1Type I and Type II
The two wrong cells have names of their own:
| The model said | The truth | Also called | |
|---|---|---|---|
| Type I error | positive | negative | false positive, false alarm |
| Type II error | negative | positive | false negative, miss |
In the class of 20 students the model made 3 errors of Type I (it said "passes" for students who failed) and 2 errors of Type II (it said "fails" for students who passed).
The names come from statistics. In Topic 19 a Type I error was rejecting a null hypothesis that is true, and a Type II error was keeping one that is false. It is the same idea: "nothing special" is the negative class.
4.2Cases
| Task (positive class) | Type I error: false positive | Type II error: false negative |
|---|---|---|
| Medical test (sick) | a healthy person is told "sick": worry, more tests | a sick person is told "healthy": no treatment |
| Spam filter (spam) | a good e-mail lands in the spam folder | a spam e-mail lands in the inbox |
| Bank, churn (leaves) | a loyal customer gets a call or an offer he did not need | a customer leaves and nobody tried to keep him |
| Bank, fraud (fraud) | an honest payment is blocked | a fraud goes through |
| Fire alarm (fire) | the alarm rings without a fire | there is a fire and the alarm is silent |
| Court (guilty) | an innocent person is convicted | a guilty person goes free |
Which error is worse? It depends on the task. For the medical test and the fire alarm the miss is far worse. For the spam filter and the court the false alarm is worse. The choice of the measure follows from this question, and Part 6 returns to it.
4.3How to remember which is which
- The boy who cried wolf. In the old story the boy shouts "wolf!" and there is no wolf. The villagers believe him: a false alarm, Type I. Later a wolf really comes, he shouts again, and the villagers do not believe him: a miss, Type II. The two errors happen in the order of their numbers.
- Count the strokes. The letter P of "false Positive" has one vertical stroke: Type I. The letter N of "false Negative" has two vertical strokes: Type II.
Type I or Type II?
1 of 8
A fire alarm rings, and there is no fire.
Try it yourself
Show a hint
Show the solution
Answer: (a) Type I; (b) Type II; (c) Type I; (d) Type II.
In (a) and (c) the model said "positive" (fire, spam) and that was false: false positives, Type I. In (b) and (d) the model said "negative" (no fraud, stays) and that was false: false negatives, Type II.
5The measures
Every measure is a fraction made of the four counts. The class of 20 students is used for all of them: , , , .
5.1Accuracy
The share of all predictions that are right:
The model is right for 75 percent of the students. The accuracy uses the diagonal of the matrix, divided by everything.
5.2Precision
Of the students for whom the model said "passes", how many really passed?
When this model says "passes", it is right in 77 of 100 cases. Precision answers the question: can I trust a positive answer of the model? It is lowered by false positives.
5.3Recall
Of the students who really passed, how many did the model find?
The model found 83 percent of the students who passed. Recall answers the question: how many of the positives did the model find? It is lowered by false negatives. Recall has two other names: sensitivity (in medicine) and true positive rate (for the ROC curve).
5.4Specificity
The same as recall, for the negative class. Of the students who really failed, how many did the model recognise?
The model recognised only 62.5 percent of the students who failed. Its other name is the true negative rate.
5.5Where each measure lives in the matrix
Accuracy
the diagonal, of all four cells: 15 of 20, 0.75
Precision
TP, of the column "predicted 1": 10 of 13, 0.769
Recall
TP, of the row "actual 1": 10 of 12, 0.833
Specificity
TN, of the row "actual 0": 5 of 8, 0.625
- Precision is a column: the column of the positive predictions. TP at the bottom, divided by the sum of the column.
- Recall is a row: the row of the real positives. TP on the right, divided by the sum of the row.
- Specificity is the other row: the row of the real negatives.
5.6Tricks to remember precision and recall
- PREcision looks at what the model PREdicted as positive. REcall looks at what is REally positive.
- Both have TP on top. Only the second number below differs: precision adds the false Positives, recall adds the false negatives.
- Precision: "when the model raises its hand, is it right?" Recall: "of all the cases where it should have raised its hand, how often did it?"
5.7Precision and recall pull against each other
A model that says "positive" for everybody has a recall of 1: it misses nobody. Its precision is poor, because most of its alarms are false. A model that says "positive" only when it is completely sure has a high precision, and it misses many positives: a low recall.
Between these two ends, raising one usually lowers the other. That is why neither is enough alone, and why they are reported together.
5.8The F1-score
The F1-score makes one number of the two. It is their harmonic mean:
The same number comes directly from the counts:
Why not the ordinary mean? Take a model with a precision of 1.0 and a recall of 0.1: it is sure of its few alarms and misses nine positives in ten.
The ordinary mean calls this model "medium". The F1-score calls it poor, which is right. The harmonic mean stays close to the smaller of the two numbers: the F1-score is high only when precision and recall are both high.
Notice also what is missing in the F1-score: the true negatives. It looks only at the positive class. That makes it useful when the negative class is very large.
5.9The balanced accuracy
The mean of the recall of the two classes:
Each class counts for one half, however many rows it has. A model that always answers with one class gets a recall of 1 for that class and 0 for the other: a balanced accuracy of exactly 0.5, whatever its accuracy is.
5.10All measures of the example
| Measure | Formula | The class of 20 students |
|---|---|---|
| Accuracy | ||
| Precision | ||
| Recall (sensitivity) | ||
| Specificity | ||
| F1-score | ||
| Balanced accuracy | 0.729 |
One model, six numbers between 0.625 and 0.833. Each one answers a different question.
Set the four counts and watch every measure. It starts with the class of 20 students.
The model said "positive" 13 times and was right 10 times. 12 rows are really positive, and it found 10 of them.
Set TP to 0: recall and F1 fall to 0, whatever the accuracy says. Set FP and TP to 0: the model never says "positive", and the precision cannot be calculated.
Try it yourself
Show a hint
Show the solution
Answer: (a) 0.9; (b) 0.8; (c) 0.5; (d) 0.615.
An accuracy of 0.9, and the model finds only half of the positive rows. The recall and the F1-score show it.
6Which measure for which task
6.1The question to ask
Before choosing a measure, ask: which mistake costs more here, a false alarm or a miss?
- If a miss (false negative) is the expensive mistake, the model must find as many positives as possible: watch the recall.
- If a false alarm (false positive) is the expensive mistake, a positive answer must be trustworthy: watch the precision.
- If both matter, or you need one number: the F1-score.
- If the classes have very different sizes, do not trust the accuracy: use the balanced accuracy or the F1-score.
- If the classes are about equal in size and both mistakes cost the same, the accuracy is fine.
6.2Banking
- Churn. A customer who leaves takes years of income with him. A call or a small offer to a customer who would have stayed costs little. The miss is the expensive mistake: recall comes first. The precision still matters, because the bank cannot call everybody.
- Fraud. A fraud that goes through costs money directly; a payment that is checked once too often costs a moment. Again recall, with an eye on the precision: a bank that blocks too many honest payments loses its customers.
- Loans. The positive class is "will not pay back". Giving a loan to such a customer is a miss, and it is expensive: recall. Refusing a good customer is a false alarm: lost business, so the precision is watched too.
In all three cases the positive class is rare, so the accuracy says little. Banks also compare their models with the ROC-AUC and the Gini coefficient of Part 9.
6.3Healthcare
- A screening test (the first test for a dangerous disease) must not send sick people home. A miss can cost a life, a false alarm costs a second test. The measure is the recall, which doctors call sensitivity.
- A confirming test, before a hard treatment or an operation, must not treat healthy people. Here a positive answer has to be trustworthy: precision and specificity.
Medicine often works in exactly this order: a first test with a high recall, then a second test with a high precision for those who were positive.
6.4Other tasks
| Task | The expensive mistake | Watch |
|---|---|---|
| Spam filter | a good e-mail in the spam folder (false positive) | precision |
| Court, "guilty" | an innocent person convicted (false positive) | precision |
| Fire or gas alarm | a fire without an alarm (false negative) | recall |
| Search for a rare defect in a factory | a broken part that is delivered (false negative) | recall |
| Recommending a film | a recommendation the viewer dislikes (false positive) | precision |
| Classes of equal size, mistakes of equal cost | none in particular | accuracy |
6.5Unbalanced data
When one class is much larger than the other, the data is unbalanced (or imbalanced). Then:
- the accuracy is high for a model that does nothing (Topic 27: 0.80 for "always stays");
- the balanced accuracy gives such a model 0.5;
- the recall of such a model is 0, and so is its F1-score.
So for unbalanced data: report the balanced accuracy or the F1-score, and always look at the confusion matrix itself. Topic 41 is about unbalanced data and what can be done with the data; here only the measuring is the subject.
6.6Summary of the choice
| Situation | Measure |
|---|---|
| A miss is expensive (banking, screening, alarms) | recall |
| A false alarm is expensive (spam, a confirming test, court) | precision |
| Both matter, one number wanted | F1-score |
| Unbalanced classes | balanced accuracy, F1-score |
| Balanced classes, equal costs | accuracy |
| Comparing models without fixing a threshold | ROC-AUC (Part 9) |
Which measure comes first: precision or recall?
1 of 8
A first test for a dangerous disease.
Try it yourself
Show a hint
Show the solution
Answer: (a) recall; (b) precision; (c) recall; (d) the balanced accuracy.
A fraud that passes and a sick person who is sent home are misses: recall. A good e-mail in the spam folder is a false alarm: precision. With 98 percent in one class, always answering with that class gives an accuracy of 0.98 and a balanced accuracy of 0.5.
7The project: from the file to the model
Now the data. The file is Bank Customer Churn Prediction.csv, as in Topic 27: 10,000 customers of a bank, and the column churn says who left (1) and who stayed (0). The positive class is "leaves".
The data file: Bank Customer Churn Prediction.csv
10,000 customers, 12 columns. A cell marked "empty" has no value in the file: pandas shows it as NaN.
Loading the table ...
This part repeats every step up to the trained model, shortly, as a revision. The cells continue from each other like the cells of a notebook.
7.1Step 1: read and look
import pandas as pd
df = pd.read_csv("Bank Customer Churn Prediction.csv")
print(df.shape)
print(df.head())Output
(10000, 12) customer_id credit_score country ... active_member estimated_salary churn 0 15634602 619 France ... 1 101348.88 1 1 15647311 608 Spain ... 1 112542.58 0 2 15619304 502 France ... 0 113931.57 1 3 15701354 699 France ... 0 93826.63 0 4 15737888 850 Spain ... 1 79084.10 0 [5 rows x 12 columns]
10,000 rows and 12 columns: an identification number, ten features and the target churn.
7.2Step 2: check
print(df.isna().sum().sum())
print(df.duplicated().sum())
print(df.dtypes)Output
0 0 customer_id int64 credit_score int64 country str gender str age int64 tenure int64 balance float64 products_number int64 credit_card int64 active_member int64 estimated_salary float64 churn int64 dtype: object
No missing values and no repeated rows (Topic 11). Two columns are text: country and gender. They must become numbers before a model can use them.
7.3Step 3: drop what carries no information
df = df.drop(columns=["customer_id"])
print(df.shape)Output
(10000, 11)
An identification number says nothing about a customer (Topic 24).
7.4Step 4: the target
print(df["churn"].value_counts())
print(df["churn"].mean())Output
churn 0 7963 1 2037 Name: count, dtype: int64 0.2037
2,037 of the 10,000 customers left: about 20 percent. The data is unbalanced, four to one. After Part 6 this is a clear sign: the accuracy alone will not be enough here.
7.5Step 5: encode
gender has two values and becomes 0 and 1. country has three values without an order and gets one-hot encoding (Topic 25). products_number is one-hot encoded too: Topic 27 found that its effect is not in order (customers with 2 products leave least), and that this encoding raised the accuracy from 0.811 to 0.843.
df["gender"] = df["gender"].map({"Female": 0, "Male": 1})
df = pd.get_dummies(df, columns=["country", "products_number"], drop_first=True, dtype=int)
print(df.columns.tolist())Output
['credit_score', 'gender', 'age', 'tenure', 'balance', 'credit_card', 'active_member', 'estimated_salary', 'churn', 'country_Germany', 'country_Spain', 'products_number_2', 'products_number_3', 'products_number_4']
The outliers were looked at in Topic 27: they are real customers and stay in the data.
7.6Step 6: split
from sklearn.model_selection import train_test_split
X = df.drop(columns=["churn"])
y = df["churn"]
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)
print(y_test.sum())Output
(8000, 13) (2000, 13) 393
8,000 customers for training and 2,000 for the test (Topic 23). Of the 2,000 test customers, 393 left and 1,607 stayed.
7.7Step 7: scale
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
print(X_train_scaled.shape, X_test_scaled.shape)Output
(8000, 13) (2000, 13)
The scaler is fitted on the training data and applied to both parts (Topic 24).
7.8Step 8: train
from sklearn.linear_model import LogisticRegression
model = LogisticRegression()
model.fit(X_train_scaled, y_train)
predicted = model.predict(X_test_scaled)
print(predicted[:10])
print(round(model.score(X_test_scaled, y_test), 4))Output
[0 0 0 0 0 0 0 0 0 0] 0.843
predicted holds the class the model gives to each of the 2,000 test customers. The accuracy is 0.843, as in Topic 27. Everything from here on asks: what is behind this number?
Try it yourself
Show a hint
print(predicted.sum()) and print(y_test.sum()). The model marks far fewer customers than really left.Show the solution
print(predicted.sum())
print(y_test.sum())Output
207 393
8The measures in code
All measures are in sklearn.metrics. Every function takes the truth first and the prediction second: (y_test, predicted).
8.1The confusion matrix
from sklearn.metrics import confusion_matrix
print(confusion_matrix(y_test, predicted))Output
[[1543 64] [ 250 143]]
Change it and run: write confusion_matrix(predicted, y_test) and run: the two wrong cells change places. The truth must come first.
The layout is the one of Part 3: rows are the truth, columns the prediction, class 0 first.
| Predicted 0 (stays) | Predicted 1 (leaves) | |
|---|---|---|
| Actual 0 (stayed) | ||
| Actual 1 (left) |
- 1,543 customers stayed and the model said so.
- 64 customers stayed, and the model said "leaves": false alarms.
- 250 customers left, and the model said "stays": misses.
- 143 customers left and the model found them.
This is what the accuracy of 0.843 was hiding. The model is right very often, because it is right about the many customers who stay. Of the 393 customers who left it found only 143.
ravel() lays the matrix out as one line, in the reading order TN, FP, FN, TP, so that the four numbers get names:
tn, fp, fn, tp = confusion_matrix(y_test, predicted).ravel()
print(tn, fp, fn, tp)Output
1543 64 250 143
8.2The matrix as a picture
import matplotlib.pyplot as plt
from sklearn.metrics import ConfusionMatrixDisplay
ConfusionMatrixDisplay.from_predictions(y_test, predicted, display_labels=["stays", "leaves"], cmap="Blues")
plt.title("Confusion matrix of the model")
plt.show()
from_predictions draws the same four numbers, a darker cell for a larger count. display_labels gives the two classes their names.
8.3The measures by hand
With the four counts, every formula of Part 5 is one line:
print(round((tp + tn) / (tp + tn + fp + fn), 4))
print(round(tp / (tp + fp), 4))
print(round(tp / (tp + fn), 4))
print(round(tn / (tn + fp), 4))Output
0.843 0.6908 0.3639 0.9602
The accuracy, the precision, the recall and the specificity.
- Precision 0.6908: when the model says "leaves", it is right in 69 of 100 cases.
- Recall 0.3639: the model finds only 36 of 100 customers who leave. It misses almost two thirds of them.
- Specificity 0.9602: of the customers who stay, it recognises 96 of 100.
8.4The measures with scikit-learn
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
print(round(accuracy_score(y_test, predicted), 4))
print(round(precision_score(y_test, predicted), 4))
print(round(recall_score(y_test, predicted), 4))
print(round(f1_score(y_test, predicted), 4))Output
0.843 0.6908 0.3639 0.4767
The same numbers as by hand, and the F1-score: 0.4767. It is low because the recall is low: the harmonic mean stays close to the smaller number.
from sklearn.metrics import balanced_accuracy_score
print(round(balanced_accuracy_score(y_test, predicted), 4))
print(round((tp / (tp + fn) + tn / (tn + fp)) / 2, 4))Output
0.662 0.662
The balanced accuracy is 0.662. The second line calculates it from the counts, as the mean of the recall (0.3639) and the specificity (0.9602), and gives the same number. The accuracy said 0.843, the balanced accuracy says 0.662. The difference is the size of the class "stays".
8.5Everything in one report
from sklearn.metrics import classification_report
print(classification_report(y_test, predicted, target_names=["stays", "leaves"]))Output
precision recall f1-score support
stays 0.86 0.96 0.91 1607
leaves 0.69 0.36 0.48 393
accuracy 0.84 2000
macro avg 0.78 0.66 0.69 2000
weighted avg 0.83 0.84 0.82 2000How to read the report:
- One line for each class. The line "leaves" holds the precision, the recall and the F1-score of this lesson: 0.69, 0.36, 0.48.
- The line "stays" holds the same measures with "stays" taken as the positive class. Its recall, 0.96, is the specificity.
supportis the number of test rows of each class: 1,607 and 393.macro avgis the plain mean of the two lines. The macro average of the recall, 0.66, is the balanced accuracy.weighted avgis the mean weighted with the support, so the large class dominates it.
8.6The baseline with the new measures
Topic 27 compared every accuracy with the model that always answers "stays". What do the other measures say about it?
import numpy as np
always_stays = np.zeros(len(y_test), dtype=int)
print(round(accuracy_score(y_test, always_stays), 4))
print(round(recall_score(y_test, always_stays), 4))
print(round(balanced_accuracy_score(y_test, always_stays), 4))Output
0.8035 0.0 0.5
np.zeros(len(y_test), dtype=int) is a list of 2,000 zeros: the prediction "stays" for everybody (Topic 8).
An accuracy of 0.8035, a recall of 0 and a balanced accuracy of 0.5. The recall and the balanced accuracy see at once that this "model" finds nobody. (Its precision cannot be calculated: it never says "leaves", so the fraction would be .)
8.7The balanced model, judged again
Topic 27 trained a model with class_weight="balanced" and could not decide, with the accuracy alone, whether it was better. Now it can be judged:
balanced = LogisticRegression(class_weight="balanced")
balanced.fit(X_train_scaled, y_train)
predicted_balanced = balanced.predict(X_test_scaled)
print(confusion_matrix(y_test, predicted_balanced))Output
[[1229 378] [ 91 302]]
The misses fell from 250 to 91. The price: the false alarms rose from 64 to 378.
print(round(accuracy_score(y_test, predicted_balanced), 4))
print(round(precision_score(y_test, predicted_balanced), 4))
print(round(recall_score(y_test, predicted_balanced), 4))
print(round(f1_score(y_test, predicted_balanced), 4))
print(round(balanced_accuracy_score(y_test, predicted_balanced), 4))Output
0.7655 0.4441 0.7684 0.5629 0.7666
| Measure | The first model | The balanced model |
|---|---|---|
| Accuracy | 0.843 | 0.7655 |
| Precision | 0.6908 | 0.4441 |
| Recall | 0.3639 | 0.7684 |
| F1-score | 0.4767 | 0.5629 |
| Balanced accuracy | 0.662 | 0.7666 |
The first model
finds 143 of the 393 customers who left, 64 false alarms
The balanced model
finds 302 of the 393, 378 false alarms
The accuracy and the precision are lower. The recall is more than twice as high, and the F1-score and the balanced accuracy are higher too. For a bank that wants to find the customers who are about to leave (Part 6: the miss is the expensive mistake), the balanced model is the better one: it finds 302 of the 393 leaving customers, where the first model found 143. The accuracy pointed in the wrong direction.
8.8The threshold moves precision and recall
predict uses the threshold 0.5 on the probability of leaving (Topic 27). With predict_proba the threshold can be chosen:
leaving = model.predict_proba(X_test_scaled)[:, 1]
for threshold in [0.2, 0.3, 0.4, 0.5, 0.6, 0.7]:
marked = (leaving >= threshold).astype(int)
print(threshold, round(precision_score(y_test, marked), 4), round(recall_score(y_test, marked), 4))Output
0.2 0.4387 0.7735 0.3 0.5248 0.6183 0.4 0.6226 0.4911 0.5 0.6908 0.3639 0.6 0.7847 0.2875 0.7 0.82 0.2087
Change it and run: add 0.1 and 0.9 to the list and run.
Every line shows the threshold, the precision and the recall.
- A low threshold marks many customers as leaving: the recall is high, the precision low.
- A high threshold marks only the surest cases: the precision is high, the recall low.
- precision
- recall
This is the pull between precision and recall of Part 5, in numbers. The model is the same in all six lines; only the place of the cut changes. With the threshold 0.2 the first model has almost the precision and the recall of the balanced model: class_weight="balanced" and a lower threshold do much the same thing.
So a single pair of precision and recall describes a model at one threshold. To judge the model itself, at all thresholds at once, there is the ROC curve.
Move the threshold of the bank model. The 2,000 test customers and the model stay the same.
With the threshold 0.5 the model marks 207 customers as leaving. It finds 143 of the 393 who left and gives 64 false alarms.
A low threshold: many found, many false alarms. A high threshold: few false alarms, few found. The F1-score is highest between 0.25 and 0.35, not at 0.5.
Try it yourself
tp, fp and fn, then the F1-score with f1_score, each rounded to 4 decimals.Show a hint
2 * tp / (2 * tp + fp + fn). With the function: f1_score(y_test, predicted). The two numbers are the same.Show the solution
print(round(2 * tp / (2 * tp + fp + fn), 4))
print(round(f1_score(y_test, predicted), 4))Output
0.4767 0.4767
Try it yourself
leaving holds the probability of leaving of every test customer. With the threshold 0.3, print the confusion matrix, then the recall, rounded to 4 decimals.Show a hint
marked = (leaving >= 0.3).astype(int), then print(confusion_matrix(y_test, marked)) and print(round(recall_score(y_test, marked), 4)).Show the solution
marked = (leaving >= 0.3).astype(int)
print(confusion_matrix(y_test, marked))
print(round(recall_score(y_test, marked), 4))Output
[[1387 220] [ 150 243]] 0.6183
9The ROC curve, the AUC and the Gini coefficient
9.1Two rates
The ROC curve is drawn from two measures:
| Rate | Formula | In words |
|---|---|---|
| true positive rate (TPR) | the recall | |
| false positive rate (FPR) | the share of false alarms among the real negatives |
The false positive rate is the opposite of the specificity: . For the class of 20 students:
A good model has a high TPR (it finds the positives) and a low FPR (it gives few false alarms).
9.2A curve from thresholds, by hand
A model gave eight students a probability of passing. Four of them passed (P) and four failed (N):
| Student | A | B | C | D | E | F | G | H |
|---|---|---|---|---|---|---|---|---|
| Probability | 0.9 | 0.8 | 0.7 | 0.6 | 0.4 | 0.3 | 0.2 | 0.1 |
| Truth | P | P | N | P | N | P | N | N |
For a threshold, every student with a probability at or above it is predicted "passes". Three thresholds:
| Threshold | Predicted "passes" | TP | FP | ||
|---|---|---|---|---|---|
| 0.75 | A, B | 2 | 0 | 0.5 | 0 |
| 0.5 | A, B, C, D | 3 | 1 | 0.75 | 0.25 |
| 0.25 | A to F | 4 | 2 | 1 | 0.5 |
Each threshold gives one point (FPR, TPR). A threshold above 0.9 marks nobody: the point (0, 0). A threshold of 0 marks everybody: the point (1, 1). The ROC curve joins the points of all thresholds, from (0, 0) to (1, 1). ROC stands for "receiver operating characteristic", a name from radar engineering.
9.3The area under the curve: AUC
The AUC ("area under the curve") is the area under the ROC curve. The whole square has the area 1. In the picture the square is cut into 16 small squares, and 13 of them lie under the curve:
The AUC has a simple meaning. Take one student who passed and one who failed, at random. The AUC is the probability that the model gave the higher number to the one who passed. It can be counted directly. There are pairs of one P and one N:
| Student who passed | Is above | Pairs |
|---|---|---|
| A (0.9) | all 4 students who failed | 4 |
| B (0.8) | all 4 | 4 |
| D (0.6) | E, G and H, but below C | 3 |
| F (0.3) | G and H only | 2 |
The same number as the area. So the AUC measures how well the model puts the positives above the negatives, without choosing any threshold.
9.4Which curve is better, and why
- perfect: AUC 1
- good: AUC 0.8
- weak: AUC 0.6
- guessing: AUC 0.5
- The diagonal is a model that guesses: it marks rows as positive at random, so it catches the same share of the positives and of the negatives. at every threshold, and the AUC is 0.5.
- The perfect model gives every positive a higher probability than every negative. Its curve goes straight up to the top left corner, the point with and , and then to the right. Its AUC is 1.
- Real models lie in between. The closer a curve comes to the top left corner, the better: at the same rate of false alarms it finds more of the positives. A curve that lies above another one everywhere belongs to the better model, and it has the larger area.
- A curve below the diagonal (AUC under 0.5) means the model puts the classes the wrong way round.
A rough guide for reading an AUC (the borders are habits, not laws):
| AUC | Reading |
|---|---|
| 0.5 | no better than guessing |
| 0.6 to 0.7 | weak |
| 0.7 to 0.8 | fair |
| 0.8 to 0.9 | good |
| above 0.9 | very good (and worth a second look: is a column leaking the answer?) |
9.5The points of the bank model, with the measures you know
Back to the project. The ROC curve needs the probabilities, not the classes: leaving holds the probability of leaving of every test customer. For five thresholds, the cell calculates the two rates from the confusion matrix:
fpr_points = []
tpr_points = []
for threshold in [0.1, 0.3, 0.5, 0.7, 0.9]:
marked = (leaving >= threshold).astype(int)
tn, fp, fn, tp = confusion_matrix(y_test, marked).ravel()
fpr_points.append(fp / (fp + tn))
tpr_points.append(tp / (tp + fn))
print(threshold, round(fp / (fp + tn), 4), round(tp / (tp + fn), 4))Output
0.1 0.4717 0.9033 0.3 0.1369 0.6183 0.5 0.0398 0.3639 0.7 0.0112 0.2087 0.9 0.0037 0.0992
Every line shows a threshold, its false positive rate and its true positive rate. With the threshold 0.1 the model finds nine of ten leaving customers, and it gives a false alarm for almost half of the customers who stay. With 0.9 it gives almost no false alarm and finds only one leaving customer in ten.
Five points are already the outline of a curve:
plt.plot(fpr_points, tpr_points, marker="o")
plt.plot([0, 1], [0, 1], linestyle="--")
plt.xlabel("False positive rate")
plt.ylabel("True positive rate (recall)")
plt.title("Five points of the ROC curve")
plt.show()
9.6The whole curve with scikit-learn
roc_curve does the same for every useful threshold. It takes the truth and the probabilities and returns three arrays: the false positive rates, the true positive rates and the thresholds.
from sklearn.metrics import roc_curve
fpr, tpr, thresholds = roc_curve(y_test, leaving)
plt.plot(fpr, tpr, label="the model")
plt.plot([0, 1], [0, 1], linestyle="--", label="guessing")
plt.xlabel("False positive rate")
plt.ylabel("True positive rate (recall)")
plt.title("ROC curve")
plt.legend()
plt.show()
Change it and run: write roc_curve(y_test, predicted) and run: with classes in the place of probabilities only one point is left between the two corners.
The curve lies well above the diagonal and far from the top left corner: a good model, not a perfect one.
The same threshold, as a point on the ROC curve of the bank model.
Threshold 0.5: false positive rate 0.040, true positive rate 0.364.
A low threshold moves the point up and to the right, a high one down and to the left. The curve itself does not move: its area, the AUC of 0.837, belongs to all thresholds at once.
9.7The AUC in code
from sklearn.metrics import roc_auc_score
auc = roc_auc_score(y_test, leaving)
print(round(auc, 4))Output
0.837
An AUC of 0.837: take a customer who left and one who stayed, and in about 84 of 100 such pairs the model gives the higher probability to the one who left.
Give roc_auc_score the probabilities (leaving), not the classes (predicted). With classes there is only one threshold, and the curve shrinks to a single point.
9.8Comparing models
A weaker model for comparison: one that knows only the age and the balance of a customer.
columns = ["age", "balance"]
small_scaler = StandardScaler()
small_train = small_scaler.fit_transform(X_train[columns])
small_test = small_scaler.transform(X_test[columns])
small = LogisticRegression()
small.fit(small_train, y_train)
small_leaving = small.predict_proba(small_test)[:, 1]
print(round(roc_auc_score(y_test, small_leaving), 4))Output
0.7461
Change it and run: change the list to ["credit_score", "tenure"] and run: the AUC falls to about 0.52, hardly better than guessing.
small_fpr, small_tpr, small_thresholds = roc_curve(y_test, small_leaving)
plt.plot(fpr, tpr, label="all 13 features")
plt.plot(small_fpr, small_tpr, label="age and balance only")
plt.plot([0, 1], [0, 1], linestyle="--", label="guessing")
plt.xlabel("False positive rate")
plt.ylabel("True positive rate (recall)")
plt.title("Two models, two ROC curves")
plt.legend()
plt.show()
The AUC of the small model is 0.7461, against 0.837. The curve of the full model lies above the curve of the small model almost everywhere: at the same rate of false alarms it finds more of the leaving customers. Its area is larger. The full model is the better one whatever threshold is chosen, and the AUC says so in one number.
And the balanced model?
balanced_leaving = balanced.predict_proba(X_test_scaled)[:, 1]
print(round(roc_auc_score(y_test, balanced_leaving), 4))Output
0.8385
Almost the same AUC as the first model. That is an important result. The two models put the customers in almost the same order; they only cut the list at different places. class_weight="balanced" did not make a better model in the sense of the AUC: it moved the model to another point of nearly the same curve, a point with more recall. The AUC judges the order, the recall and the precision judge one cut.
9.9The Gini coefficient
Banks often report the Gini coefficient in the place of the AUC. It is the same information on another scale:
| AUC | Gini | |
|---|---|---|
| Guessing | 0.5 | 0 |
| Perfect model | 1 | 1 |
The Gini coefficient runs from 0 (guessing) to 1 (perfect), which many people find easier to read than "from 0.5 to 1". For the eight students:
For the bank model:
gini = 2 * auc - 1
print(round(gini, 4))Output
0.674
In the picture, the Gini coefficient is the area between the ROC curve and the diagonal, compared with the same area for the perfect model. (The Gini coefficient of economics, which measures the inequality of incomes, is a relative of it with the same name.)
9.10What the AUC does not tell
- The AUC does not choose a threshold. To use a model, a threshold is still needed, and with it come a precision and a recall.
- With a very rare positive class, the false positive rate stays small even when the false alarms outnumber the hits, so the ROC curve can look better than the model feels in use. Look at the precision as well.
9.11More than two classes
With three or more classes the confusion matrix has one row and one column for every class, and the diagonal still holds the right predictions. Precision, recall and F1 are calculated for every class in turn (this class against all the others), as the lines of classification_report did, and then averaged. This lesson stays with two classes.
Try it yourself
Show a hint
Show the solution
Answer: (a) 0.5; (b) 0.2; (c) 0.9; (d) 0.8.
0.9 is above all five customers who stayed: 5 pairs. 0.5 is above four of them and below 0.7: 4 pairs.
Try it yourself
small_leaving holds the probabilities of the small model (age and balance only). Print its AUC, then its Gini coefficient, each rounded to 4 decimals.Show a hint
small_auc = roc_auc_score(y_test, small_leaving), then print(round(small_auc, 4)) and print(round(2 * small_auc - 1, 4)).Show the solution
small_auc = roc_auc_score(y_test, small_leaving)
print(round(small_auc, 4))
print(round(2 * small_auc - 1, 4))Output
0.7461 0.4922
10The workflow, step by step
| Step | What is done | In this project |
|---|---|---|
| 1. Look and check | shape, missing values, text columns | 10,000 customers, nothing missing |
| 2. Drop | columns without information | customer_id |
| 3. Target | the share of each class | 20 percent left: unbalanced |
| 4. Encode | text and unordered numbers | gender, country, products_number |
| 5. Split | training and test data | 8,000 and 2,000 |
| 6. Scale | fit on the training data | StandardScaler |
| 7. Train | the model | LogisticRegression |
| 8. Confusion matrix | the four counts | 1543, 64, 250, 143 |
| 9. Choose the measure | which mistake costs more? | a miss: recall |
| 10. Measures | precision, recall, F1, balanced accuracy | 0.69, 0.36, 0.48, 0.66 |
| 11. Threshold or class weights | move along the curve | recall 0.77 with balanced classes |
| 12. ROC-AUC and Gini | the model at all thresholds | 0.837 and 0.674 |
Steps 1 to 7 are the workflow of Topic 27. Steps 8 to 12 are new: judging a classifier is a piece of work of its own, not one line.
Try it yourself
roc_auc_score need besides the truth: the predicted classes or the probabilities? (b) What comes first inside the brackets of every measure of scikit-learn? (c) What is looked at before a measure is chosen? (d) With which data is a threshold chosen?Show a hint
Show the solution
Answer: (a) the probabilities; (b) the truth; (c) the confusion matrix; (d) the training data.
With classes there is only one threshold and no curve. Every function is called as (y_test, predicted). The confusion matrix shows which mistake the model makes, and the task says which mistake is expensive: then the measure is clear. A threshold is a choice like a hyperparameter, so the test data must not make it.
11Common mistakes
| Mistake | Why it is wrong | Right |
|---|---|---|
| Judging a model on unbalanced data with the accuracy alone. | A model that finds nobody can have a high accuracy. | Confusion matrix, recall, precision, balanced accuracy. |
| Mixing up precision and recall. | They divide by different sums. | Precision: by what was predicted positive. Recall: by what is really positive. |
| Reading a confusion matrix without its labels. | Books and libraries place the cells differently. | In scikit-learn: rows are the truth, class 0 first: TN, FP, FN, TP. |
Writing confusion_matrix(predicted, y_test). | The matrix is turned round: FP and FN change places. | The truth first: (y_test, predicted). |
| "Positive means good." | The positive class is the one being looked for, often the bad news. | Decide and say which class is positive. |
| Reporting only the precision, or only the recall. | Each can be made high alone: mark nobody, or mark everybody. | Report both, or the F1-score. |
| Taking the ordinary mean of precision and recall. | It hides a very low value. | The harmonic mean: the F1-score. |
Giving roc_auc_score the predicted classes. | Only one threshold is used; the result is not the AUC of the model. | Give the probabilities: predict_proba(...)[:, 1]. |
| "An AUC of 0.5 is a model that is half right." | 0.5 is guessing: the model cannot order the classes at all. | The scale of the AUC starts at 0.5; the Gini starts at 0. |
| Choosing the threshold with the test data. | The test data then takes part in building the model. | Choose it on training data, with cross-validation. |
Thinking class_weight="balanced" makes a better model. | It mainly moves the cut: more recall, less precision. | Compare the AUC, and judge the cut by the costs. |
| Comparing an F1-score with an accuracy. | They measure different things on different scales. | Compare the same measure between models. |
12Solved problems
Sixteen problems. The first four are short and solved by hand. Problems 5 to 16 are one project on Bank Customer Churn Prediction.csv, solved step by step like a notebook: every cell continues from the cells above it. It is the workflow of the lesson once more, with another split.
Problem 1: From a story to the matrix
A spam filter checked 200 e-mails. 50 of them were spam. The filter marked 40 e-mails as spam, and 30 of those really were spam. Find TP, FP, FN and TN. The positive class is "spam".
Idea. Start with what the model said and whether it was right (Part 2). The rest follows from the sums.
| Count | Calculation | In words |
|---|---|---|
| 30 | marked as spam, and spam | |
| marked as spam, but good | ||
| spam that was not marked | ||
| good, and not marked |
| Predicted 0 (good) | Predicted 1 (spam) | |
|---|---|---|
| Actual 0 (good) | ||
| Actual 1 (spam) |
Why: the column "predicted 1" adds up to the 40 marked e-mails, the row "actual 1" to the 50 spam e-mails, and all four cells to 200.
Problem 2: The measures of the spam filter
For the filter of Problem 1 (, , , ), calculate the accuracy, the precision, the recall and the F1-score.
Idea. Every measure is a fraction of the four counts (Part 5).
Why: the accuracy looks good, 0.85. The recall shows the weakness: 40 percent of the spam still reaches the inbox. For a spam filter the precision matters most (a good e-mail in the spam folder is the expensive mistake), and 0.75 means that one marked e-mail in four was a good one. That is too many.
Problem 3: The trap of the accuracy
A disease is found in 10 of 1,000 people. A "model" says "healthy" for everybody. Calculate its accuracy, its recall and its balanced accuracy. The positive class is "sick".
Idea. Write down the four counts first (Parts 2 and 5).
Why: an accuracy of 0.99 for a model that finds no sick person at all. The recall, 0, and the balanced accuracy, 0.5, show the truth. With unbalanced classes the accuracy must never be read alone.
Problem 4: A ROC curve by hand
A model gave six customers a probability of leaving. Three left (P): 0.9, 0.7 and 0.4. Three stayed (N): 0.6, 0.3 and 0.2. (a) Calculate the TPR and the FPR for the threshold 0.5. (b) Calculate the AUC by counting pairs. (c) Calculate the Gini coefficient.
Idea. A threshold gives one point of the curve. The AUC is the share of the pairs (one P, one N) in which the P has the higher number (Part 9).
(a) At or above 0.5 are 0.9 (P), 0.7 (P) and 0.6 (N), so and .
(b) There are pairs. 0.9 is above 0.6, 0.3 and 0.2: 3 pairs. 0.7 is above 0.6, 0.3 and 0.2: 3 pairs. 0.4 is above 0.3 and 0.2: 2 pairs.
(c) The Gini coefficient:
Why: only one pair is in the wrong order: the customer with 0.4 who left and the customer with 0.6 who stayed. A model with no such pair would have an AUC of 1.
Problem 5: Read and check
Read the file. Print its shape, the number of missing values and the share of customers who left.
Idea. The first steps of the workflow (Part 7).
import pandas as pd
df = pd.read_csv("Bank Customer Churn Prediction.csv")
print(df.shape)
print(df.isna().sum().sum())
print(df["churn"].mean())Output
(10000, 12) 0 0.2037
Why: one customer in five left. The classes are unbalanced, so the accuracy will not be enough.
Problem 6: Drop and encode
Drop customer_id. Encode gender as 0 (Female) and 1 (Male). One-hot encode country and products_number with drop_first=True. Print the number of columns.
Idea. A column without information is dropped; text and numbers without order are encoded (Part 7).
df = df.drop(columns=["customer_id"])
df["gender"] = df["gender"].map({"Female": 0, "Male": 1})
df = pd.get_dummies(df, columns=["country", "products_number"], drop_first=True, dtype=int)
print(len(df.columns))Output
14
Why: 14 columns: 13 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 number of test customers and how many of them left.
Idea. The split comes before everything that learns from the rows (Part 7).
from sklearn.model_selection import train_test_split
X = df.drop(columns=["churn"])
y = df["churn"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=7)
print(len(y_test), y_test.sum())Output
2500 510
Why: these two numbers are the sums of the confusion matrix: all its cells add up to 2,500, and its row "actual 1" to 510.
Problem 8: Scale and train
Scale the features with a StandardScaler fitted on the training data. Train a LogisticRegression and print its test accuracy, rounded to 4 decimals.
Idea. fit_transform on the training data, transform on the test data, then fit and score (Part 7).
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
model = LogisticRegression()
model.fit(X_train_scaled, y_train)
print(round(model.score(X_test_scaled, y_test), 4))Output
0.8376
Why: an accuracy of about 0.84. The following problems look behind it.
Problem 9: The confusion matrix
Predict the classes of the test customers and print the confusion matrix.
Idea. confusion_matrix(y_test, predicted): the truth first (Part 8).
from sklearn.metrics import confusion_matrix
predicted = model.predict(X_test_scaled)
print(confusion_matrix(y_test, predicted))Output
[[1917 73] [ 333 177]]
Why: read it like a text: TN, FP, FN, TP. The model is right about almost all customers who stayed, and it misses most of the customers who left: the number at the bottom left is larger than the number at the bottom right.
Problem 10: The four counts and the recall by hand
Give the four counts names with ravel(). Print the number of misses and the number of false alarms, then the recall calculated from the counts, rounded to 4 decimals.
Idea. ravel() gives TN, FP, FN, TP; (Parts 5 and 8).
tn, fp, fn, tp = confusion_matrix(y_test, predicted).ravel()
print(fn, fp)
print(round(tp / (tp + fn), 4))Output
333 73 0.3471
Why: many more misses than false alarms. This model is careful: it says "leaves" rarely, so it finds only about a third of the customers who leave.
Problem 11: Precision, recall and F1
Print the precision, the recall and the F1-score with the functions of scikit-learn, rounded to 4 decimals.
Idea. precision_score, recall_score, f1_score, each with (y_test, predicted) (Part 8).
from sklearn.metrics import precision_score, recall_score, f1_score
print(round(precision_score(y_test, predicted), 4))
print(round(recall_score(y_test, predicted), 4))
print(round(f1_score(y_test, predicted), 4))Output
0.708 0.3471 0.4658
Why: the recall is the number of Problem 10. The F1-score lies between the precision and the recall, closer to the smaller one.
Problem 12: The balanced accuracy
Print the balanced accuracy of the model, and the balanced accuracy of always answering 0, both rounded to 4 decimals.
Idea. The mean of the recall of the two classes; a model that always gives one class gets 0.5 (Parts 5 and 8).
import numpy as np
from sklearn.metrics import balanced_accuracy_score
always_stays = np.zeros(len(y_test), dtype=int)
print(round(balanced_accuracy_score(y_test, predicted), 4))
print(round(balanced_accuracy_score(y_test, always_stays), 4))Output
0.6552 0.5
Why: on this scale the model is clearly above the "model" that finds nobody, and still far from 1. The balanced accuracy is the honest relative of the accuracy for unbalanced data.
Problem 13: A lower threshold
Take the probability of leaving of every test customer. With the threshold 0.3, print the precision and the recall, rounded to 4 decimals.
Idea. predict_proba(...)[:, 1], compared with the threshold (Part 8).
leaving = model.predict_proba(X_test_scaled)[:, 1]
marked = (leaving >= 0.3).astype(int)
print(round(precision_score(y_test, marked), 4))
print(round(recall_score(y_test, marked), 4))Output
0.5504 0.6098
Why: compared with Problem 11 the recall is much higher and the precision lower. The model did not change; the cut moved.
Problem 14: The balanced model
Train a model with class_weight="balanced". Print its confusion matrix, then its recall and its F1-score, rounded to 4 decimals.
Idea. Mistakes on the rare class weigh more, so the model marks more customers (Part 8).
balanced = LogisticRegression(class_weight="balanced")
balanced.fit(X_train_scaled, y_train)
predicted_balanced = balanced.predict(X_test_scaled)
print(confusion_matrix(y_test, predicted_balanced))
print(round(recall_score(y_test, predicted_balanced), 4))
print(round(f1_score(y_test, predicted_balanced), 4))Output
[[1516 474] [ 134 376]] 0.7373 0.5529
Why: far fewer misses, many more false alarms. The recall and the F1-score are higher than in Problem 11. For a bank that wants to keep its customers this is the better model.
Problem 15: AUC and Gini
Print the AUC of the first model and its Gini coefficient, rounded to 4 decimals.
Idea. roc_auc_score with the probabilities; (Part 9).
from sklearn.metrics import roc_auc_score
auc = roc_auc_score(y_test, leaving)
print(round(auc, 4))
print(round(2 * auc - 1, 4))Output
0.8333 0.6665
Why: an AUC above 0.8: in more than four of five pairs of one leaving and one staying customer, the model gives the higher probability to the one who left.
Problem 16: The ROC curve
Draw the ROC curve of the first model, with the diagonal of guessing.
Idea. roc_curve returns the false positive rates and the true positive rates of all thresholds (Part 9).
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve
fpr, tpr, thresholds = roc_curve(y_test, leaving)
plt.plot(fpr, tpr, label="the model")
plt.plot([0, 1], [0, 1], linestyle="--", label="guessing")
plt.xlabel("False positive rate")
plt.ylabel("True positive rate (recall)")
plt.title("ROC curve")
plt.legend()
plt.show()
Why: the curve lies clearly above the diagonal. The area between the two, doubled, is the Gini coefficient of Problem 15.
13Practice
Sixteen problems. The first four are solved on paper. Problems 5 to 16 are one project in Python on Bank Customer Churn Prediction.csv, the file of the lesson (the whole table): its steps continue from one another, like the cells of a notebook, from reading the file to the AUC. Under every problem there is a hint and a solution.
13.1Group A: by hand
- 1.A bank checked 1,000 payments. 40 of them were frauds. Its model marked 50 payments as fraud, and 30 of those really were frauds. Find TP, FP, FN and TN. The positive class is "fraud".
Show a hint
TP is given. FP is the rest of the marked payments, FN the rest of the frauds, TN everything else.Show one possible solution
Answer: , , , .
The 50 marked payments are the column "predicted 1", the 40 frauds are the row "actual 1".
- 2.For the model of Problem 1, calculate (a) the accuracy, (b) the precision, (c) the recall, (d) the F1-score, with 3 decimals where needed.
Show a hint
Precision divides by what was marked (50), recall by the real frauds (40). For the F1-score: .Show one possible solution
Answer: (a) 0.97; (b) 0.6; (c) 0.75; (d) 0.667.
The accuracy of 0.97 says little here: answering "no fraud" for every payment would give 0.96.
- 3.(a) A healthy person is told "you are sick". Which type of error is it? (b) Which measure matters most for a first test for a dangerous disease? (c) Which measure matters most for a spam filter?
Show a hint
(a) The model said positive, and that was false. (b) and (c): which mistake is the expensive one, the miss or the false alarm?Show one possible solution
Answer: (a) Type I (a false positive); (b) recall; (c) precision.
(a) A false positive is a Type I error: a false alarm. (b) A sick person who is sent home is a miss, the expensive mistake: recall, which doctors call sensitivity. (c) A good e-mail in the spam folder is a false alarm, the expensive mistake: precision.
- 4.A model gave seven customers a probability of leaving. Three left (P): 0.8, 0.6 and 0.3. Four stayed (N): 0.7, 0.4, 0.2 and 0.1. (a) Calculate the TPR for the threshold 0.5, with 3 decimals. (b) Calculate the FPR for the threshold 0.5. (c) Calculate the AUC by counting pairs. (d) Calculate the Gini coefficient.
Show a hint
Who is at or above 0.5? There are pairs. For each P, count the N below it.Show one possible solution
Answer: (a) 0.667; (b) 0.25; (c) 0.75; (d) 0.5.
At or above 0.5 are 0.8 (P), 0.7 (N) and 0.6 (P): two of the three P and one of the four N.
0.8 is above all 4 customers who stayed. 0.6 is above 0.4, 0.2 and 0.1: 3 pairs. 0.3 is above 0.2 and 0.1: 2 pairs.
13.2Group B: one project in Python
The same workflow as in the lesson, on the same 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 10: from the file to the model
Read the file, drop and encode, split, scale and train: the steps of Topic 27 once more.
- 5.Read
Bank Customer Churn Prediction.csvintodf. Print the shape, then the number of customers who left.Show a hint
df = pd.read_csv("Bank Customer Churn Prediction.csv"), thenprint(df.shape)andprint(df["churn"].sum()).Show one possible solution
Pythonimport pandas as pd df = pd.read_csv("Bank Customer Churn Prediction.csv") print(df.shape) print(df["churn"].sum())Output
(10000, 12) 2037
- 6.Drop the column
customer_idand encodegenderas 0 (Female) and 1 (Male). Print the number of women. This step continues from Step 5.Show a hint
df = df.drop(columns=["customer_id"])anddf["gender"] = df["gender"].map({"Female": 0, "Male": 1}). The women are the rows with 0:print((df["gender"] == 0).sum()).Show one possible solution
Python, continues from the cells abovedf = df.drop(columns=["customer_id"]) df["gender"] = df["gender"].map({"Female": 0, "Male": 1}) print((df["gender"] == 0).sum())Output
4543
- 7.One-hot encode
countryandproducts_numberinside the table, withdrop_first=Trueanddtype=int. Print the number of columns. This step continues from Step 6.Show a hint
df = pd.get_dummies(df, columns=["country", "products_number"], drop_first=True, dtype=int), thenprint(len(df.columns)).Show one possible solution
Python, continues from the cells abovedf = pd.get_dummies(df, columns=["country", "products_number"], drop_first=True, dtype=int) print(len(df.columns))Output
14
- 8.Make
X(all columns withoutchurn) andy(churn). Split them withtest_size=0.3andrandom_state=1. Print the number of test customers, then how many of them left. This step continues from Step 7.Show a hint
X = df.drop(columns=["churn"]),y = df["churn"], thenX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1). Printlen(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=["churn"]) y = df["churn"] 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
3000 627
- 9.Scale the features with a
StandardScalercalledscalerintoX_train_scaledandX_test_scaled. Print the shape ofX_test_scaled. This step continues from Step 8.Show a hint
scaler = StandardScaler(),X_train_scaled = scaler.fit_transform(X_train),X_test_scaled = scaler.transform(X_test), thenprint(X_test_scaled.shape).Show one possible solution
Python, continues from the cells abovefrom sklearn.preprocessing import StandardScaler scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train) X_test_scaled = scaler.transform(X_test) print(X_test_scaled.shape)Output
(3000, 13)
- 10.Train a
LogisticRegressioncalledmodeland put its predictions for the test customers intopredicted. Print the test accuracy, rounded to 4 decimals, then the number of customers the model marks as leaving. This step continues from Step 9.Show a hint
model = LogisticRegression(),model.fit(X_train_scaled, y_train),predicted = model.predict(X_test_scaled). Thenprint(round(model.score(X_test_scaled, y_test), 4))andprint(predicted.sum()).Show one possible solution
Python, continues from the cells abovefrom sklearn.linear_model import LogisticRegression model = LogisticRegression() model.fit(X_train_scaled, y_train) predicted = model.predict(X_test_scaled) print(round(model.score(X_test_scaled, y_test), 4)) print(predicted.sum())Output
0.84 309
Steps 11 to 14: the confusion matrix and its measures
The four counts, then precision, recall, the F1-score, the specificity and the balanced accuracy.
- 11.Print the confusion matrix of the model. This step continues from Step 10.
Show a hint
print(confusion_matrix(y_test, predicted)): the truth first, then the prediction.Show one possible solution
Python, continues from the cells abovefrom sklearn.metrics import confusion_matrix print(confusion_matrix(y_test, predicted))Output
[[2292 81] [ 399 228]]
- 12.Give the four counts the names
tn,fp,fn,tp. Print the number of misses (leaving customers the model did not find), then the number of false alarms. This step continues from Step 11.Show a hint
tn, fp, fn, tp = confusion_matrix(y_test, predicted).ravel(). The misses arefn, the false alarms arefp.Show one possible solution
Python, continues from the cells abovetn, fp, fn, tp = confusion_matrix(y_test, predicted).ravel() print(fn) print(fp)Output
399 81
- 13.Print the precision, the recall and the F1-score of the model, in this order, each rounded to 4 decimals. This step continues from Step 10.
Show a hint
print(round(precision_score(y_test, predicted), 4)), and the same withrecall_scoreandf1_score.Show one possible solution
Python, continues from the cells abovefrom sklearn.metrics import precision_score, recall_score, f1_score print(round(precision_score(y_test, predicted), 4)) print(round(recall_score(y_test, predicted), 4)) print(round(f1_score(y_test, predicted), 4))Output
0.7379 0.3636 0.4872
- 14.Print the specificity, calculated from the four counts, then the balanced accuracy with the function of scikit-learn, each rounded to 4 decimals. This step continues from Step 12.
Show a hint
The specificity istn / (tn + fp). Thenprint(round(balanced_accuracy_score(y_test, predicted), 4)).Show one possible solution
Python, continues from the cells abovefrom sklearn.metrics import balanced_accuracy_score print(round(tn / (tn + fp), 4)) print(round(balanced_accuracy_score(y_test, predicted), 4))Output
0.9659 0.6648
Steps 15 and 16: the threshold, the AUC and the Gini coefficient
Another cut of the same model, then the model at all thresholds and its ROC curve.
- 15.Put the probability of leaving of every test customer into
leaving. With the threshold 0.3, print the precision, then the recall, each rounded to 4 decimals. This step continues from Step 13.Show a hint
leaving = model.predict_proba(X_test_scaled)[:, 1], thenmarked = (leaving >= 0.3).astype(int)and the two functions with(y_test, marked). The recall is much higher than in Step 13 and the precision lower: the same model, another cut.Show one possible solution
Python, continues from the cells aboveleaving = model.predict_proba(X_test_scaled)[:, 1] marked = (leaving >= 0.3).astype(int) print(round(precision_score(y_test, marked), 4)) print(round(recall_score(y_test, marked), 4))Output
0.5607 0.6045
- 16.Print the AUC of the model, then its Gini coefficient, each rounded to 4 decimals. Then draw the ROC curve with the diagonal of guessing. This step continues from Step 15.
Show a hint
auc = roc_auc_score(y_test, leaving), thenprint(round(auc, 4))andprint(round(2 * auc - 1, 4)). For the curve:fpr, tpr, thresholds = roc_curve(y_test, leaving),plt.plot(fpr, tpr),plt.plot([0, 1], [0, 1], linestyle="--")andplt.show().Show one possible solution
Python, continues from the cells aboveimport matplotlib.pyplot as plt from sklearn.metrics import roc_auc_score, roc_curve auc = roc_auc_score(y_test, leaving) print(round(auc, 4)) print(round(2 * auc - 1, 4)) fpr, tpr, thresholds = roc_curve(y_test, leaving) plt.plot(fpr, tpr, label="the model") plt.plot([0, 1], [0, 1], linestyle="--", label="guessing") plt.xlabel("False positive rate") plt.ylabel("True positive rate (recall)") plt.title("ROC curve") plt.legend() plt.show()Output
0.8389 0.6778

14Check yourself
Twelve questions. Every question has one right answer.
0 of 12 answered.
15Summary
| Predicted 0 | Predicted 1 | |
|---|---|---|
| Actual 0 | TN | FP (Type I error) |
| Actual 1 | FN (Type II error) | TP |
| Measure | Formula | Question it answers |
|---|---|---|
| Accuracy | how often is the model right? | |
| Precision | can a positive answer be trusted? | |
| Recall (sensitivity, TPR) | how many positives are found? | |
| Specificity | how many negatives are recognised? | |
| F1-score | precision and recall in one number | |
| Balanced accuracy | the accuracy with equal weight for both classes | |
| False positive rate | the share of false alarms among the negatives | |
| AUC | the area under the ROC curve | how well are positives put above negatives? |
| Gini | the AUC on a scale from 0 to 1 |
| Code | What it does |
|---|---|
confusion_matrix(y_test, predicted) | the matrix: rows the truth, class 0 first |
tn, fp, fn, tp = confusion_matrix(y_test, predicted).ravel() | the four counts with names |
ConfusionMatrixDisplay.from_predictions(y_test, predicted) | the matrix as a picture |
accuracy_score, precision_score, recall_score, f1_score | the measures, each with (y_test, predicted) |
balanced_accuracy_score(y_test, predicted) | the balanced accuracy |
classification_report(y_test, predicted) | all measures of every class |
leaving = model.predict_proba(X_test_scaled)[:, 1] | the probability of class 1 |
(leaving >= 0.3).astype(int) | the classes for another threshold |
roc_curve(y_test, leaving) | the points of the ROC curve |
roc_auc_score(y_test, leaving) | the AUC (give the probabilities) |
Rules to keep
- A classifier can be wrong in two ways. Look at the confusion matrix before any single number.
- The second word of TP, TN, FP, FN is what the model said; the first word says whether it was right.
- Precision divides by what was predicted positive, recall by what is really positive.
- Ask which mistake costs more. A miss: recall. A false alarm: precision. Both: F1.
- With unbalanced classes the accuracy misleads. Use the balanced accuracy or the F1-score.
- The threshold trades precision for recall. The ROC curve shows the model at all thresholds, and the AUC is its area.
- The closer the curve comes to the top left corner, the better. .
What comes next
Every model so far was a weighted sum of the features. Topic 29 starts a different family: decision trees, which ask a row of yes-or-no questions. They are judged with the measures of this lesson.