Asiman Data School

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.

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. 1.Why a classifier needs more than one measure
  2. 2.The four outcomes: true positive, true negative, false positive, false negative
  3. 3.The confusion matrix: how to draw it, read it, and remember what stands where
  4. 4.The two types of error, and what each one costs
  5. 5.Accuracy, precision, recall, specificity, the F1-score and the balanced accuracy
  6. 6.Which measure fits which task: banking, healthcare, spam, unbalanced data
  7. 7.All of them in scikit-learn, on a real data file
  8. 8.The ROC curve, the AUC and the Gini coefficient
The words of this lesson
WordMeaning
Positive classthe class the model is looking for, coded 1 (the customer leaves, the patient is sick)
Negative classthe 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 matrixthe table of these four counts
Accuracythe share of all predictions that are right
Precisionof the rows the model called positive, the share that are positive
Recallof the rows that are positive, the share the model found
F1-scoreone number made of precision and recall
ROC curverecall against the rate of false alarms, for every threshold
AUCthe 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

In a data set 990 of 1,000 rows are negative and 10 are positive. A "model" answers "negative" for every row. (a) What is its accuracy? (b) How many of the 10 positive rows does it find? (c) In how many different ways can a classifier be wrong?

Show a hint
It is right for every negative row, and it never says "positive".
Show the solution

Answer: (a) 0.99; (b) 0; (c) two.

9901000=0.99\frac{990}{1000} = 0.99

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:

A class of 20 students
GroupThe truthThe model saidStudents
True positive (TP)passedpasses10
False negative (FN)passedfails2
True negative (TN)failedfails5
False positive (FP)failedpasses3
TP+FN+TN+FP=10+2+5+3=20\begin{aligned} \text{TP} + \text{FN} + \text{TN} + \text{FP} &= 10 + 2 + 5 + 3 \\ &= 20 \end{aligned}

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.

How to read the names
NameThe model saidWas it right?So the truth is
True positivepositiveyespositive
True negativenegativeyesnegative
False positivepositivenonegative
False negativenegativenopositive

Two sums are worth seeing at once:

How to read the names
SumWho
really positiveTP+FN=10+2=12\text{TP} + \text{FN} = 10 + 2 = 12the students who passed
really negativeTN+FP=5+3=8\text{TN} + \text{FP} = 5 + 3 = 8the students who failed
predicted positiveTP+FP=10+3=13\text{TP} + \text{FP} = 10 + 3 = 13the model said "passes"
predicted negativeTN+FN=5+2=7\text{TN} + \text{FN} = 5 + 2 = 7the 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

A test looks for a disease, and the positive class is "sick". Name the outcome. (a) The test says "sick", and the person is healthy. (b) The test says "healthy", and the person is sick. (c) The test says "sick", and the person is sick. (d) The test says "healthy", and the person is healthy.

Show a hint
The second word is what the test said ("sick" is positive). The first word says whether the test was right.
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.

The confusion matrix of the class of 20 students. The rows are the truth, the columns what the model said, and class 0 comes first. The two green cells on the diagonal are the right predictions, 15 students. The two red cells are the mistakes, 5 students.

As a plain table:

Drawing it
Predicted 0 (fails)Predicted 1 (passes)Sum
Actual 0 (failed)TN=5\text{TN} = 5FP=3\text{FP} = 38
Actual 1 (passed)FN=2\text{FN} = 2TP=10\text{TP} = 1012
Sum71320

3.2Reading it

  • The diagonal from the top left to the bottom right holds the right predictions: TN and TP. Here 5+10=155 + 10 = 15.
  • The other two cells hold the mistakes: FP and FN. Here 3+2=53 + 2 = 5.
  • 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

  1. Rows are real. The rows are the reality, the columns are the prediction. (In scikit-learn the truth also comes first inside the brackets: confusion_matrix(y_test, predicted).)
  2. Zero comes first. Class 0 is the first row and the first column, as numbers are counted: 0, then 1.
  3. True is on the diagonal. Both "true" cells lie on the diagonal: TN at the top left (0 and 0), TP at the bottom right (1 and 1).
  4. The column gives the second word. Everything in the column "predicted 1" ends with "positive" (FP, TP). Everything in the column "predicted 0" ends with "negative" (TN, FN).
  5. Read it like a text. Line by line, from left to right: TN, FP, FN, TP. This is the order in which scikit-learn gives the four numbers.

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

A confusion matrix in the layout of scikit-learn has the first row 50, 10 and the second row 5, 35. (a) What is TN? (b) What is FP? (c) What is FN? (d) What is TP? (e) How many rows are really positive? (f) How many times did the model say "positive"?

Show a hint
Read it like a text: TN, FP, FN, TP. A row is the truth, a column the prediction.
Show the solution

Answer: (a) 50; (b) 10; (c) 5; (d) 35; (e) 40; (f) 45.

really positive=FN+TP=5+35=40predicted positive=FP+TP=10+35=45\begin{aligned} \text{really positive} &= \text{FN} + \text{TP} \\ &= 5 + 35 = 40 \\[6pt] \text{predicted positive} &= \text{FP} + \text{TP} \\ &= 10 + 35 = 45 \end{aligned}

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:

Type I and Type II
The model saidThe truthAlso called
Type I errorpositivenegativefalse positive, false alarm
Type II errornegativepositivefalse 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

Cases
Task (positive class)Type I error: false positiveType II error: false negative
Medical test (sick)a healthy person is told "sick": worry, more testsa sick person is told "healthy": no treatment
Spam filter (spam)a good e-mail lands in the spam foldera spam e-mail lands in the inbox
Bank, churn (leaves)a loyal customer gets a call or an offer he did not needa customer leaves and nobody tried to keep him
Bank, fraud (fraud)an honest payment is blockeda fraud goes through
Fire alarm (fire)the alarm rings without a firethere is a fire and the alarm is silent
Court (guilty)an innocent person is convicteda 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

Which type of error is it? (a) A fire alarm rings, and there is no fire. (b) A fraud passes the check of the bank unnoticed. (c) A spam filter puts a letter from your teacher into the spam folder. (d) A model says "stays" for a customer who leaves.

Show a hint
A false alarm is a Type I error. A miss is a Type II error.
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: TP=10\text{TP} = 10, TN=5\text{TN} = 5, FP=3\text{FP} = 3, FN=2\text{FN} = 2.

5.1Accuracy

The share of all predictions that are right:

accuracy=TP+TNTP+TN+FP+FN=10+520=1520=0.75\begin{aligned} \text{accuracy} &= \frac{\text{TP} + \text{TN}}{\text{TP} + \text{TN} + \text{FP} + \text{FN}} \\[8pt] &= \frac{10 + 5}{20} = \frac{15}{20} = 0.75 \end{aligned}

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?

precision=TPTP+FP=1010+3=1013=0.769\begin{aligned} \text{precision} &= \frac{\text{TP}}{\text{TP} + \text{FP}} \\[8pt] &= \frac{10}{10 + 3} = \frac{10}{13} = 0.769 \end{aligned}

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?

recall=TPTP+FN=1010+2=1012=0.833\begin{aligned} \text{recall} &= \frac{\text{TP}}{\text{TP} + \text{FN}} \\[8pt] &= \frac{10}{10 + 2} = \frac{10}{12} = 0.833 \end{aligned}

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?

specificity=TNTN+FP=55+3=58=0.625\begin{aligned} \text{specificity} &= \frac{\text{TN}}{\text{TN} + \text{FP}} \\[8pt] &= \frac{5}{5 + 3} = \frac{5}{8} = 0.625 \end{aligned}

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

Where each measure lives in the matrix of the 20 students. The coloured cells are the ones a measure uses, the grey cells are ignored. Precision is a column, recall and specificity are rows, and the accuracy uses everything.
  • 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:

F1=2×precision×recallprecision+recall=2×0.769×0.8330.769+0.833=1.2811.602=0.800\begin{aligned} F_1 &= \frac{2 \times \text{precision} \times \text{recall}}{\text{precision} + \text{recall}} \\[8pt] &= \frac{2 \times 0.769 \times 0.833}{0.769 + 0.833} \\[8pt] &= \frac{1.281}{1.602} = 0.800 \end{aligned}

The same number comes directly from the counts:

F1=2×TP2×TP+FP+FN=2×102×10+3+2=2025=0.8\begin{aligned} F_1 &= \frac{2 \times \text{TP}}{2 \times \text{TP} + \text{FP} + \text{FN}} \\[8pt] &= \frac{2 \times 10}{2 \times 10 + 3 + 2} = \frac{20}{25} = 0.8 \end{aligned}

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.

ordinary mean=1.0+0.12=0.55F1=2×1.0×0.11.0+0.1=0.21.1=0.182\begin{aligned} \text{ordinary mean} &= \frac{1.0 + 0.1}{2} = 0.55 \\[8pt] F_1 &= \frac{2 \times 1.0 \times 0.1}{1.0 + 0.1} = \frac{0.2}{1.1} = 0.182 \end{aligned}

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:

balanced accuracy=recall+specificity2=0.833+0.6252=1.4582=0.729\begin{aligned} & \text{balanced accuracy} \\[4pt] &= \frac{\text{recall} + \text{specificity}}{2} \\[8pt] &= \frac{0.833 + 0.625}{2} = \frac{1.458}{2} = 0.729 \end{aligned}

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

All measures of the example
MeasureFormulaThe class of 20 students
AccuracyTP+TNall\frac{\text{TP} + \text{TN}}{\text{all}}1520=0.75\frac{15}{20} = 0.75
PrecisionTPTP+FP\frac{\text{TP}}{\text{TP} + \text{FP}}1013=0.769\frac{10}{13} = 0.769
Recall (sensitivity)TPTP+FN\frac{\text{TP}}{\text{TP} + \text{FN}}1012=0.833\frac{10}{12} = 0.833
SpecificityTNTN+FP\frac{\text{TN}}{\text{TN} + \text{FP}}58=0.625\frac{5}{8} = 0.625
F1-score2×TP2×TP+FP+FN\frac{2 \times \text{TP}}{2 \times \text{TP} + \text{FP} + \text{FN}}2025=0.8\frac{20}{25} = 0.8
Balanced accuracyrecall+specificity2\frac{\text{recall} + \text{specificity}}{2}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

A model gives TP=8\text{TP} = 8, FP=2\text{FP} = 2, FN=8\text{FN} = 8 and TN=82\text{TN} = 82. Calculate (a) the accuracy, (b) the precision, (c) the recall, (d) the F1-score with 3 decimals.

Show a hint
Precision divides by TP+FP\text{TP} + \text{FP}, recall by TP+FN\text{TP} + \text{FN}. For the F1-score use 2×TP2×TP+FP+FN\frac{2 \times \text{TP}}{2 \times \text{TP} + \text{FP} + \text{FN}}.
Show the solution

Answer: (a) 0.9; (b) 0.8; (c) 0.5; (d) 0.615.

accuracy=8+82100=0.9precision=88+2=0.8recall=88+8=0.5F1=2×82×8+2+8=1626=0.615\begin{aligned} \text{accuracy} &= \frac{8 + 82}{100} = 0.9 \\[6pt] \text{precision} &= \frac{8}{8 + 2} = 0.8 \\[6pt] \text{recall} &= \frac{8}{8 + 8} = 0.5 \\[6pt] F_1 &= \frac{2 \times 8}{2 \times 8 + 2 + 8} = \frac{16}{26} = 0.615 \end{aligned}

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

Other tasks
TaskThe expensive mistakeWatch
Spam filtera good e-mail in the spam folder (false positive)precision
Court, "guilty"an innocent person convicted (false positive)precision
Fire or gas alarma fire without an alarm (false negative)recall
Search for a rare defect in a factorya broken part that is delivered (false negative)recall
Recommending a filma recommendation the viewer dislikes (false positive)precision
Classes of equal size, mistakes of equal costnone in particularaccuracy

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

Summary of the choice
SituationMeasure
A miss is expensive (banking, screening, alarms)recall
A false alarm is expensive (spam, a confirming test, court)precision
Both matter, one number wantedF1-score
Unbalanced classesbalanced accuracy, F1-score
Balanced classes, equal costsaccuracy
Comparing models without fixing a thresholdROC-AUC (Part 9)

Which measure comes first: precision or recall?

1 of 8

A first test for a dangerous disease.

Try it yourself

Which measure should be watched first? (a) A bank looks for fraud among its payments. (b) A spam filter. (c) A first test for a dangerous disease. (d) 98 percent of the rows belong to one class, and one number is wanted in the place of the accuracy.

Show a hint
Which mistake is the expensive one: the miss or the false alarm? And what does a model get that always answers with the large class?
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.

Download

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

Python
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

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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.

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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

Python, continues from the cells above
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

This task continues from the cells above. Print how many test customers the model marks as leaving, then how many test customers really left.
Show a hint
A column of 0 and 1 is counted with its sum: print(predicted.sum()) and print(y_test.sum()). The model marks far fewer customers than really left.
Show the solution
Python, continues from the cells above
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

Python, continues from the cells above
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.

The confusion matrix
Predicted 0 (stays)Predicted 1 (leaves)
Actual 0 (stayed)TN=1543\text{TN} = 1543FP=64\text{FP} = 64
Actual 1 (left)FN=250\text{FN} = 250TP=143\text{TP} = 143
  • 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:

Python, continues from the cells above
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

Python, continues from the cells above
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()
Chart: Confusion matrix of the model

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:

Python, continues from the cells above
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

Python, continues from the cells above
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.

Python, continues from the cells above
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

Python, continues from the cells above
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      2000

How 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.
  • support is the number of test rows of each class: 1,607 and 393.
  • macro avg is the plain mean of the two lines. The macro average of the recall, 0.66, is the balanced accuracy.
  • weighted avg is 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?

Python, continues from the cells above
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 00\frac{0}{0}.)

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:

Python, continues from the cells above
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.

Python, continues from the cells above
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
The balanced model, judged again
MeasureThe first modelThe balanced model
Accuracy0.8430.7655
Precision0.69080.4441
Recall0.36390.7684
F1-score0.47670.5629
Balanced accuracy0.6620.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 two models of the lesson, measure by measure. The first model wins on the accuracy and the precision. The balanced model finds more than twice as many of the customers who leave, and it wins on the recall, the F1-score and the balanced accuracy.

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:

Python, continues from the cells above
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.
00.510.10.30.50.70.9
  • precision
  • recall
Precision and recall of the same model for every threshold from 0.05 to 0.95. As the threshold rises, the precision climbs and the recall falls. The dashed line is the threshold 0.5 that predict uses. The AUC of the model, 0.837, belongs to all thresholds at once.

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

This task continues from the cells above. Print the F1-score calculated from the counts tp, fp and fn, then the F1-score with f1_score, each rounded to 4 decimals.
Show a hint
From the counts: 2 * tp / (2 * tp + fp + fn). With the function: f1_score(y_test, predicted). The two numbers are the same.
Show the solution
Python, continues from the cells above
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

This task continues from the cells above: 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
Python, continues from the cells above
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:

Two rates
RateFormulaIn words
true positive rate (TPR)TPTP+FN\frac{\text{TP}}{\text{TP} + \text{FN}}the recall
false positive rate (FPR)FPFP+TN\frac{\text{FP}}{\text{FP} + \text{TN}}the share of false alarms among the real negatives

The false positive rate is the opposite of the specificity: FPR=1−specificity\text{FPR} = 1 - \text{specificity}. For the class of 20 students:

TPR=1010+2=1012=0.833FPR=33+5=38=0.375\begin{aligned} \text{TPR} &= \frac{10}{10 + 2} = \frac{10}{12} = 0.833 \\[8pt] \text{FPR} &= \frac{3}{3 + 5} = \frac{3}{8} = 0.375 \end{aligned}

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

A curve from thresholds, by hand
StudentABCDEFGH
Probability0.90.80.70.60.40.30.20.1
TruthPPNPNPNN

For a threshold, every student with a probability at or above it is predicted "passes". Three thresholds:

A curve from thresholds, by hand
ThresholdPredicted "passes"TPFPTPR=TP4\text{TPR} = \frac{\text{TP}}{4}FPR=FP4\text{FPR} = \frac{\text{FP}}{4}
0.75A, B200.50
0.5A, B, C, D310.750.25
0.25A to F4210.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.

000.250.250.50.50.750.7511threshold 0.75threshold 0.5threshold 0.25false positive ratetrue positive rate (recall)
The ROC curve of the eight students. Every threshold is one point; three of them are marked. The square is cut into 16 small squares, and 13 of them lie under the curve: the AUC is 13 of 16, 0.8125. The dashed diagonal is a model that guesses.

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:

AUC=1316=0.8125\text{AUC} = \frac{13}{16} = 0.8125

The AUC has a simple meaning. Take one student who passed and one who failed, at random. The AUC is the probability that the model gave the higher number to the one who passed. It can be counted directly. There are 4×4=164 \times 4 = 16 pairs of one P and one N:

The area under the curve: AUC
Student who passedIs abovePairs
A (0.9)all 4 students who failed4
B (0.8)all 44
D (0.6)E, G and H, but below C3
F (0.3)G and H only2
AUC=4+4+3+216=1316=0.8125\text{AUC} = \frac{4 + 4 + 3 + 2}{16} = \frac{13}{16} = 0.8125

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

000.250.250.50.50.750.7511false positive ratetrue positive rate (recall)
  • perfect: AUC 1
  • good: AUC 0.8
  • weak: AUC 0.6
  • guessing: AUC 0.5
Four ROC curves. The perfect model goes straight up to the top left corner and then to the right: AUC 1. A good model bends towards that corner: AUC 0.8. A weak one stays close to the diagonal: AUC 0.6. The diagonal itself is guessing: AUC 0.5. The closer to the top left corner, the better.
  • 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. TPR=FPR\text{TPR} = \text{FPR} 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 TPR=1\text{TPR} = 1 and FPR=0\text{FPR} = 0, 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):

Which curve is better, and why
AUCReading
0.5no better than guessing
0.6 to 0.7weak
0.7 to 0.8fair
0.8 to 0.9good
above 0.9very 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:

Python, continues from the cells above
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:

Python, continues from the cells above
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()
Chart: Five points of the ROC curve

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.

Python, continues from the cells above
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()
Chart: ROC curve

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.

000.250.250.50.50.750.7511false positive ratetrue positive rate (recall)

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

Python, continues from the cells above
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.

Python, continues from the cells above
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.

Python, continues from the cells above
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()
Chart: Two models, two ROC curves

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?

Python, continues from the cells above
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:

Gini=2×AUC−1\text{Gini} = 2 \times \text{AUC} - 1
The Gini coefficient
AUCGini
Guessing0.50
Perfect model11

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:

Gini=2×0.8125−1=1.625−1=0.625\text{Gini} = 2 \times 0.8125 - 1 = 1.625 - 1 = 0.625

For the bank model:

Python, continues from the cells above
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

A model gave seven customers a probability of leaving. Two left (P): 0.9 and 0.5. Five stayed (N): 0.7, 0.4, 0.3, 0.2 and 0.1. (a) What is the TPR for the threshold 0.6? (b) What is the FPR for the threshold 0.6? (c) What is the AUC? Count the pairs. (d) What is the Gini coefficient?

Show a hint
At or above 0.6 are 0.9 (P) and 0.7 (N). There are 2×5=102 \times 5 = 10 pairs of one P and one N.
Show the solution

Answer: (a) 0.5; (b) 0.2; (c) 0.9; (d) 0.8.

TPR=12=0.5FPR=15=0.2AUC=5+410=0.9Gini=2×0.9−1=0.8\begin{aligned} \text{TPR} &= \frac{1}{2} = 0.5 \qquad \text{FPR} = \frac{1}{5} = 0.2 \\[6pt] \text{AUC} &= \frac{5 + 4}{10} = 0.9 \\[6pt] \text{Gini} &= 2 \times 0.9 - 1 = 0.8 \end{aligned}

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

This task continues from the cells above: 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
Python, continues from the cells above
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

The workflow, step by step
StepWhat is doneIn this project
1. Look and checkshape, missing values, text columns10,000 customers, nothing missing
2. Dropcolumns without informationcustomer_id
3. Targetthe share of each class20 percent left: unbalanced
4. Encodetext and unordered numbersgender, country, products_number
5. Splittraining and test data8,000 and 2,000
6. Scalefit on the training dataStandardScaler
7. Trainthe modelLogisticRegression
8. Confusion matrixthe four counts1543, 64, 250, 143
9. Choose the measurewhich mistake costs more?a miss: recall
10. Measuresprecision, recall, F1, balanced accuracy0.69, 0.36, 0.48, 0.66
11. Threshold or class weightsmove along the curverecall 0.77 with balanced classes
12. ROC-AUC and Ginithe model at all thresholds0.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

(a) What does 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
The ROC curve is made of many thresholds. Whatever is chosen with the test data makes the test data part of the model.
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

Common mistakes
MistakeWhy it is wrongRight
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.

Solved problems
CountCalculationIn words
TP\text{TP}30marked as spam, and spam
FP\text{FP}40−30=1040 - 30 = 10marked as spam, but good
FN\text{FN}50−30=2050 - 30 = 20spam that was not marked
TN\text{TN}200−30−10−20=140200 - 30 - 10 - 20 = 140good, and not marked
Solved problems
Predicted 0 (good)Predicted 1 (spam)
Actual 0 (good)TN=140\text{TN} = 140FP=10\text{FP} = 10
Actual 1 (spam)FN=20\text{FN} = 20TP=30\text{TP} = 30

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 (TP=30\text{TP} = 30, FP=10\text{FP} = 10, FN=20\text{FN} = 20, TN=140\text{TN} = 140), calculate the accuracy, the precision, the recall and the F1-score.

Idea. Every measure is a fraction of the four counts (Part 5).

accuracy=30+140200=170200=0.85precision=3030+10=3040=0.75recall=3030+20=3050=0.6F1=2×0.75×0.60.75+0.6=0.91.35=0.667\begin{aligned} \text{accuracy} &= \frac{30 + 140}{200} = \frac{170}{200} = 0.85 \\[6pt] \text{precision} &= \frac{30}{30 + 10} = \frac{30}{40} = 0.75 \\[6pt] \text{recall} &= \frac{30}{30 + 20} = \frac{30}{50} = 0.6 \\[6pt] F_1 &= \frac{2 \times 0.75 \times 0.6}{0.75 + 0.6} = \frac{0.9}{1.35} = 0.667 \end{aligned}

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

TP=0FN=10FP=0TN=990\text{TP} = 0 \qquad \text{FN} = 10 \qquad \text{FP} = 0 \qquad \text{TN} = 990
accuracy=0+9901000=0.99recall=00+10=0specificity=990990+0=1balanced accuracy=0+12=0.5\begin{aligned} \text{accuracy} &= \frac{0 + 990}{1000} = 0.99 \\[6pt] \text{recall} &= \frac{0}{0 + 10} = 0 \\[6pt] \text{specificity} &= \frac{990}{990 + 0} = 1 \\[6pt] \text{balanced accuracy} &= \frac{0 + 1}{2} = 0.5 \end{aligned}

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 TP=2\text{TP} = 2 and FP=1\text{FP} = 1.

TPR=23=0.667FPR=13=0.333\text{TPR} = \frac{2}{3} = 0.667 \qquad \text{FPR} = \frac{1}{3} = 0.333

(b) There are 3×3=93 \times 3 = 9 pairs. 0.9 is above 0.6, 0.3 and 0.2: 3 pairs. 0.7 is above 0.6, 0.3 and 0.2: 3 pairs. 0.4 is above 0.3 and 0.2: 2 pairs.

AUC=3+3+29=89=0.889\text{AUC} = \frac{3 + 3 + 2}{9} = \frac{8}{9} = 0.889

(c) The Gini coefficient:

Gini=2×0.889−1=1.778−1=0.778\text{Gini} = 2 \times 0.889 - 1 = 1.778 - 1 = 0.778

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

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

Python, continues from the cells above
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).

Python, continues from the cells above
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).

Python, continues from the cells above
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).

Python, continues from the cells above
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; recall=TPTP+FN\text{recall} = \frac{\text{TP}}{\text{TP} + \text{FN}} (Parts 5 and 8).

Python, continues from the cells above
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).

Python, continues from the cells above
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).

Python, continues from the cells above
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).

Python, continues from the cells above
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).

Python, continues from the cells above
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; Gini=2×AUC−1\text{Gini} = 2 \times \text{AUC} - 1 (Part 9).

Python, continues from the cells above
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).

Python, continues from the cells above
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()
Chart: ROC curve

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. 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: TP=30\text{TP} = 30, FP=20\text{FP} = 20, FN=10\text{FN} = 10, TN=940\text{TN} = 940.

    TP=30FP=50−30=20FN=40−30=10TN=1000−30−20−10=940\begin{aligned} \text{TP} &= 30 \\[4pt] \text{FP} &= 50 - 30 = 20 \\[4pt] \text{FN} &= 40 - 30 = 10 \\[4pt] \text{TN} &= 1000 - 30 - 20 - 10 = 940 \end{aligned}

    The 50 marked payments are the column "predicted 1", the 40 frauds are the row "actual 1".

  2. 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: 2×precision×recallprecision+recall\frac{2 \times \text{precision} \times \text{recall}}{\text{precision} + \text{recall}}.
    Show one possible solution

    Answer: (a) 0.97; (b) 0.6; (c) 0.75; (d) 0.667.

    accuracy=30+9401000=0.97precision=3050=0.6recall=3040=0.75F1=2×0.6×0.750.6+0.75=0.91.35=0.667\begin{aligned} \text{accuracy} &= \frac{30 + 940}{1000} = 0.97 \\[6pt] \text{precision} &= \frac{30}{50} = 0.6 \\[6pt] \text{recall} &= \frac{30}{40} = 0.75 \\[6pt] F_1 &= \frac{2 \times 0.6 \times 0.75}{0.6 + 0.75} = \frac{0.9}{1.35} = 0.667 \end{aligned}

    The accuracy of 0.97 says little here: answering "no fraud" for every payment would give 0.96.

  3. 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. 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 3×4=123 \times 4 = 12 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.

    TPR=23=0.667FPR=14=0.25\text{TPR} = \frac{2}{3} = 0.667 \qquad \text{FPR} = \frac{1}{4} = 0.25

    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.

    AUC=4+3+212=912=0.75Gini=2×0.75−1=0.5\begin{aligned} \text{AUC} &= \frac{4 + 3 + 2}{12} = \frac{9}{12} = 0.75 \\[6pt] \text{Gini} &= 2 \times 0.75 - 1 = 0.5 \end{aligned}

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.

  1. 5.Read Bank Customer Churn Prediction.csv into df. Print the shape, then the number of customers who left.
    Show a hint
    df = pd.read_csv("Bank Customer Churn Prediction.csv"), then print(df.shape) and print(df["churn"].sum()).
    Show one possible solution
    Python
    import pandas as pd
    
    df = pd.read_csv("Bank Customer Churn Prediction.csv")
    
    print(df.shape)
    print(df["churn"].sum())

    Output

    (10000, 12)
    2037
  2. 6.Drop the column customer_id and encode gender as 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"]) and df["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 above
    df = df.drop(columns=["customer_id"])
    df["gender"] = df["gender"].map({"Female": 0, "Male": 1})
    
    print((df["gender"] == 0).sum())

    Output

    4543
  3. 7.One-hot encode country and products_number inside the table, with drop_first=True and dtype=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), then print(len(df.columns)).
    Show one possible solution
    Python, continues from the cells above
    df = pd.get_dummies(df, columns=["country", "products_number"], drop_first=True, dtype=int)
    
    print(len(df.columns))

    Output

    14
  4. 8.Make X (all columns without churn) and y (churn). Split them with test_size=0.3 and random_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"], then X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1). Print len(y_test) and y_test.sum().
    Show one possible solution
    Python, continues from the cells above
    from sklearn.model_selection import train_test_split
    
    X = df.drop(columns=["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
  5. 9.Scale the features with a StandardScaler called scaler into X_train_scaled and X_test_scaled. Print the shape of X_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), then print(X_test_scaled.shape).
    Show one possible solution
    Python, continues from the cells above
    from 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)
  6. 10.Train a LogisticRegression called model and put its predictions for the test customers into predicted. 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). Then print(round(model.score(X_test_scaled, y_test), 4)) and print(predicted.sum()).
    Show one possible solution
    Python, continues from the cells above
    from 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.

  1. 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 above
    from sklearn.metrics import confusion_matrix
    
    print(confusion_matrix(y_test, predicted))

    Output

    [[2292   81]
     [ 399  228]]
  2. 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 are fn, the false alarms are fp.
    Show one possible solution
    Python, continues from the cells above
    tn, fp, fn, tp = confusion_matrix(y_test, predicted).ravel()
    
    print(fn)
    print(fp)

    Output

    399
    81
  3. 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 with recall_score and f1_score.
    Show one possible solution
    Python, continues from the cells above
    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.7379
    0.3636
    0.4872
  4. 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 is tn / (tn + fp). Then print(round(balanced_accuracy_score(y_test, predicted), 4)).
    Show one possible solution
    Python, continues from the cells above
    from 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.

  1. 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], then marked = (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 above
    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.5607
    0.6045
  2. 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), then print(round(auc, 4)) and print(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="--") and plt.show().
    Show one possible solution
    Python, continues from the cells above
    import 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
    Chart: ROC curve

14Check yourself

Twelve questions. Every question has one right answer.

Question 1

1.A model says "leaves" for a customer who stays. What is this?

Question 2

2.In the confusion matrix of scikit-learn, what do the rows show?

Question 3

3.TP=40\text{TP} = 40, FP=10\text{FP} = 10, FN=40\text{FN} = 40, TN=110\text{TN} = 110. What is the precision?

Question 4

4.Which measure answers "of all the positives, how many did the model find?"

Question 5

5.Which is a Type II error?

Question 6

6.In a data set 95 percent of the rows are negative. A model answers "negative" for every row. What are its accuracy and its recall?

Question 7

7.A model has a precision of 1.0 and a recall of 0.1. What is its F1-score, about?

Question 8

8.A hospital uses a first test for a dangerous disease. Which measure matters most?

Question 9

9.The threshold is lowered from 0.5 to 0.3. What usually happens?

Question 10

10.What are the two axes of the ROC curve?

Question 11

11.Which ROC curve belongs to the better model?

Question 12

12.A model has an AUC of 0.85. What is its Gini coefficient?

0 of 12 answered.

15Summary

Summary
Predicted 0Predicted 1
Actual 0TNFP (Type I error)
Actual 1FN (Type II error)TP
Summary
MeasureFormulaQuestion it answers
AccuracyTP+TNall\frac{\text{TP} + \text{TN}}{\text{all}}how often is the model right?
PrecisionTPTP+FP\frac{\text{TP}}{\text{TP} + \text{FP}}can a positive answer be trusted?
Recall (sensitivity, TPR)TPTP+FN\frac{\text{TP}}{\text{TP} + \text{FN}}how many positives are found?
SpecificityTNTN+FP\frac{\text{TN}}{\text{TN} + \text{FP}}how many negatives are recognised?
F1-score2×precision×recallprecision+recall\frac{2 \times \text{precision} \times \text{recall}}{\text{precision} + \text{recall}}precision and recall in one number
Balanced accuracyrecall+specificity2\frac{\text{recall} + \text{specificity}}{2}the accuracy with equal weight for both classes
False positive rateFPFP+TN\frac{\text{FP}}{\text{FP} + \text{TN}}the share of false alarms among the negatives
AUCthe area under the ROC curvehow well are positives put above negatives?
Gini2×AUC−12 \times \text{AUC} - 1the AUC on a scale from 0 to 1
Summary
CodeWhat 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_scorethe 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

  1. A classifier can be wrong in two ways. Look at the confusion matrix before any single number.
  2. The second word of TP, TN, FP, FN is what the model said; the first word says whether it was right.
  3. Precision divides by what was predicted positive, recall by what is really positive.
  4. Ask which mistake costs more. A miss: recall. A false alarm: precision. Both: F1.
  5. With unbalanced classes the accuracy misleads. Use the balanced accuracy or the F1-score.
  6. The threshold trades precision for recall. The ROC curve shows the model at all thresholds, and the AUC is its area.
  7. The closer the curve comes to the top left corner, the better. Gini=2×AUC−1\text{Gini} = 2 \times \text{AUC} - 1.

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.