Asiman Data School

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.

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. 1.What classification is, and why linear regression does not fit it
  2. 2.The formula of logistic regression, and where it comes from: odds, log-odds and the sigmoid
  3. 3.Binary and multi-class classification, the sigmoid and the softmax
  4. 4.The loss function, cross-entropy, and why it is preferred to the squared error
  5. 5.The parameters of LogisticRegression and what each one does
  6. 6.A whole classification project: look, clean, encode, split, scale, train, tune
  7. 7.predict, predict_proba, the threshold, and how to read the weights
The words of this lesson
WordMeaning
classificationpredicting a class (a category), not a number
binary classificationtwo classes: yes or no, 1 or 0
multi-class classificationthree or more classes
logistic regressiona linear model that predicts the probability of a class
oddsthe probability that something happens divided by the probability that it does not
log-odds (logit)the logarithm of the odds
sigmoidthe S-shaped function that turns any number into a number between 0 and 1
softmaxthe function that turns several scores into probabilities that add up to 1
activation functionthe function between the linear score and the output: here the sigmoid or the softmax
thresholdthe probability from which the model answers "yes": usually 0.5
cross-entropy (log loss)the loss function of logistic regression
accuracythe share of predictions that are right
churna customer leaving a company

1What logistic regression is, and why it is needed

1.1A new kind of question

A new kind of question
RegressionClassification
The target isa numbera class
Examplethe price of a housewill the customer leave: yes or no
Typical modellinear regressionlogistic regression
Typical measureR2R^2, RMSEaccuracy

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.

00.510510

Linear regression

a straight line: below 0 and above 1

00.510510

Logistic regression

an S-shaped curve between 0 and 1

Rows of two classes, drawn at the height 0 or 1. Left: a straight line through them leaves the range from 0 to 1 at both ends. Right: an S-shaped curve stays between 0 and 1, is almost flat where the answer is sure, and changes quickly near the border between the classes.
  1. A line has no limits. For large xx it predicts more than 1, for small xx less than 0. A probability of 1.3 or of −0.2-0.2 does not exist.
  2. 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.
  3. 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

Regression or classification? (a) Predict the price of a flat. (b) Predict whether an e-mail is spam. (c) Predict the mark of a student from 0 to 100. (d) Predict which of three countries a customer lives in.

Show a hint
Is the target a number or a class?
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 zz:

z=w0+w1x1+w2x2+⋯+wpxpz = w_0 + w_1 x_1 + w_2 x_2 + \dots + w_p x_p

zz can be any number, from very negative to very positive. A large positive zz shall mean "almost certainly class 1", a large negative zz "almost certainly class 0". What is needed is a bridge from zz to a probability.

2.2Step 2: from a probability to the odds

A probability pp lies between 0 and 1. The odds compare it with its opposite:

odds=p1−p\text{odds} = \frac{p}{1 - p}
Step 2: from a probability to the odds
Probability ppOddsIn words
0.50.50.5=1\frac{0.5}{0.5} = 1one to one
0.80.80.2=4\frac{0.8}{0.2} = 4four to one
0.90.90.1=9\frac{0.9}{0.1} = 9nine to one
0.20.20.8=0.25\frac{0.2}{0.8} = 0.25one 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:

log-odds=ln⁡p1−p\text{log-odds} = \ln \frac{p}{1 - p}
Step 3: from the odds to the log-odds
Probability ppOddsLog-odds
0.10.111−2.197-2.197
0.20.25−1.386-1.386
0.510
0.841.386
0.992.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 −1.386-1.386. 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:

ln⁡p1−p=z=w0+w1x1+⋯+wpxp\ln \frac{p}{1 - p} = z = w_0 + w_1 x_1 + \dots + w_p x_p

That one line is the whole model. Everything else follows by solving it for pp:

p1−p=ezp=ez (1−p)p (1+ez)=ezp=ez1+ezp=11+e−z\begin{aligned} \frac{p}{1 - p} &= e^{z} \\[6pt] p &= e^{z} \, (1 - p) \\[6pt] p \, (1 + e^{z}) &= e^{z} \\[6pt] p &= \frac{e^{z}}{1 + e^{z}} \\[6pt] p &= \frac{1}{1 + e^{-z}} \end{aligned}

The last step divides the top and the bottom by eze^{z}. The result is the formula of logistic regression:

p=11+e−zz=w0+w1x1+⋯+wpxp\begin{aligned} p &= \frac{1}{1 + e^{-z}} \\[8pt] z &= w_0 + w_1 x_1 + \dots + w_p x_p \end{aligned}

The function that turns zz into pp has a name of its own: the sigmoid.

2.5The sigmoid

sigmoid(z)=11+e−z\text{sigmoid}(z) = \frac{1}{1 + e^{-z}}

By hand, with e−2=0.135e^{-2} = 0.135 and e2=7.389e^{2} = 7.389:

z=0:11+e0=11+1=0.5z=2:11+e−2=11+0.135=11.135=0.881z=−2:11+e2=11+7.389=18.389=0.119\begin{aligned} z = 0:\quad & \frac{1}{1 + e^{0}} = \frac{1}{1 + 1} = 0.5 \\[8pt] z = 2:\quad & \frac{1}{1 + e^{-2}} = \frac{1}{1 + 0.135} \\[4pt] & = \frac{1}{1.135} = 0.881 \\[8pt] z = -2:\quad & \frac{1}{1 + e^{2}} = \frac{1}{1 + 7.389} \\[4pt] & = \frac{1}{8.389} = 0.119 \end{aligned}
00.51−6−4−20246p = 0.119p = 0.500p = 0.881
The sigmoid. The score z runs to the right, the probability p upwards. Three points are marked: a score of −2 gives 0.119, a score of 0 gives exactly 0.5, a score of 2 gives 0.881. The curve comes close to 0 and to 1 and never reaches them.

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 −100-100 one just above 0. The limits are never reached.
  • At z=0z = 0 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: sigmoid(−z)=1−sigmoid(z)\text{sigmoid}(-z) = 1 - \text{sigmoid}(z). 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:

p≥0.5:class 1p<0.5:class 0\begin{aligned} p \ge 0.5:\quad & \text{class 1} \\[4pt] p < 0.5:\quad & \text{class 0} \end{aligned}

Because p=0.5p = 0.5 exactly when z=0z = 0, this is the same as asking whether the score is positive. The points where z=0z = 0 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).

z=−4+1.0×age−1.0×activez = -4 + 1.0 \times \text{age} - 1.0 \times \text{active}

A customer of 50 years (age = 5) who is not active:

z=−4+1.0×5−1.0×0=1p=11+e−1=11+0.368=11.368=0.731\begin{aligned} z &= -4 + 1.0 \times 5 - 1.0 \times 0 = 1 \\[8pt] p &= \frac{1}{1 + e^{-1}} = \frac{1}{1 + 0.368} \\[4pt] &= \frac{1}{1.368} = 0.731 \end{aligned}

The probability of leaving is 0.731, above 0.5: the model predicts class 1, "leaves". The same customer as an active member:

z=−4+1.0×5−1.0×1=0p=11+e0=0.5\begin{aligned} z &= -4 + 1.0 \times 5 - 1.0 \times 1 = 0 \\[8pt] p &= \frac{1}{1 + e^{0}} = 0.5 \end{aligned}

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 ww adds ww to the log-odds for every unit of the feature.
  • The odds are then multiplied by ewe^{w}.

In the example, one decade of age adds 1.0 to the score, so it multiplies the odds of leaving by e1=2.718e^{1} = 2.718. Being an active member multiplies them by e−1=0.368e^{-1} = 0.368: 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.

00.51−6−4−20246

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

A model is z=−1+2xz = -1 + 2x. (a) What is the score for x=1x = 1? (b) What is the probability of class 1 for this row? Use e−1=0.368e^{-1} = 0.368. (c) Which class does the model predict? (d) What are the odds for a probability of 0.75?

Show a hint
The score first, then the sigmoid, then the threshold 0.5. The odds are pp divided by 1−p1 - p.
Show the solution

Answer: (a) 1; (b) 0.731; (c) class 1; (d) 3.

(a)z=−1+2×1=1(b)p=11+e−1=11.368=0.731(d)0.750.25=3\begin{aligned} \text{(a)}\quad & z = -1 + 2 \times 1 = 1 \\[6pt] \text{(b)}\quad & p = \frac{1}{1 + e^{-1}} = \frac{1}{1.368} = 0.731 \\[6pt] \text{(d)}\quad & \frac{0.75}{0.25} = 3 \end{aligned}

(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 and multi-class
Binary classificationMulti-class classification
Classestwothree or more
Examplesleaves or stays; spam or not; ill or healthythe country of a customer; the digit in a picture; the species of a flower
The model calculatesone score zzone score for every class
Function at the endsigmoidsoftmax
Outputone probability pp (the other is 1−p1 - p)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, z1z_1, z2z_2, z3z_3: one for every class. The softmax turns them into three probabilities:

p1=ez1ez1+ez2+ez3p2=ez2ez1+ez2+ez3p3=ez3ez1+ez2+ez3\begin{aligned} p_1 &= \frac{e^{z_1}}{e^{z_1} + e^{z_2} + e^{z_3}} \\[8pt] p_2 &= \frac{e^{z_2}}{e^{z_1} + e^{z_2} + e^{z_3}} \\[8pt] p_3 &= \frac{e^{z_3}}{e^{z_1} + e^{z_2} + e^{z_3}} \end{aligned}

Two things happen. eze^{z} 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 (e2=7.389e^{2} = 7.389, e1=2.718e^{1} = 2.718, e0=1e^{0} = 1):

sum=7.389+2.718+1=11.107p1=7.38911.107=0.665p2=2.71811.107=0.245p3=111.107=0.090\begin{aligned} \text{sum} &= 7.389 + 2.718 + 1 = 11.107 \\[8pt] p_1 &= \frac{7.389}{11.107} = 0.665 \\[6pt] p_2 &= \frac{2.718}{11.107} = 0.245 \\[6pt] p_3 &= \frac{1}{11.107} = 0.090 \end{aligned}

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

Three scores, 2, 1 and 0, and what the softmax makes of them: probabilities that add up to 1. The largest score gets most of the probability, and the others keep a little.
  • 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

Side by side
SigmoidSoftmax
Used fortwo classesthree or more classes
Inputone scoreone score for every class
Outputone probability between 0 and 1probabilities that add up to 1
Formula11+e−z\frac{1}{1 + e^{-z}}ezksum of all ez\frac{e^{z_k}}{\text{sum of all } e^{z}}
Decisionclass 1 if p≥0.5p \ge 0.5the 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

(a) A model for three classes gives the scores 1, 1 and 1. What probability does every class get, with 3 decimals? (b) What do the probabilities of a softmax always add up to? (c) A model shall recognise the ten digits 0 to 9. Which function turns its scores into probabilities?

Show a hint
Equal scores give equal shares. Ten classes are more than two.
Show the solution

Answer: (a) 0.333; (b) 1; (c) the softmax.

e1e1+e1+e1=13=0.333\frac{e^{1}}{e^{1} + e^{1} + e^{1}} = \frac{1}{3} = 0.333

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 pp, and the true answer yy 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:

loss=−ln⁡(p)when the true class is 1loss=−ln⁡(1−p)when the true class is 0\begin{aligned} \text{loss} &= -\ln(p) && \text{when the true class is 1} \\[4pt] \text{loss} &= -\ln(1 - p) && \text{when the true class is 0} \end{aligned}

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:

loss=−[ yln⁡(p)+(1−y)ln⁡(1−p) ]\text{loss} = -\left[ \, y \ln(p) + (1 - y) \ln(1 - p) \, \right]

With y=1y = 1 the second part disappears, with y=0y = 0 the first. The loss of the model is the mean over all rows.

4.3By hand

Four customers who really left (y=1y = 1), and the probability of leaving that the model gave each of them:

By hand
The model saidLossReading
p=0.99p = 0.99−ln⁡(0.99)=0.010-\ln(0.99) = 0.010sure and right: almost no loss
p=0.9p = 0.9−ln⁡(0.9)=0.105-\ln(0.9) = 0.105right: a small loss
p=0.6p = 0.6−ln⁡(0.6)=0.511-\ln(0.6) = 0.511right, but unsure: a medium loss
p=0.1p = 0.1−ln⁡(0.1)=2.303-\ln(0.1) = 2.303wrong: a large loss
p=0.01p = 0.01−ln⁡(0.01)=4.605-\ln(0.01) = 4.605sure and wrong: a very large loss
01234500.20.40.60.81
  • the true class is 1: the loss is −ln(p)
  • the true class is 0: the loss is −ln(1 − p)
The price of a prediction. To the right the probability p that the model gives to class 1, upwards the loss. When the true class is 1, a probability close to 1 costs almost nothing and a probability close to 0 costs very much. When the true class is 0, it is the other way round.

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 (y=1y = 1):

Why this loss, and not the squared error?
The model saidSquared error (1−p)2(1 - p)^2Cross-entropy −ln⁡(p)-\ln(p)
p=0.9p = 0.90.010.105
p=0.5p = 0.50.250.693
p=0.1p = 0.10.812.303
p=0.01p = 0.010.984.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, p−yp - y: 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.

loss=−ln⁡(p of the true class)\text{loss} = -\ln(p \text{ of 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 −ln⁡(0.665)=0.408-\ln(0.665) = 0.408. If it is class 3, the loss is −ln⁡(0.090)=2.408-\ln(0.090) = 2.408.

Choose what really happened and move the probability of leaving that the model gave.

01234500.20.40.60.81

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

A customer left (y=1y = 1). (a) The model said p=0.5p = 0.5. What is the cross-entropy loss? Use ln⁡(0.5)=−0.693\ln(0.5) = -0.693. (b) Which prediction has the larger loss: p=0.2p = 0.2 or p=0.7p = 0.7? (c) With which loss is a logistic regression trained? (d) With which measure is it judged in this lesson?

Show a hint
The loss is minus the logarithm of the probability given to the true class. A smaller probability for the truth costs more.
Show the solution

Answer: (a) 0.693; (b) p=0.2p = 0.2; (c) the cross-entropy; (d) the accuracy.

−ln⁡(0.5)=0.693-\ln(0.5) = 0.693

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.

The parameters of LogisticRegression
ParameterDefaultWhat it does
C1.0the strength of the regularization, turned round: a small C is a strong penalty
l1_ratio0the 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_iter100the largest number of steps the solver may take
class_weightNone"balanced" gives the rare class more weight in the loss
random_stateNonefixes 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:

C=1αC = \frac{1}{\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 and max_iter: how the weights are found
SolverGood 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):

What is learned, not set
AttributeMeaning
model.coef_the weights, one for every feature
model.intercept_the intercept w0w_0
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

(a) Which value of 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 C=1αC = \frac{1}{\alpha}. 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.

Python
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
Step 1: read the file and look at it
ColumnMeaning
customer_idthe identification number of the customer
credit_scorethe credit score: how reliable the customer is with money
countryFrance, Germany or Spain
genderFemale or Male
agethe age in years
tenurefor how many years the customer has been with the bank
balancethe money in the account
products_numberhow many products of the bank the customer uses
credit_cardhas a credit card: 1 or 0
active_memberis an active member: 1 or 0
estimated_salarythe estimated salary
churnthe 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.

Download

Loading the table ...

6.2Step 2: check the columns

Missing values, repeated rows, and the columns that are text (Topic 11):

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

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

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

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

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

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

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

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

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

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)

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.

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, 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

In a data set 2,037 of 10,000 customers left. (a) What accuracy does a "model" reach that answers "stays" for everybody? (b) Why is customer_id dropped? (c) Why does country get one-hot encoding and not the numbers 0, 1, 2?

Show a hint
The model is right for everybody who stayed. Topics 24 and 25 for the other two.
Show the solution

Answer: (a) 0.7963; (b) it only names the row; (c) the countries have no order.

10000−203710000=796310000=0.7963\frac{10000 - 2037}{10000} = \frac{7963}{10000} = 0.7963

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.

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

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

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

Python, continues from the cells above
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 predict says 0.
  • These numbers are the output of the sigmoid of Part 2.

The probability of leaving for every test customer is the second column:

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

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

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

  • age has the largest positive weight: older customers leave more often.
  • active_member has the largest negative weight: active members stay.
  • country_Germany is positive: German customers leave more often than French ones, the reference.
  • gender is negative: men (1) leave less often than women (0).
  • credit_card, estimated_salary and tenure are 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

This task continues from the cells above. Print the probability of leaving of the tenth test customer (position 9), rounded to 3 decimals, then the class the model predicts for this customer.
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
Python, continues from the cells above
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

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

Python, continues from the cells above
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.1 upwards nothing changes: the penalty is weak, and the model is the same.
  • With C = 0.0001 the 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.01 is 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:

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

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

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

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

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

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

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

The share of customers who left, for every number of products. It does not rise or fall in order: lowest at 2 products, far higher at 3 and 4. One weight for the number of products cannot follow this.

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.

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

Python, continues from the cells above
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)
Python, continues from the cells above
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
A better model through better features
ModelTest accuracy
always "stays" (the baseline)0.8035
the first model, 11 features0.811
the best C0.8145
products_number one-hot encoded, 13 features0.843
The test accuracy of the models of this lesson. The baseline, always answering 'stays', is already at 0.8035, so the first model is only a little better. The step that mattered was the encoding of one feature.

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

This task continues from the cells above, with the thirteen features. Train a 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
Python, continues from the cells above
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.)

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

Python, continues from the cells above
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, and predict_proba has three columns: one probability for every country, in that order. Every row adds up to 1. This is the softmax of Part 3.
  • predict answers with the country of the largest probability.
Python, continues from the cells above
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

The workflow, step by step
StepWhat is doneIn this project
1. Lookshape, first rows, the meaning of the columns10,000 customers, 12 columns
2. Checkmissing values, repeated rows, text columnsnothing missing; two text columns
3. Dropcolumns without informationcustomer_id
4. Targetthe share of each class, the baseline20 percent left; baseline about 0.80
5. Outliersfind them, decide: mistake or realreal customers: kept
6. Encodetext to numbersgender as 0 and 1, country one-hot
7. Splittraining and test data8,000 and 2,000
8. Scalefit on the training data, transform bothStandardScaler
9. First modela simple starting point, compared with the baselineaccuracy 0.811
10. Tunehyperparameters, with cross-validationC, the penalty, class_weight
11. Improvebetter featuresproducts_number one-hot: 0.843
12. Judgethe test score of the finished modelTopic 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

(a) Which two steps does a classification project add to a regression project? (b) With which data is C chosen? (c) What is fitted on the training data only?

Show a hint
Look at Steps 4 and 9 of the table. Whatever learns from the rows learns from the training rows.
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

Common mistakes
MistakeWhy it is wrongRight
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.C=1αC = \frac{1}{\alpha}.
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 ewe^{w}.
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: e−3=0.050e^{-3} = 0.050, e−1=0.368e^{-1} = 0.368, e1=2.718e^{1} = 2.718, e3=20.086e^{3} = 20.086.

Problem 1: The sigmoid by hand

Calculate the sigmoid of 3 and of −3-3. What do the two results add up to?

Idea. sigmoid(z)=11+e−z\text{sigmoid}(z) = \frac{1}{1 + e^{-z}} (Part 2).

z=3:11+e−3=11+0.050=11.050=0.952z=−3:11+e3=11+20.086=121.086=0.047\begin{aligned} z = 3:\quad & \frac{1}{1 + e^{-3}} = \frac{1}{1 + 0.050} \\[4pt] & = \frac{1}{1.050} = 0.952 \\[8pt] z = -3:\quad & \frac{1}{1 + e^{3}} = \frac{1}{1 + 20.086} \\[4pt] & = \frac{1}{21.086} = 0.047 \end{aligned}

Why: the two results add up to 1 (the small difference comes from rounding), because the sigmoid is symmetric: sigmoid(−z)=1−sigmoid(z)\text{sigmoid}(-z) = 1 - \text{sigmoid}(z). A score of 3 is "almost sure yes", a score of −3-3 "almost sure no".

Problem 2: From the features to a class

A model for churn is z=−3+0.5×age+1.0×germanz = -3 + 0.5 \times \text{age} + 1.0 \times \text{german}, 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).

z=−3+0.5×4+1.0×1=−3+2+1=0p=11+e0=12=0.5\begin{aligned} z &= -3 + 0.5 \times 4 + 1.0 \times 1 \\ &= -3 + 2 + 1 = 0 \\[8pt] p &= \frac{1}{1 + e^{0}} = \frac{1}{2} = 0.5 \end{aligned}

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 pp 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. ee to the power of every score, divided by the sum (Part 3).

e3=20.086e1=2.718sum=20.086+2.718+2.718=25.522p1=20.08625.522=0.787p2=2.71825.522=0.106p3=2.71825.522=0.106\begin{aligned} & e^{3} = 20.086 \qquad e^{1} = 2.718 \\[4pt] & \text{sum} = 20.086 + 2.718 + 2.718 = 25.522 \\[8pt] p_1 &= \frac{20.086}{25.522} = 0.787 \\[6pt] p_2 &= \frac{2.718}{25.522} = 0.106 \\[6pt] p_3 &= \frac{2.718}{25.522} = 0.106 \end{aligned}

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 (y=0y = 0). Model A gave a probability of leaving of 0.2, Model B of 0.9. Calculate the loss of each. Use ln⁡(0.8)=−0.223\ln(0.8) = -0.223 and ln⁡(0.1)=−2.303\ln(0.1) = -2.303.

Idea. For y=0y = 0 the loss is −ln⁡(1−p)-\ln(1 - p): minus the logarithm of the probability given to the true class (Part 4).

Model A:−ln⁡(1−0.2)=−ln⁡(0.8)=0.223Model B:−ln⁡(1−0.9)=−ln⁡(0.1)=2.303\begin{aligned} \text{Model A:}\quad & -\ln(1 - 0.2) = -\ln(0.8) = 0.223 \\[6pt] \text{Model B:}\quad & -\ln(1 - 0.9) = -\ln(0.1) = 2.303 \end{aligned}

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

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

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

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

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

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

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

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

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

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

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

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

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

Python, continues from the cells above
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: e−2=0.135e^{-2} = 0.135, e−1=0.368e^{-1} = 0.368, e1=2.718e^{1} = 2.718, e2=7.389e^{2} = 7.389.

14.1Group A: by hand

  1. 1.Calculate the sigmoid of 1 and of −1-1, with 3 decimals.

    Show a hint
    11+e−z\frac{1}{1 + e^{-z}}. For z=−1z = -1 the power is e1e^{1}.
    Show one possible solution

    Answer: 0.731 and 0.269.

    z=1:11+0.368=11.368=0.731z=−1:11+2.718=13.718=0.269\begin{aligned} z = 1:\quad & \frac{1}{1 + 0.368} = \frac{1}{1.368} = 0.731 \\[6pt] z = -1:\quad & \frac{1}{1 + 2.718} = \frac{1}{3.718} = 0.269 \end{aligned}

    The two results add up to 1: the sigmoid is symmetric.

  2. 2.A model is z=−2+0.5x1+1.5x2z = -2 + 0.5 x_1 + 1.5 x_2. A row has x1=2x_1 = 2 and x2=2x_2 = 2. (a) What is the score zz? (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.

    (a)z=−2+0.5×2+1.5×2=−2+1+3=2(b)p=11+e−2=11.135=0.881\begin{aligned} \text{(a)}\quad & z = -2 + 0.5 \times 2 + 1.5 \times 2 \\ & \quad = -2 + 1 + 3 = 2 \\[6pt] \text{(b)}\quad & p = \frac{1}{1 + e^{-2}} = \frac{1}{1.135} = 0.881 \end{aligned}

    (c) The probability 0.881 is above 0.5: class 1.

  3. 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
    e2=7.389e^{2} = 7.389 and e0=1e^{0} = 1. Divide each by the sum.
    Show one possible solution

    Answer: 0.787, 0.107 and 0.107.

    sum=7.389+1+1=9.389p1=7.3899.389=0.787p2=p3=19.389=0.107\begin{aligned} \text{sum} &= 7.389 + 1 + 1 = 9.389 \\[6pt] p_1 &= \frac{7.389}{9.389} = 0.787 \\[6pt] p_2 = p_3 &= \frac{1}{9.389} = 0.107 \end{aligned}
  4. 4.(a) A customer left (y=1y = 1) and the model gave a probability of leaving of 0.5. What is the cross-entropy loss? Use ln⁡(0.5)=−0.693\ln(0.5) = -0.693. (b) Which is the stronger regularization: C = 0.01 or C = 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. C is turned round.
    Show one possible solution

    Answer: (a) 0.693; (b) C = 0.01; (c) the softmax.

    (a) −ln⁡(0.5)=0.693-\ln(0.5) = 0.693. (b) A small C is a strong penalty, because C=1αC = \frac{1}{\alpha}. (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.

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

    Output

    (10000, 12)
    0
  2. 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"]), then print(df["churn"].sum()) and print(df["churn"].mean()).
    Show one possible solution
    Python, continues from the cells above
    df = df.drop(columns=["customer_id"])
    
    print(df["churn"].sum())
    print(df["churn"].mean())

    Output

    2037
    0.2037
  3. 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 with 0.75 for q3, then upper = 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 above
    q1 = 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
  4. 8.Encode gender as 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 above
    df["gender"] = df["gender"].map({"Female": 0, "Male": 1})
    
    print(df["gender"].sum())

    Output

    5457
  5. 9.One-hot encode country and products_number inside the table, with drop_first=True and dtype=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), then print(df.columns.tolist()).
    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(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.

  1. 10.Make X (all columns without churn) and y (churn). Split them with test_size=0.3 and random_state=1. Print the shapes of X_train and X_test on 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"], then X_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 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(X_train.shape, X_test.shape)

    Output

    (7000, 13) (3000, 13)
  2. 11.Scale the features with a StandardScaler called scaler into X_train_scaled and X_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 and scaler.transform(X_test) for the test data, then print(round(X_test_scaled.max(), 2)). If your number differs, check test_size=0.3 and random_state=1 in Step 10.
    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(round(X_test_scaled.max(), 2))

    Output

    12.57
  3. 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 in y_test: print(round(1 - y_test.mean(), 4)).
    Show one possible solution
    Python, continues from the cells above
    print(round(1 - y_test.mean(), 4))

    Output

    0.791
  4. 13.Train a LogisticRegression called model on 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), then model.score(X_train_scaled, y_train) and model.score(X_test_scaled, y_test).
    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)
    
    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.

  1. 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], then print(leaving[:3].round(3)) and print((leaving >= 0.5).sum()).
    Show one possible solution
    Python, continues from the cells above
    leaving = 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
  2. 15.Train a LogisticRegression with C=0.001 and print its test accuracy, rounded to 4 decimals. Is this C a good choice? This step continues from Step 13.
    Show a hint
    strong = LogisticRegression(C=0.001), fit, then print(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 above
    strong = LogisticRegression(C=0.001)
    strong.fit(X_train_scaled, y_train)
    
    print(round(strong.score(X_test_scaled, y_test), 4))

    Output

    0.8157
  3. 16.Train a LogisticRegression with class_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, then score and print(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 above
    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.7673
    1001

15Check yourself

Twelve questions. Every question has one right answer.

Question 1

1.What does logistic regression predict?

Question 2

2.Why is linear regression a poor choice for a target of 0 and 1?

Question 3

3.What is the sigmoid of 0?

Question 4

4.What does logistic regression assume to be a linear function of the features?

Question 5

5.Which function turns the scores of three classes into probabilities that add up to 1?

Question 6

6.A customer left (y=1y = 1). Which prediction has the largest cross-entropy loss?

Question 7

7.Why is the cross-entropy preferred to the squared error for training a classifier?

Question 8

8.What does a small value of C mean?

Question 9

9.What does model.predict_proba(X_test)[:, 1] give for a model with two classes?

Question 10

10.In a data set 80 percent of the rows belong to class 0. A model has an accuracy of 0.81. How good is it?

Question 11

11.The solver prints a ConvergenceWarning. What is the best first step?

Question 12

12.What does class_weight="balanced" do?

0 of 12 answered.

16Summary

Summary
FormulaMeaning
Scorez=w0+w1x1+⋯+wpxpz = w_0 + w_1 x_1 + \dots + w_p x_pa weighted sum, as in linear regression
Sigmoidp=11+e−zp = \frac{1}{1 + e^{-z}}turns the score into a probability (two classes)
Softmaxpk=ezksum of all ezp_k = \frac{e^{z_k}}{\text{sum of all } e^{z}}probabilities for three or more classes
Log-oddsln⁡p1−p=z\ln \frac{p}{1 - p} = zwhat the model assumes to be linear
Cross-entropy−[yln⁡(p)+(1−y)ln⁡(1−p)]-\left[ y \ln(p) + (1 - y) \ln(1 - p) \right]the loss: minus the logarithm of the probability of the true class
Decisionclass 1 if p≥0.5p \ge 0.5the same as z≥0z \ge 0
Summary
CodeWhat 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

  1. Logistic regression is a classifier. It predicts a probability and turns it into a class.
  2. A linear score, then the sigmoid (two classes) or the softmax (more classes).
  3. It is trained with the cross-entropy and judged, in this lesson, with the accuracy.
  4. Look at the classes of the target first, and compare every accuracy with the baseline.
  5. Scale the features: the model is regularized, and its solver walks down a loss.
  6. A small C is a strong regularization. Choose it with cross-validation.
  7. 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.