Module 3, topic 27, week 14, Tuesday
Logistic Regression
The first model for classification: where its formula comes from, the sigmoid and the softmax, the cross-entropy loss, its parameters, and a complete project on a real data file of bank customers, from reading the file to a tuned model.
Lesson notebook
The lesson as a Jupyter notebook: the explanations, the whole project on the bank data cell by cell, and the sixteen solved problems.
topic-27-logistic-regression.ipynb, 72 KB
Practice notebook
The same project on the bank data in twelve steps, from reading the file to a tuned model, with a hint and a hidden solution for each step.
topic-27-practice.ipynb, 18 KB
Data file: the bank customers
10,000 customers of a bank with 12 columns: 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: from numbers to classes
The seventh lesson of Module 3. Every model so far predicted a number: a mark, a price. This lesson is about the other large task of supervised learning (Topic 21): predicting a class. Will this customer leave the bank, yes or no? Is this e-mail spam? Is this tumour benign or malignant? The first and most important model for such questions is logistic regression.
The lesson has two halves. The first explains the model: what it is, where its formula comes from, the sigmoid for two classes and the softmax for several, the loss it is trained with, and its parameters. The second half is a complete project on a real data file, Bank Customer Churn Prediction.csv: every step from reading the file to a trained and tuned model, in the order of real work. It repeats everything of Topics 22 to 26.
In this lesson a model is judged with one measure only, the accuracy: the share of right predictions. Topic 28 adds the other measures of classification.
You need: linear regression and gradient descent (Topic 22), the train/test split and cross-validation (Topic 23), scaling (Topic 24), outliers and encoding (Topic 25), regularization (Topic 26), and probability (Topic 16).
What you will learn
- 1.What classification is, and why linear regression does not fit it
- 2.The formula of logistic regression, and where it comes from: odds, log-odds and the sigmoid
- 3.Binary and multi-class classification, the sigmoid and the softmax
- 4.The loss function, cross-entropy, and why it is preferred to the squared error
- 5.The parameters of
LogisticRegressionand what each one does - 6.A whole classification project: look, clean, encode, split, scale, train, tune
- 7.
predict,predict_proba, the threshold, and how to read the weights
| Word | Meaning |
|---|---|
| classification | predicting a class (a category), not a number |
| binary classification | two classes: yes or no, 1 or 0 |
| multi-class classification | three or more classes |
| logistic regression | a linear model that predicts the probability of a class |
| odds | the probability that something happens divided by the probability that it does not |
| log-odds (logit) | the logarithm of the odds |
| sigmoid | the S-shaped function that turns any number into a number between 0 and 1 |
| softmax | the function that turns several scores into probabilities that add up to 1 |
| activation function | the function between the linear score and the output: here the sigmoid or the softmax |
| threshold | the probability from which the model answers "yes": usually 0.5 |
| cross-entropy (log loss) | the loss function of logistic regression |
| accuracy | the share of predictions that are right |
| churn | a customer leaving a company |
1What logistic regression is, and why it is needed
1.1A new kind of question
| Regression | Classification | |
|---|---|---|
| The target is | a number | a class |
| Example | the price of a house | will the customer leave: yes or no |
| Typical model | linear regression | logistic regression |
| Typical measure | , RMSE | accuracy |
Despite its name, logistic regression is a model for classification. The word "regression" is there because, inside, it calculates a number, a probability, and only then turns it into a class.
A model that says "this customer will leave with a probability of 0.83" is worth more than one that only says "leaves". The bank can call the customers with the highest probabilities first. Logistic regression gives exactly this: a probability for every row.
1.2Why not linear regression?
The two classes can be written as numbers, 1 for "yes" and 0 for "no". Then a linear regression could be trained on them. It is tried in the left picture, and it fails for three reasons.
Linear regression
a straight line: below 0 and above 1
Logistic regression
an S-shaped curve between 0 and 1
- A line has no limits. For large it predicts more than 1, for small less than 0. A probability of 1.3 or of does not exist.
- A line changes at the same speed everywhere. In reality the answer is almost certain far from the border between the classes, and it changes quickly near the border. That is the shape of an S, not of a line.
- The squared error fits numbers, not classes. Part 4 comes back to this.
Logistic regression keeps what is good about a linear model, a weighted sum of the features, and bends its result into the range from 0 to 1.
Try it yourself
Show a hint
Show the solution
Answer: (a) regression; (b) classification; (c) regression; (d) classification.
A price and a mark are numbers: regression. "Spam or not" is one of two classes, and a country is one of three: classification. (b) is binary, (d) is multi-class.
2The formula, and where it comes from
2.1Step 1: a linear score
Like linear regression, the model first calculates a weighted sum of the features. It is called the score and written :
can be any number, from very negative to very positive. A large positive shall mean "almost certainly class 1", a large negative "almost certainly class 0". What is needed is a bridge from to a probability.
2.2Step 2: from a probability to the odds
A probability lies between 0 and 1. The odds compare it with its opposite:
| Probability | Odds | In words |
|---|---|---|
| 0.5 | one to one | |
| 0.8 | four to one | |
| 0.9 | nine to one | |
| 0.2 | one to four |
The odds run from 0 to infinity. That is already one limit less.
2.3Step 3: from the odds to the log-odds
The logarithm of the odds, the log-odds or logit, removes the other limit:
| Probability | Odds | Log-odds |
|---|---|---|
| 0.1 | 0.111 | |
| 0.2 | 0.25 | |
| 0.5 | 1 | 0 |
| 0.8 | 4 | 1.386 |
| 0.9 | 9 | 2.197 |
The log-odds run from minus infinity to plus infinity, they are 0 when the probability is 0.5, and they are symmetric: 0.8 and 0.2 give 1.386 and . That is exactly the kind of number a linear score can be.
2.4Step 4: the idea of logistic regression
Logistic regression assumes that the log-odds are a linear function of the features:
That one line is the whole model. Everything else follows by solving it for :
The last step divides the top and the bottom by . The result is the formula of logistic regression:
The function that turns into has a name of its own: the sigmoid.
2.5The sigmoid
By hand, with and :
Read the curve:
- It turns any number into a number between 0 and 1. A score of 100 gives a probability just below 1, a score of one just above 0. The limits are never reached.
- At it gives exactly 0.5.
- It is steep in the middle and flat at the ends: near the border a small change of the score moves the probability a lot; far from the border the model is sure and stays sure.
- It is symmetric: . The values 0.881 and 0.119 above add up to 1.
2.6From a probability to a class: the threshold
The model answers with a class by comparing the probability with a threshold, usually 0.5:
Because exactly when , this is the same as asking whether the score is positive. The points where form the decision boundary: a straight line (with two features), a plane or its higher relative (with more). So logistic regression is a linear classifier: it separates the two classes with a straight border. The S is the shape of the probability, not of the border.
2.7An example by hand
A small model for churn has two features: the age (in decades) and whether the customer is an active member (1 or 0).
A customer of 50 years (age = 5) who is not active:
The probability of leaving is 0.731, above 0.5: the model predicts class 1, "leaves". The same customer as an active member:
Exactly on the border.
2.8What a weight means
In linear regression a weight is "the change of the prediction for one unit of the feature". Here the weight changes the log-odds, and that reads best in odds:
- A weight of adds to the log-odds for every unit of the feature.
- The odds are then multiplied by .
In the example, one decade of age adds 1.0 to the score, so it multiplies the odds of leaving by . Being an active member multiplies them by : it cuts them to about a third.
The simple reading is enough for most work: a positive weight pushes towards class 1, a negative weight towards class 0, and a weight further from 0 pushes harder.
Move the score and watch the probability. Then move the threshold.
p = 1 / (1 + e−1) = 0.731, the odds are 2.718 to 1.
With the threshold 0.5 the model answers class 1.
A score of 0 gives exactly 0.5. Far from 0 the curve is flat: the model is sure, and a little more score changes almost nothing.
Try it yourself
Show a hint
Show the solution
Answer: (a) 1; (b) 0.731; (c) class 1; (d) 3.
(c) The probability 0.731 is above 0.5, so the model predicts class 1.
3Two classes or more: the sigmoid and the softmax
3.1Binary and multi-class
| Binary classification | Multi-class classification | |
|---|---|---|
| Classes | two | three or more |
| Examples | leaves or stays; spam or not; ill or healthy | the country of a customer; the digit in a picture; the species of a flower |
| The model calculates | one score | one score for every class |
| Function at the end | sigmoid | softmax |
| Output | one probability (the other is ) | one probability for every class; together they add up to 1 |
The function that stands between the linear score and the output is called the activation function of the model. The word comes from neural networks (Module 5), where logistic regression returns as the smallest possible network: one layer of weights and an activation function.
3.2The softmax
With three classes the model has three sets of weights and calculates three scores, , , : one for every class. The softmax turns them into three probabilities:
Two things happen. makes every score positive and makes large scores much larger. Dividing by the sum makes the three results add up to 1.
By hand, with the scores 2, 1 and 0 (, , ):
The three probabilities add up to 1, and the class with the highest score has the highest probability. The model answers with that class: class 1.
The three scores
any numbers
After the softmax
probabilities that add up to 1
- The name: it is a soft version of the maximum. A hard maximum would answer 1, 0, 0. The softmax gives most of the probability to the largest score and leaves a little for the others.
- The differences between the scores matter, not the scores themselves: 2, 1, 0 and 12, 11, 10 give the same probabilities.
- With two classes the softmax is the sigmoid. The two functions are one idea: the sigmoid is the short form for the case of two classes.
3.3Side by side
| Sigmoid | Softmax | |
|---|---|---|
| Used for | two classes | three or more classes |
| Input | one score | one score for every class |
| Output | one probability between 0 and 1 | probabilities that add up to 1 |
| Formula | ||
| Decision | class 1 if | the class with the largest probability |
In scikit-learn you do not choose between them: LogisticRegression looks at the target and uses the right one. Part 10 shows it on the bank data.
Three scores, one for every class. Move them and watch the three probabilities.
The probabilities are 0.665, 0.245, 0.090. They add up to 1, and the model answers class 1.
Add the same amount to all three scores and nothing changes: only the differences between the scores matter.
Sigmoid or softmax?
1 of 8
Will the customer leave the bank: yes or no?
Try it yourself
Show a hint
Show the solution
Answer: (a) 0.333; (b) 1; (c) the softmax.
Only the differences between the scores matter, and here there are none. With ten classes the model has ten scores, and the softmax turns them into ten probabilities that add up to 1.
4The loss function: cross-entropy
4.1What the training needs
Training means finding the weights that make a loss as small as possible (Topic 22). For linear regression the loss was the mean squared error. A classifier predicts a probability , and the true answer is 1 or 0. A good loss must be small when the model gives a high probability to the true class, and large when it does not.
4.2The formula
For one row the cross-entropy, also called log loss, is:
In both cases it is minus the logarithm of the probability that the model gave to the true class. The two lines are usually written as one formula:
With the second part disappears, with the first. The loss of the model is the mean over all rows.
4.3By hand
Four customers who really left (), and the probability of leaving that the model gave each of them:
| The model said | Loss | Reading |
|---|---|---|
| sure and right: almost no loss | ||
| right: a small loss | ||
| right, but unsure: a medium loss | ||
| wrong: a large loss | ||
| sure and wrong: a very large loss |
- the true class is 1: the loss is −ln(p)
- the true class is 0: the loss is −ln(1 − p)
The loss is 0 for a perfect prediction and grows without limit as the model becomes sure of the wrong answer.
4.4Why this loss, and not the squared error?
1. It punishes a confident mistake properly. Compare the two losses for a customer who left ():
| The model said | Squared error | Cross-entropy |
|---|---|---|
| 0.01 | 0.105 | |
| 0.25 | 0.693 | |
| 0.81 | 2.303 | |
| 0.98 | 4.605 |
For the squared error, saying 0.1 and saying 0.01 are almost the same mistake: 0.81 and 0.98. It can never be larger than 1. For the cross-entropy the second mistake costs twice as much, and a model that says "0.000001" for something that happens pays a huge price. A model trained with it learns not to be sure without a reason.
2. It has one valley. With the sigmoid inside, the squared error becomes a loss with flat regions and several dips, and gradient descent (Topic 22) can get stuck. The cross-entropy of a logistic regression is a single smooth bowl: wherever the walk starts, it reaches the same lowest point.
3. It keeps learning when the model is badly wrong. Where the sigmoid is flat, the squared error gives almost no slope, so a very wrong model would learn very slowly. With the cross-entropy the slope is simply the error, : the worse the prediction, the larger the step.
4. It is the loss that belongs to probabilities. Minimising the cross-entropy is the same as choosing the weights under which the observed data is most probable. This principle is called maximum likelihood.
4.5Why not the accuracy as a loss?
The accuracy only counts right and wrong. If a weight changes a little, usually no prediction flips, and the accuracy does not move at all: there is no slope to walk down. The cross-entropy changes with every small change of every probability. So the model is trained with the cross-entropy and judged with the accuracy.
4.6More than two classes
The idea stays the same: the loss of a row is minus the logarithm of the probability that the model gave to the true class.
In the softmax example of Part 3 the probabilities were 0.665, 0.245 and 0.090. If the true class is class 1, the loss is . If it is class 3, the loss is .
Choose what really happened and move the probability of leaving that the model gave.
Cross-entropy: −ln(0.8) = 0.223. Squared error: 0.040.
The probability given to the true class is 0.8. Move it towards 0: the cross-entropy grows without limit, and the squared error stops below 1.
Try it yourself
Show a hint
Show the solution
Answer: (a) 0.693; (b) ; (c) the cross-entropy; (d) the accuracy.
The customer left, so the true class is 1. A probability of 0.2 for it is further from the truth than 0.7, and costs more. The model is trained with the cross-entropy, which changes with every small change of a probability, and judged with the accuracy, which is easy to read.
5The parameters of LogisticRegression
A model has two kinds of numbers (Topic 21). The weights are learned by fit. The hyperparameters are set by you when the model is created. LogisticRegression() works without any of them, but each one has a job.
| Parameter | Default | What it does |
|---|---|---|
C | 1.0 | the strength of the regularization, turned round: a small C is a strong penalty |
l1_ratio | 0 | the kind of penalty: 0 is L2 (as Ridge), 1 is L1 (as Lasso), between them an elastic net |
solver | "lbfgs" | the method that searches for the weights |
max_iter | 100 | the largest number of steps the solver may take |
class_weight | None | "balanced" gives the rare class more weight in the loss |
random_state | None | fixes the randomness of the solvers that use it |
5.1C: regularization against overfitting
This is the most important one. Logistic regression is regularized by default: its loss is the cross-entropy plus a penalty for large weights, exactly as in Topic 26. The strength is set with C, and C works the other way round than alpha:
- A small
C(0.01) is a strong penalty: small weights, a simpler model, less overfitting, and with too small a value underfitting. - A large
C(100) is a weak penalty: the model is almost free.
C is chosen like alpha: with cross-validation on the training data.
5.2l1_ratio: which penalty
With l1_ratio=0, the default, the penalty is L2: all weights become smaller. With l1_ratio=1 it is L1: some weights become exactly 0, and the model selects features. Values between 0 and 1 give an elastic net. (Older code and many books set this with another parameter, penalty="l1" or penalty="l2". It still works in current versions and gives a warning.)
Because the penalty looks at the size of the weights, the features must be scaled, as in Topic 26.
5.3solver and max_iter: how the weights are found
There is no direct formula for the best weights of a logistic regression, as there was for linear regression. They are found step by step, by a relative of gradient descent. The solver is the method, and max_iter is the limit of its steps.
| Solver | Good for |
|---|---|
"lbfgs" | the default: fast and reliable; L2 penalty only |
"liblinear" | small data sets; supports the L1 penalty |
"saga" | large data sets; supports L1, L2 and the elastic net |
If the solver reaches max_iter before it has found the lowest point, scikit-learn prints a ConvergenceWarning. The two usual cures: scale the features (unscaled features make the valley long and narrow, as in Topic 24), or raise max_iter.
5.4class_weight: when one class is rare
If 80 percent of the customers stay, a model can reach a high accuracy by mostly answering "stays". With class_weight="balanced" every mistake on the rare class counts more in the loss, so the model pays more attention to it. It then finds more of the customers who leave, usually at the price of a lower accuracy. Part 8 shows it, and Topics 28 and 41 explain when that trade is worth it.
5.5What is learned, not set
After fit the model holds the learned numbers, with an underscore at the end (Topic 21):
| Attribute | Meaning |
|---|---|
model.coef_ | the weights, one for every feature |
model.intercept_ | the intercept |
model.classes_ | the classes, in the order of the columns of predict_proba |
model.n_iter_ | the number of steps the solver needed |
Try it yourself
C is the stronger regularization: 0.01 or 100? (b) Which parameter gives a rare class more weight? (c) The solver prints a ConvergenceWarning. What is the best first cure? (d) Which parameter makes the penalty an L1 penalty?Show a hint
C is turned round. Unscaled features make the loss a long, narrow valley.Show the solution
Answer: (a) 0.01; (b) class_weight; (c) scale the features; (d) l1_ratio.
A small C is a strong penalty, because . class_weight="balanced" makes mistakes on the rare class count more. A solver that does not finish usually walks on unscaled features: scaling removes the cause. l1_ratio=1 gives the L1 penalty, with a solver that supports it.
6The project: the data and its preparation
From here on the lesson is one project, in the order of real work: look at the data, clean it, encode it, split it, scale it, train a first model, then improve it. Every code block is a cell that continues from the cells above it, like a notebook.
The task: predict whether a customer of a bank will leave.
6.1Step 1: read the file and look at it
Bank Customer Churn Prediction.csv is a public data set of 10,000 customers of a bank.
import pandas as pd
df = pd.read_csv("Bank Customer Churn Prediction.csv")
print(df.shape)
print(df.head(3).T)Output
(10000, 12)
0 1 2
customer_id 15634602 15647311 15619304
credit_score 619 608 502
country France Spain France
gender Female Female Female
age 42 41 42
tenure 2 1 8
balance 0.0 83807.86 159660.8
products_number 1 1 3
credit_card 1 0 1
active_member 1 1 0
estimated_salary 101348.88 112542.58 113931.57
churn 1 0 1| Column | Meaning |
|---|---|
customer_id | the identification number of the customer |
credit_score | the credit score: how reliable the customer is with money |
country | France, Germany or Spain |
gender | Female or Male |
age | the age in years |
tenure | for how many years the customer has been with the bank |
balance | the money in the account |
products_number | how many products of the bank the customer uses |
credit_card | has a credit card: 1 or 0 |
active_member | is an active member: 1 or 0 |
estimated_salary | the estimated salary |
churn | the target: 1 if the customer left the bank, 0 if not |
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 ...
6.2Step 2: check the columns
Missing values, repeated rows, and the columns that are text (Topic 11):
print(df.isna().sum().sum())
print(df.duplicated().sum())
print(df.select_dtypes(exclude="number").columns.tolist())Output
0 0 ['country', 'gender']
Nothing is missing and nothing is repeated. Two columns are text and must be encoded.
6.3Step 3: drop the columns without information
print(df.nunique())Output
customer_id 10000 credit_score 460 country 3 gender 2 age 70 tenure 11 balance 6382 products_number 4 credit_card 2 active_member 2 estimated_salary 9999 churn 2 dtype: int64
customer_id has 10,000 values in 10,000 rows: an identification number (Topic 24). It names a customer and says nothing about him or her, so it is dropped.
df = df.drop(columns=["customer_id"])
print(df.shape)Output
(10000, 11)
6.4Step 4: look at the target
In a classification project the target deserves a look of its own: how many rows does each class have?
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. The mean of a column of 0 and 1 is the share of the ones: 20.37 percent left, and about 80 percent stayed. The two classes are not balanced.
Keep this number in mind. A "model" that answers "stays" for every customer, without looking at anything, would be right in about 80 percent of the cases. That is the baseline: a real model has to beat it.
6.5Step 5: look for outliers
The columns with continuous measurements (Topic 25):
print(df[["credit_score", "age", "balance", "estimated_salary"]].describe().round(0))Output
credit_score age balance estimated_salary count 10000.0 10000.0 10000.0 10000.0 mean 651.0 39.0 76486.0 100090.0 std 97.0 10.0 62397.0 57510.0 min 350.0 18.0 0.0 12.0 25% 584.0 32.0 0.0 51002.0 50% 652.0 37.0 97199.0 100194.0 75% 718.0 44.0 127644.0 149388.0 max 850.0 92.0 250898.0 199992.0
The IQR rule on each of them:
for name in ["credit_score", "age", "balance", "estimated_salary"]:
q1 = df[name].quantile(0.25)
q3 = df[name].quantile(0.75)
low = q1 - 1.5 * (q3 - q1)
high = q3 + 1.5 * (q3 - q1)
print(name, low, high, ((df[name] < low) | (df[name] > high)).sum())Output
credit_score 383.0 919.0 15 age 14.0 62.0 359 balance -191466.36000000002 319110.60000000003 0 estimated_salary -96577.09624999999 296967.45375 0
The rule marks 359 ages above 62 and 15 credit scores below 383. Mistakes, or real values? The oldest customer is 92 and the lowest credit score is 350: both are possible. A bank does have customers of 70 and 80 years. These are real values, so they stay (Topic 25). Nothing in this file looks like a typing mistake.
6.6Step 6: encode the text columns
gender has two values. It becomes 0 and 1:
df["gender"] = df["gender"].map({"Female": 0, "Male": 1})
print(df["gender"].value_counts())Output
gender 1 5457 0 4543 Name: count, dtype: int64
country has three values without an order. It gets one-hot encoding, with one column dropped (Topic 25):
df = pd.get_dummies(df, columns=["country"], drop_first=True, dtype=int)
print(df.columns.tolist())Output
['credit_score', 'gender', 'age', 'tenure', 'balance', 'products_number', 'credit_card', 'active_member', 'estimated_salary', 'churn', 'country_Germany', 'country_Spain']
France, the first country in the alphabet, is the reference: a French customer has 0 in both new columns.
6.7Step 7: a look at the correlations
print(df.corr()["churn"].round(2).sort_values())Output
active_member -0.16 gender -0.11 products_number -0.05 country_Spain -0.05 credit_score -0.03 tenure -0.01 credit_card -0.01 estimated_salary 0.01 balance 0.12 country_Germany 0.17 age 0.29 churn 1.00 Name: churn, dtype: float64
The age has the strongest relationship with leaving (older customers leave more often), then the German customers and the balance; active members and men leave less often. No single column is strongly correlated with the target. That is normal in real data: the model has to combine many weak hints.
6.8Step 8: 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)Output
(8000, 11) (2000, 11)
Change it and run: change test_size to 0.3 and run: 3,000 customers become test data.
6.9Step 9: scale
The scaler is fitted on the training data and applied to both parts (Topic 24). For logistic regression scaling matters twice: the model is regularized, and its solver walks down a loss.
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, 11) (2000, 11)
The data is ready: 8,000 customers for training, 2,000 for the test, eleven features on the same scale.
Try it yourself
customer_id dropped? (c) Why does country get one-hot encoding and not the numbers 0, 1, 2?Show a hint
Show the solution
Answer: (a) 0.7963; (b) it only names the row; (c) the countries have no order.
An identification number is different for every row and says nothing about the customer. France, Germany and Spain have no order, so numbers in a row would invent one: every country gets its own column.
7The first model
7.1Train and judge
LogisticRegression is used like every model of scikit-learn. For a classifier, score returns the accuracy: the share of right predictions.
from sklearn.linear_model import LogisticRegression
model = LogisticRegression()
model.fit(X_train_scaled, y_train)
print(round(model.score(X_train_scaled, y_train), 4))
print(round(model.score(X_test_scaled, y_test), 4))Output
0.8114 0.811
Change it and run: write LogisticRegression(C=0.001) and run: both accuracies fall, because the penalty is too strong.
An accuracy of 0.8114 on the training data and 0.811 on the test data: the model is right for 81 of 100 customers, and it does not overfit (the two numbers are almost equal).
7.2Compare with the baseline
Is 0.811 good? The share of test customers who stayed:
print(round(1 - y_test.mean(), 4))Output
0.8035
Always answering "stays" would already be right for 0.8035 of the test customers. The model is better than that, but only by a little. An accuracy means nothing without its baseline, and with unbalanced classes the baseline is high. This is the main weakness of the accuracy, and the reason for the other measures of Topic 28. Part 9 will improve the model itself.
7.3predict and predict_proba
predict returns the class of every row:
print(model.predict(X_test_scaled)[:5])
print(y_test[:5].tolist())Output
[0 0 0 0 0] [0, 0, 0, 0, 0]
The first line is the prediction for the first five test customers, the second the truth. predict_proba returns the probabilities behind the predictions:
print(model.classes_)
print(model.predict_proba(X_test_scaled)[:5].round(3))Output
[0 1] [[0.767 0.233] [0.923 0.077] [0.684 0.316] [0.566 0.434] [0.933 0.067]]
- Every row has two numbers that add up to 1: the probability of class 0 (stays) and of class 1 (leaves).
model.classes_gives the order of the columns. - The first customer leaves with a probability of 0.233, the second with 0.077. Both are below 0.5, so
predictsays 0. - These numbers are the output of the sigmoid of Part 2.
The probability of leaving for every test customer is the second column:
leaving = model.predict_proba(X_test_scaled)[:, 1]
print(leaving[:5].round(3))
print(round(leaving.max(), 3))Output
[0.233 0.077 0.316 0.434 0.067] 0.918
[:, 1] takes the second column (Topic 8). A bank can sort its customers by this number and speak first with the ones at the top.
7.4The threshold
predict uses the threshold 0.5. With the probabilities you can use your own. The cell counts how many customers the model marks as leaving, and its accuracy, for three thresholds:
for threshold in [0.3, 0.5, 0.7]:
predicted = (leaving >= threshold).astype(int)
print(threshold, predicted.sum(), round((predicted == y_test).mean(), 4))Output
0.3 428 0.7965 0.5 143 0.811 0.7 25 0.809
Change it and run: add 0.4 and 0.6 to the list and run.
(leaving >= threshold) is True or False for every customer, astype(int) makes 1 and 0 of it, and (predicted == y_test).mean() is the share of right predictions: the accuracy, calculated by hand.
A lower threshold marks many more customers as leaving. Whether that is better depends on what a missed customer costs and what a needless call costs: a question of Topic 28. The accuracy alone cannot answer it.
7.5The weights
print(round(model.intercept_[0], 3))
for name, weight in zip(X.columns, model.coef_[0]):
print(name, round(weight, 3))Output
-1.636 credit_score -0.068 gender -0.265 age 0.754 tenure -0.043 balance 0.161 products_number -0.06 credit_card -0.01 active_member -0.533 estimated_salary 0.016 country_Germany 0.337 country_Spain 0.039
coef_ is a table with one row here, so coef_[0] is the list of the weights. The features are standardised, so the weights can be compared (Topic 24):
agehas the largest positive weight: older customers leave more often.active_memberhas the largest negative weight: active members stay.country_Germanyis positive: German customers leave more often than French ones, the reference.genderis negative: men (1) leave less often than women (0).credit_card,estimated_salaryandtenureare close to 0: they hardly matter.
The intercept is negative: for an average customer the score is clearly below 0, so the probability of leaving is far below 0.5. That is the 20 percent of Step 4, seen from inside the model.
Try it yourself
Show a hint
p = model.predict_proba(X_test_scaled)[9, 1] is row 9, column 1. Then print(round(p, 3)) and print(model.predict(X_test_scaled)[9]).Show the solution
p = model.predict_proba(X_test_scaled)[9, 1]
print(round(p, 3))
print(model.predict(X_test_scaled)[9])Output
0.303 0
Try it yourself
leaving holds the probability of leaving of every test customer. With the threshold 0.4, print how many customers are marked as leaving, then the accuracy, rounded to 4 decimals.Show a hint
predicted = (leaving >= 0.4).astype(int), then print(predicted.sum()) and print(round((predicted == y_test).mean(), 4)).Show the solution
predicted = (leaving >= 0.4).astype(int)
print(predicted.sum())
print(round((predicted == y_test).mean(), 4))Output
243 0.815
8Changing the hyperparameters
Now the parameters of Part 5, one at a time, on the same data. Change one thing, train again, and compare.
8.1C
Every line shows C, the training accuracy and the test accuracy:
for C in [0.0001, 0.001, 0.01, 0.1, 1, 10, 100]:
model = LogisticRegression(C=C)
model.fit(X_train_scaled, y_train)
print(C, round(model.score(X_train_scaled, y_train), 4), round(model.score(X_test_scaled, y_test), 4))Output
0.0001 0.7945 0.8035 0.001 0.7973 0.8065 0.01 0.8119 0.8145 0.1 0.8111 0.811 1 0.8114 0.811 10 0.8111 0.811 100 0.8111 0.811
- From
C = 0.1upwards nothing changes: the penalty is weak, and the model is the same. - With
C = 0.0001the penalty is so strong that all weights are pressed to almost 0. The test accuracy is 0.8035: exactly the baseline. The model has stopped using its features and answers "stays" for everybody. That is underfitting by too much regularization. - In between,
C = 0.01is a little better than the default on the test data.
The model has 11 features and 8,000 rows, so it hardly overfits, and regularization has little to do (the lesson of Topic 26). The choice of C is made with cross-validation on the training data, not with these test scores:
from sklearn.model_selection import cross_val_score
for C in [0.001, 0.01, 0.1, 1, 10]:
scores = cross_val_score(LogisticRegression(C=C), X_train_scaled, y_train, cv=5)
print(C, round(scores.mean(), 4))Output
0.001 0.7949 0.01 0.8104 0.1 0.8103 1 0.8104 10 0.8106
All values from 0.01 upwards are equal within a few ten-thousandths. The default, C = 1, is a fine choice here.
8.2The L1 penalty
With l1_ratio=1 the penalty is L1, as in a Lasso. The default solver cannot work with it, so solver="liblinear" is chosen too:
model = LogisticRegression(l1_ratio=1, solver="liblinear", C=0.01)
model.fit(X_train_scaled, y_train)
print(round(model.score(X_test_scaled, y_test), 4))
print((model.coef_[0] != 0).sum())
print(X.columns[model.coef_[0] != 0].tolist())Output
0.813 5 ['gender', 'age', 'balance', 'active_member', 'country_Germany']
Change it and run: change C=0.01 to C=0.005 and run: fewer weights are left.
Only 5 of the 11 weights are left, and the test accuracy is still 0.813. The model has selected the five features it needs most: the age, the gender, the balance, the active membership and Germany. A short model with the same accuracy is easier to explain to a bank.
8.3max_iter
How many steps did the solver of the first model need?
model = LogisticRegression()
model.fit(X_train_scaled, y_train)
print(model.n_iter_)Output
[6]
It was finished long before the limit of 100. On unscaled features it is another story:
unscaled = LogisticRegression()
unscaled.fit(X_train, y_train)
print(unscaled.n_iter_)
print(unscaled.score(X_test, y_test) < model.score(X_test_scaled, y_test))Output
[100] True
The first line shows that the solver used all 100 steps: it was stopped before it was finished. The second line asks whether the accuracy of this model is lower than that of the scaled model, and the answer is True (it is about 0.80 here, below even the baseline; the exact number of an unfinished model can differ a little from one computer to the next). When you run this cell it also shows a ConvergenceWarning. The warning itself names the two cures: scale the data, or raise max_iter. Scaling is the better one: it removes the cause.
8.4class_weight
balanced = LogisticRegression(class_weight="balanced")
balanced.fit(X_train_scaled, y_train)
print(round(balanced.score(X_test_scaled, y_test), 4))
print(model.predict(X_test_scaled).sum(), balanced.predict(X_test_scaled).sum(), y_test.sum())Output
0.7195 143 728 393
The accuracy falls from 0.811 to 0.7195. The second line explains why: the first model marked 143 test customers as leaving, the balanced one marks many more, and 393 really left. The first model was careful and missed most of the customers who leave. The balanced model finds far more of them and gives many false alarms on the way, and every false alarm costs accuracy.
Which model is better? With the accuracy alone, the first. For a bank that wants to find the customers who are about to leave, probably the second. This is exactly the point where the accuracy stops being enough, and where Topic 28 begins.
Try it yourself
LogisticRegression with C=0.01 and print its training accuracy, then its test accuracy, each rounded to 4 decimals.Show a hint
model = LogisticRegression(C=0.01), model.fit(X_train_scaled, y_train), then model.score for each part.Show the solution
model = LogisticRegression(C=0.01)
model.fit(X_train_scaled, y_train)
print(round(model.score(X_train_scaled, y_train), 4))
print(round(model.score(X_test_scaled, y_test), 4))Output
0.8119 0.8145
9A better model through better features
The hyperparameters moved the accuracy by a few thousandths. In Topic 24 the large gains came from the features. Look at one of them again:
print(df.groupby("products_number")["churn"].agg(["mean", "count"]).round(3))Output
mean count products_number 1 0.277 5084 2 0.076 4590 3 0.827 266 4 1.000 60
groupby with agg(["mean", "count"]) gives the share of customers who left and the number of customers, for every number of products (Topic 11).
This is a surprise. Customers with 2 products leave least often (7.6 percent), customers with 1 product much more often (27.7 percent), and of the customers with 3 or 4 products almost all left. The column is a number, but its effect is not in order: more products do not simply mean more or less churn.
A linear score can only say "every product more adds the same amount". It cannot follow down, then up. The cure is the one of Topic 25 for categories without order: one-hot encoding. The number of products is treated as four categories.
df = pd.get_dummies(df, columns=["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 table changed, so the split, the scaling and the training are repeated. The same random_state gives the same customers in each part:
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)
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)
model = LogisticRegression()
model.fit(X_train_scaled, y_train)
print(round(model.score(X_train_scaled, y_train), 4))
print(round(model.score(X_test_scaled, y_test), 4))Output
0.8416 0.843
| Model | Test accuracy |
|---|---|
| always "stays" (the baseline) | 0.8035 |
| the first model, 11 features | 0.811 |
the best C | 0.8145 |
products_number one-hot encoded, 13 features | 0.843 |
From 0.811 to 0.843: one look at a column and one line of encoding did more than every hyperparameter. The model is now four points above the baseline, not one. Understanding the data comes before tuning the model.
Try it yourself
LogisticRegression with class_weight="balanced" and print its test accuracy, rounded to 4 decimals, then the number of test customers it marks as leaving.Show a hint
balanced = LogisticRegression(class_weight="balanced"), balanced.fit(X_train_scaled, y_train), then score and print(balanced.predict(X_test_scaled).sum()).Show the solution
balanced = LogisticRegression(class_weight="balanced")
balanced.fit(X_train_scaled, y_train)
print(round(balanced.score(X_test_scaled, y_test), 4))
print(balanced.predict(X_test_scaled).sum())Output
0.7655 680
10More than two classes on the same data
LogisticRegression handles three or more classes with the same code. To see it, the question is turned round for a moment: predict the country of a customer from the other columns. (The bank knows the country, of course. The exercise only shows how the model behaves with three classes.)
raw = pd.read_csv("Bank Customer Churn Prediction.csv")
raw = raw.drop(columns=["customer_id"])
raw["gender"] = raw["gender"].map({"Female": 0, "Male": 1})
X3 = raw.drop(columns=["country"])
y3 = raw["country"]
X3_train, X3_test, y3_train, y3_test = train_test_split(X3, y3, test_size=0.2, random_state=42)
scaler3 = StandardScaler()
X3_train_scaled = scaler3.fit_transform(X3_train)
X3_test_scaled = scaler3.transform(X3_test)
print(y3.value_counts())Output
country France 5014 Germany 2509 Spain 2477 Name: count, dtype: int64
The target is a text column with three values. It does not have to be encoded: scikit-learn accepts class names as they are.
model3 = LogisticRegression()
model3.fit(X3_train_scaled, y3_train)
print(model3.classes_)
print(model3.predict_proba(X3_test_scaled)[:3].round(3))
print(model3.predict(X3_test_scaled)[:3])Output
['France' 'Germany' 'Spain'] [[0.498 0.251 0.251] [0.621 0.052 0.326] [0.649 0.052 0.299]] ['France' 'France' 'France']
classes_has three entries, andpredict_probahas three columns: one probability for every country, in that order. Every row adds up to 1. This is the softmax of Part 3.predictanswers with the country of the largest probability.
print(model3.coef_.shape)
print(round(model3.score(X3_test_scaled, y3_test), 4))Output
(3, 10) 0.536
coef_ now has three rows of weights, one for every class: three scores, as Part 3 described. The accuracy is 0.536, and about half of all customers are French, so the baseline is about 0.5. The model is hardly better than always answering "France": these columns say little about where a customer lives. That is an honest result, and it shows again why a baseline is needed. The mechanics are the point here: three classes, three scores, three probabilities, one line of code.
11The workflow, step by step
| Step | What is done | In this project |
|---|---|---|
| 1. Look | shape, first rows, the meaning of the columns | 10,000 customers, 12 columns |
| 2. Check | missing values, repeated rows, text columns | nothing missing; two text columns |
| 3. Drop | columns without information | customer_id |
| 4. Target | the share of each class, the baseline | 20 percent left; baseline about 0.80 |
| 5. Outliers | find them, decide: mistake or real | real customers: kept |
| 6. Encode | text to numbers | gender as 0 and 1, country one-hot |
| 7. Split | training and test data | 8,000 and 2,000 |
| 8. Scale | fit on the training data, transform both | StandardScaler |
| 9. First model | a simple starting point, compared with the baseline | accuracy 0.811 |
| 10. Tune | hyperparameters, with cross-validation | C, the penalty, class_weight |
| 11. Improve | better features | products_number one-hot: 0.843 |
| 12. Judge | the test score of the finished model | Topic 28 adds more measures |
Compared with a regression project, two steps are new: looking at the classes of the target, and comparing the accuracy with a baseline.
Try it yourself
C chosen? (c) What is fitted on the training data only?Show a hint
Show the solution
Answer: (a) the classes of the target and the baseline; (b) the training data, with cross-validation; (c) the scaler and the model.
A classifier is judged against the share of the largest class, so that share has to be known first. A hyperparameter is chosen without the test data. The scaler learns means and standard deviations and the model learns weights: both see the training data only.
12Common mistakes
| Mistake | Why it is wrong | Right |
|---|---|---|
| Using linear regression for a target of 0 and 1. | Its predictions leave the range from 0 to 1, and its loss does not fit classes. | Logistic regression. |
| "Logistic regression is a regression model." | It predicts classes. Only its inner score is a number. | It is a classifier. |
| Reading an accuracy without the baseline. | With 80 percent in one class, 0.80 is reached without any model. | Compare with the share of the largest class. |
"A large C is a strong regularization." | C is turned round: a small C is the strong penalty. | . |
| Training without scaling. | The penalty treats the features unequally, and the solver may not finish. | Scale first, with a scaler fitted on the training data. |
Ignoring a ConvergenceWarning. | The weights are not the best ones yet. | Scale the data, or raise max_iter. |
l1_ratio=1 with the default solver. | lbfgs supports only the L2 penalty: an error. | solver="liblinear" or "saga". |
| Reading a weight as "the change of the probability". | A weight changes the log-odds, not the probability. | Sign and size; or the odds are multiplied by . |
Thinking predict_proba gives one number per row. | It gives one column for every class. | [:, 1] is the probability of class 1. |
Choosing C or the threshold with the test data. | The test data then takes part in building the model. | Cross-validation on the training data. |
| Giving a numerical column with an effect that is not in order to a linear model as it is. | One weight cannot go down and up again. | One-hot encode it, as products_number. |
Expecting class_weight="balanced" to raise the accuracy. | It finds more of the rare class and usually lowers the accuracy. | Judge it with the measures of Topic 28. |
13Solved 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 the better encoding from the start and another split.
For the problems by hand: , , , .
Problem 1: The sigmoid by hand
Calculate the sigmoid of 3 and of . What do the two results add up to?
Idea. (Part 2).
Why: the two results add up to 1 (the small difference comes from rounding), because the sigmoid is symmetric: . A score of 3 is "almost sure yes", a score of "almost sure no".
Problem 2: From the features to a class
A model for churn is , with the age in decades and german 1 or 0. Predict for a German customer of 40 years (age = 4).
Idea. First the score, then the sigmoid, then the threshold 0.5 (Part 2).
Why: the score is exactly 0, so the probability is exactly 0.5: this customer lies on the decision boundary. With the rule "class 1 if is at least 0.5" the prediction is 1. One year more and the score would be positive.
Problem 3: The softmax by hand
A model for three classes gives the scores 3, 1 and 1. Calculate the three probabilities.
Idea. to the power of every score, divided by the sum (Part 3).
Why: the class with the largest score gets most of the probability, the two classes with equal scores get equal shares, and the three numbers add up to 1 (0.999 after rounding). The model answers with class 1.
Problem 4: The cross-entropy by hand
A customer stayed (). Model A gave a probability of leaving of 0.2, Model B of 0.9. Calculate the loss of each. Use and .
Idea. For the loss is : minus the logarithm of the probability given to the true class (Part 4).
Why: Model A gave the true class, "stays", a probability of 0.8 and pays little. Model B gave it only 0.1 and pays ten times as much. The cross-entropy punishes being sure of the wrong answer.
Problem 5: Read and check
Read the file. Print its shape, the number of missing values and the number of repeated rows.
Idea. The first two steps of the workflow (Part 6).
import pandas as pd
df = pd.read_csv("Bank Customer Churn Prediction.csv")
print(df.shape)
print(df.isna().sum().sum(), df.duplicated().sum())Output
(10000, 12) 0 0
Why: before any model, know what is in the table. Nothing has to be repaired here.
Problem 6: Drop and look at the target
Drop customer_id. Print the share of customers who left, rounded to 4 decimals.
Idea. An identification number carries no information; the mean of a column of 0 and 1 is the share of the ones (Part 6).
df = df.drop(columns=["customer_id"])
print(round(df["churn"].mean(), 4))Output
0.2037
Why: about one customer in five left. The classes are not balanced, so the accuracy of a model must later be compared with a baseline of about 0.80.
Problem 7: Encode
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. Two values: a dictionary. Categories without order, and a number whose effect is not in order: one-hot encoding (Parts 6 and 9).
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: get_dummies takes a list of columns and encodes them in one line. 14 columns: 13 features and the target.
Problem 8: Split
Make X and and split them with test_size=0.25 and random_state=7. Print the shapes of X_train and X_test.
Idea. The split comes before everything that learns from the rows (Part 6).
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(X_train.shape, X_test.shape)Output
(7500, 13) (2500, 13)
Why: a quarter of the customers is put aside. The model will not see them before it is finished.
Problem 9: Scale
Scale the features with a StandardScaler fitted on the training data. Print the shapes of the two scaled arrays.
Idea. fit_transform on the training data, transform on the test data (Topic 24).
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
(7500, 13) (2500, 13)
Why: logistic regression is regularized and is trained step by step. Both need features on the same scale.
Problem 10: The baseline
Print the accuracy of a "model" that answers 0 (stays) for every test customer, rounded to 4 decimals.
Idea. It is right for every customer who stayed: the share of zeros in y_test (Part 7).
print(round(1 - y_test.mean(), 4))Output
0.796
Why: this is the number to beat. A model with a lower accuracy has learned nothing useful.
Problem 11: Train and judge
Train a LogisticRegression and print its training accuracy and its test accuracy, rounded to 4 decimals.
Idea. fit, then score, which is the accuracy for a classifier (Part 7).
from sklearn.linear_model import LogisticRegression
model = LogisticRegression()
model.fit(X_train_scaled, y_train)
print(round(model.score(X_train_scaled, y_train), 4))
print(round(model.score(X_test_scaled, y_test), 4))Output
0.8433 0.8376
Why: the two accuracies are close together, so the model does not overfit, and the test accuracy lies about four points above the baseline of Problem 10.
Problem 12: Probabilities
Print the probabilities of the first three test customers, rounded to 3 decimals, and the predicted classes of the same customers.
Idea. predict_proba gives a column for every class; predict compares the second column with 0.5 (Part 7).
print(model.predict_proba(X_test_scaled)[:3].round(3))
print(model.predict(X_test_scaled)[:3])Output
[[0.195 0.805] [0.709 0.291] [0.93 0.07 ]] [1 0 0]
Why: every row of probabilities adds up to 1. A customer is predicted as 1 exactly when the second number is at least 0.5.
Problem 13: Another threshold
Take the probability of leaving of every test customer. With the threshold 0.4, how many customers are marked as leaving, and what is the accuracy?
Idea. [:, 1] is the probability of class 1; compare it with the threshold yourself (Part 7).
leaving = model.predict_proba(X_test_scaled)[:, 1]
predicted = (leaving >= 0.4).astype(int)
print(predicted.sum())
print(round((predicted == y_test).mean(), 4))Output
371 0.8396
Why: a lower threshold marks more customers. The accuracy hardly moves, but the model now catches customers it missed before: a difference the accuracy does not show.
Problem 14: Choosing C
Compare the values 0.001, 0.01, 0.1, 1 and 10 for C with a 5-fold cross-validation on the training data. Print every C with its mean accuracy, rounded to 4 decimals.
Idea. A hyperparameter is chosen with cross-validation, never with the test data (Part 8).
from sklearn.model_selection import cross_val_score
for C in [0.001, 0.01, 0.1, 1, 10]:
scores = cross_val_score(LogisticRegression(C=C), X_train_scaled, y_train, cv=5)
print(C, round(scores.mean(), 4))Output
0.001 0.8203 0.01 0.838 0.1 0.8423 1 0.8429 10 0.8431
Why: a very small C is too strong a penalty and lowers the accuracy. From 0.1 upwards the values are practically equal, so the default C = 1 can stay.
Problem 15: The L1 penalty
Train a model with l1_ratio=1, solver="liblinear" and C=0.01. Print its test accuracy and the number of weights that are not 0.
Idea. The L1 penalty sets weights to exactly 0, as a Lasso does (Part 8).
lasso_like = LogisticRegression(l1_ratio=1, solver="liblinear", C=0.01)
lasso_like.fit(X_train_scaled, y_train)
print(round(lasso_like.score(X_test_scaled, y_test), 4))
print((lasso_like.coef_[0] != 0).sum())Output
0.8392 7
Why: several of the 13 weights are exactly 0, and the accuracy stays close to that of the full model. The model has chosen its features itself.
Problem 16: Balanced classes
Train a model with class_weight="balanced". Print its test accuracy, then the number of test customers that the first model and this model mark as leaving, and the number who really left.
Idea. The rare class gets more weight in the loss (Part 8).
balanced = LogisticRegression(class_weight="balanced")
balanced.fit(X_train_scaled, y_train)
print(round(balanced.score(X_test_scaled, y_test), 4))
print(model.predict(X_test_scaled).sum(), balanced.predict(X_test_scaled).sum(), y_test.sum())Output
0.7568 250 850 510
Why: the accuracy is lower, and the balanced model marks far more customers as leaving than the first model did. It finds more of the customers who leave and gives more false alarms. Which model is better depends on the purpose, and the accuracy cannot decide it: Topic 28.
14Practice
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): from reading the file to a tuned model. Under every problem there is a hint and a solution.
For the problems by hand: , , , .
14.1Group A: by hand
- 1.Calculate the sigmoid of 1 and of , with 3 decimals.
Show a hint
. For the power is .Show one possible solution
Answer: 0.731 and 0.269.
The two results add up to 1: the sigmoid is symmetric.
- 2.A model is . A row has and . (a) What is the score ? (b) What is the probability of class 1? (c) Which class does the model predict?
Show a hint
The score first, then the sigmoid.Show one possible solution
Answer: (a) 2; (b) 0.881; (c) class 1.
(c) The probability 0.881 is above 0.5: class 1.
- 3.A model for three classes gives the scores 2, 0 and 0. Calculate the three probabilities with the softmax, with 3 decimals.
Show a hint
and . Divide each by the sum.Show one possible solution
Answer: 0.787, 0.107 and 0.107.
- 4.(a) A customer left () and the model gave a probability of leaving of 0.5. What is the cross-entropy loss? Use . (b) Which is the stronger regularization:
C = 0.01orC = 100? (c) Which function does a logistic regression use for five classes?Show a hint
The loss is minus the logarithm of the probability of the true class.Cis turned round.Show one possible solution
Answer: (a) 0.693; (b)
C = 0.01; (c) the softmax.(a) . (b) A small
Cis a strong penalty, because . (c) With three or more classes the softmax turns the scores into probabilities.
14.2Group B: one project in Python
The same workflow as in the lesson, on the same file, with the better encoding from the start and 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 9: look and prepare
Read the file, drop the identification number, look at the target and at the ages, encode the text columns.
- 5.Read
Bank Customer Churn Prediction.csvintodf. Print the shape, then the number of missing values.Show a hint
df = pd.read_csv("Bank Customer Churn Prediction.csv"), thenprint(df.shape)andprint(df.isna().sum().sum()).Show one possible solution
Pythonimport pandas as pd df = pd.read_csv("Bank Customer Churn Prediction.csv") print(df.shape) print(df.isna().sum().sum())Output
(10000, 12) 0
- 6.Drop the column
customer_id. Print the number of customers who left, then the share of customers who left. This step continues from Step 5.Show a hint
df = df.drop(columns=["customer_id"]), thenprint(df["churn"].sum())andprint(df["churn"].mean()).Show one possible solution
Python, continues from the cells abovedf = df.drop(columns=["customer_id"]) print(df["churn"].sum()) print(df["churn"].mean())Output
2037 0.2037
- 7.Calculate the upper limit of the IQR rule for
age. Print the limit, then the number of ages above it. (They are real customers and stay in the data.) This step continues from Step 6.Show a hint
q1 = df["age"].quantile(0.25), the same with0.75forq3, thenupper = q3 + 1.5 * (q3 - q1). The number of ages above it is(df["age"] > upper).sum().Show one possible solution
Python, continues from the cells aboveq1 = df["age"].quantile(0.25) q3 = df["age"].quantile(0.75) upper = q3 + 1.5 * (q3 - q1) print(upper) print((df["age"] > upper).sum())Output
62.0 359
- 8.Encode
genderas 0 (Female) and 1 (Male). Print the number of men. This step continues from Step 6.Show a hint
df["gender"] = df["gender"].map({"Female": 0, "Male": 1}). The number of men is the sum of the column.Show one possible solution
Python, continues from the cells abovedf["gender"] = df["gender"].map({"Female": 0, "Male": 1}) print(df["gender"].sum())Output
5457
- 9.One-hot encode
countryandproducts_numberinside the table, withdrop_first=Trueanddtype=int. Print the names of the columns as a list. This step continues from Step 8.Show a hint
df = pd.get_dummies(df, columns=["country", "products_number"], drop_first=True, dtype=int), thenprint(df.columns.tolist()).Show one possible solution
Python, continues from the cells abovedf = 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']
Steps 10 to 13: split, scale, baseline, model
The split, the scaler fitted on the training data, the number to beat, and the first model.
- 10.Make
X(all columns withoutchurn) andy(churn). Split them withtest_size=0.3andrandom_state=1. Print the shapes ofX_trainandX_teston one line. This step continues from Step 9.Show a hint
from sklearn.model_selection import train_test_split,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).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(X_train.shape, X_test.shape)Output
(7000, 13) (3000, 13)
- 11.Scale the features with a
StandardScalercalledscalerintoX_train_scaledandX_test_scaled. Print the largest value of the scaled test data, rounded to 2 decimals. This step continues from Step 10.Show a hint
from sklearn.preprocessing import StandardScaler,scaler.fit_transform(X_train)for the training data andscaler.transform(X_test)for the test data, thenprint(round(X_test_scaled.max(), 2)). If your number differs, checktest_size=0.3andrandom_state=1in Step 10.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(round(X_test_scaled.max(), 2))Output
12.57
- 12.Print the baseline: the accuracy of always answering 0 (stays) for the test customers, rounded to 4 decimals. This step continues from Step 10.
Show a hint
It is the share of zeros iny_test:print(round(1 - y_test.mean(), 4)).Show one possible solution
Python, continues from the cells aboveprint(round(1 - y_test.mean(), 4))Output
0.791
- 13.Train a
LogisticRegressioncalledmodelon the scaled training data. Print the training accuracy, then the test accuracy, each rounded to 4 decimals. This step continues from Step 11.Show a hint
from sklearn.linear_model import LogisticRegression,model.fit(X_train_scaled, y_train), thenmodel.score(X_train_scaled, y_train)andmodel.score(X_test_scaled, y_test).Show one possible solution
Python, continues from the cells abovefrom sklearn.linear_model import LogisticRegression model = LogisticRegression() model.fit(X_train_scaled, y_train) print(round(model.score(X_train_scaled, y_train), 4)) print(round(model.score(X_test_scaled, y_test), 4))Output
0.8416 0.84
Steps 14 to 16: probabilities and hyperparameters
The probabilities behind the predictions, a strong penalty, and balanced classes.
- 14.Make
leaving, the probability of leaving of every test customer. Print the first three values, rounded to 3 decimals, then the number of test customers with a probability of at least 0.5. This step continues from Step 13.Show a hint
leaving = model.predict_proba(X_test_scaled)[:, 1], thenprint(leaving[:3].round(3))andprint((leaving >= 0.5).sum()).Show one possible solution
Python, continues from the cells aboveleaving = model.predict_proba(X_test_scaled)[:, 1] print(leaving[:3].round(3)) print((leaving >= 0.5).sum())Output
[0.038 0.168 0.051] 309
- 15.Train a
LogisticRegressionwithC=0.001and print its test accuracy, rounded to 4 decimals. Is thisCa good choice? This step continues from Step 13.Show a hint
strong = LogisticRegression(C=0.001),fit, thenprint(round(strong.score(X_test_scaled, y_test), 4)). The accuracy is lower than that of the default model: the penalty is too strong, and the model underfits.Show one possible solution
Python, continues from the cells abovestrong = LogisticRegression(C=0.001) strong.fit(X_train_scaled, y_train) print(round(strong.score(X_test_scaled, y_test), 4))Output
0.8157
- 16.Train a
LogisticRegressionwithclass_weight="balanced". Print its test accuracy, rounded to 4 decimals, then the number of test customers it marks as leaving. This step continues from Step 13.Show a hint
balanced = LogisticRegression(class_weight="balanced"),fit, thenscoreandprint(balanced.predict(X_test_scaled).sum()). The accuracy falls, and the model marks many more customers than the count of Step 14. Whether that is better is the question of Topic 28.Show one possible solution
Python, continues from the cells abovebalanced = LogisticRegression(class_weight="balanced") balanced.fit(X_train_scaled, y_train) print(round(balanced.score(X_test_scaled, y_test), 4)) print(balanced.predict(X_test_scaled).sum())Output
0.7673 1001
15Check yourself
Twelve questions. Every question has one right answer.
0 of 12 answered.
16Summary
| Formula | Meaning | |
|---|---|---|
| Score | a weighted sum, as in linear regression | |
| Sigmoid | turns the score into a probability (two classes) | |
| Softmax | probabilities for three or more classes | |
| Log-odds | what the model assumes to be linear | |
| Cross-entropy | the loss: minus the logarithm of the probability of the true class | |
| Decision | class 1 if | the same as |
| Code | What it does |
|---|---|
model = LogisticRegression() | creates the model (regularized, C=1) |
model.fit(X_train_scaled, y_train) | learns the weights |
model.score(X_test_scaled, y_test) | the accuracy |
model.predict(X_test_scaled) | the classes |
model.predict_proba(X_test_scaled)[:, 1] | the probability of class 1 |
model.coef_, model.intercept_, model.classes_ | the weights, the intercept, the classes |
LogisticRegression(C=0.01) | a stronger regularization |
LogisticRegression(l1_ratio=1, solver="liblinear") | the L1 penalty: some weights become 0 |
LogisticRegression(class_weight="balanced") | more weight for the rare class |
1 - y_test.mean() | the baseline for a target of 0 and 1 with more zeros |
Rules to keep
- Logistic regression is a classifier. It predicts a probability and turns it into a class.
- A linear score, then the sigmoid (two classes) or the softmax (more classes).
- It is trained with the cross-entropy and judged, in this lesson, with the accuracy.
- Look at the classes of the target first, and compare every accuracy with the baseline.
- Scale the features: the model is regularized, and its solver walks down a loss.
- A small
Cis a strong regularization. Choose it with cross-validation. - Better features beat better hyperparameters.
What comes next
This lesson judged its models with the accuracy and found its limits twice: a model that is barely above the baseline, and a balanced model that is "worse" and still more useful. Topic 28, classification metrics, gives the tools to see what the accuracy hides: the confusion matrix, precision, recall, the F1-score and the ROC curve.