Chapter 6 // Classification

Logistic Regression.

A student studied for four and a half hours. How likely are they to pass?

Reading time
20 min
Data

Part I predicted numbers. This part predicts categories: pass or fail, spam or not, ill or healthy. The first model for the job is a small change to the one you already know, and it is the building block of every neural network later in the book.

The data is the exam class again, all eighteen students this time, and for each one a single fact: did they pass?

A line is the wrong shape

The obvious first move is to reuse linear regression. Write a pass as 1 and a fail as 0, and fit a straight line through those numbers. The height of the line can then be read as the chance of passing.

Figure

Fitting a yes/no answer

passed = 1failed = 03 hours, passed4 hours, passed5 hours, passed5.5 hours, passed6 hours, passed6.5 hours, passed7 hours, passed8 hours, passed8.5 hours, passed9 hours, passed0.5 hours, failed1 hours, failed1.5 hours, failed2 hours, failed2.5 hours, failed3 hours, failed3.5 hours, failed4.5 hours, failed
  • Passed (filled)
  • Failed (hollow)
  • Straight-line fit
Prediction at 0 hours
-13%
Prediction at 4.5 hours
56%
Prediction at 9 hours
124%
Each student sits at 1 if they passed and 0 if they failed. Try it: read the straight line's predictions at 0 hours and at 9 hours. Then switch to the S-shaped curve.

The line gives a student who did no studying a −13% chance of passing, and one who studied nine hours a 124% chance. Neither number means anything. A has to stay between 0 and 1, and a straight line never stops.

What the data calls for is a curve that stays near 0 for a while, rises through the middle, and levels off near 1. The second option in the figure has that shape.

Squashing a line into a probability

We do not need to give up the line. We keep it, and pass its output through a function that squashes any number into the range 0 to 1. That function is the , written σ\sigma:

p=σ(w x+b)whereσ(z)=11+e−zp = \sigma(w\,x + b) \qquad\text{where}\qquad \sigma(z) = \frac{1}{1 + e^{-z}}

chance of passing = sigmoid of (w × hours + b)

The inside, wx+bw x + b, is the same line as in the linear regression chapter. Call its value the score. The sigmoid turns the score into a probability:

Score wx+bw x + b−4−2024
Probability2%12%50%88%98%

A score of zero means “could go either way”. Large positive scores mean “almost certainly yes”, and large negative ones “almost certainly no”. This model is called . Despite the name, it is used for classification.

Figure

What the two numbers do

3 hours, passed4 hours, passed5 hours, passed5.5 hours, passed6 hours, passed6.5 hours, passed7 hours, passed8 hours, passed8.5 hours, passed9 hours, passed0.5 hours, failed1 hours, failed1.5 hours, failed2 hours, failed2.5 hours, failed3 hours, failed3.5 hours, failed4.5 hours, failed
Score at 4.5 h: w·x + b
-1.30
Chance of passing at 4.5 h
21%
Curve crosses 50% at
6.7 hours
0.60
-4.0
The curve is the sigmoid of w × hours + b. The dashed lines mark where it crosses 50%. Try it: raise w and watch the rise get sharper. Then change b and watch the whole curve slide sideways. Try to make the curve agree with the dots.

Scoring a probability

To fit the curve we need a loss, and squared error is a poor fit for probabilities. Think about what a good prediction is here. If a student passed, the model should have given a high chance of passing. If they failed, a low one. So score the model by the probability it gave to what actually happened, and punish it more the smaller that was.

The standard choice is the : take that probability and compute its negative logarithm.

Model gave what happened a chance of90%50%10%1%
Loss0.110.692.304.61

A confident, correct prediction costs almost nothing. A coin-flip costs 0.69. A confident, wrong prediction is punished severely, and the cost keeps growing without limit as the model becomes more sure of the wrong answer.

Figure

The cost of being confidently wrong

Model said: chance of a pass
70%
Chance it gave to what happened
70%
Loss = −log of that
0.36
Drag the orange dot along the curve.
The curve is the loss for one student, for every probability the model might have predicted. Try it: with 'passed' selected, drag the dot toward the left edge and watch the loss. Then switch to 'failed' and see the curve flip.

For a whole dataset the loss is the average over all the students:

L=−1n∑i=1n[ yilog⁡pi+(1−yi)log⁡(1−pi)]L = -\frac{1}{n}\sum_{i=1}^{n}\Big[\,y_i \log p_i + (1 - y_i)\log(1 - p_i)\Big]

The formula looks heavy, but it is only the table above written compactly. When yi=1y_i = 1 the second term vanishes and the loss is −log⁡pi-\log p_i. When yi=0y_i = 0 the first vanishes and the loss is −log⁡(1−pi)-\log(1 - p_i).

Checkpoint

Two models predict for a student who passed. Model A said 60% chance of a pass; model B said 99%. A second student failed: A said 40%, B said 99%. Which model has the lower total log loss?

Fitting the curve

Unlike the straight line, this model has no formula for the best ww and bb. That is no obstacle, because gave us a method that needs only a loss and its slope. Start with w=0w = 0 and b=0b = 0, which predicts 50% for everyone and has a loss of 0.69, and walk downhill.

The slopes turn out to be almost the same as for linear regression:

∂L∂w=1n∑i(pi−yi) xi∂L∂b=1n∑i(pi−yi)\frac{\partial L}{\partial w} = \frac{1}{n}\sum_i (p_i - y_i)\,x_i \qquad \frac{\partial L}{\partial b} = \frac{1}{n}\sum_i (p_i - y_i)

Again it is “prediction minus truth, times the input, averaged”. The only difference is that the prediction pip_i now comes out of the sigmoid.

Figure

Gradient descent finds the curve

3 hours, passed4 hours, passed5 hours, passed5.5 hours, passed6 hours, passed6.5 hours, passed7 hours, passed8 hours, passed8.5 hours, passed9 hours, passed0.5 hours, failed1 hours, failed1.5 hours, failed2 hours, failed2.5 hours, failed3 hours, failed3.5 hours, failed4.5 hours, failed
  • Current curve
  • Best possible curve
Step
0
Log loss
0.693
50% point
–
Students right
10 of 18
0.50

Lowest possible log loss on these students is 0.259.

The orange curve is the current model. The dashed curve is where it is heading. Try it: press Step a few times, then Run. Watch the loss fall from 0.693, and the 50% point settle.

The run settles on w=1.56w = 1.56 and b=−6.03b = -6.03, with a loss of 0.259. That answers the opening question:

p=σ(1.56×4.5−6.03)=σ(0.99)≈0.73p = \sigma(1.56 \times 4.5 - 6.03) = \sigma(0.99) \approx 0.73

A student who studied four and a half hours has about a 73% chance of passing. The straight-line model could only say “pass”. This one says how sure it is.

ExampleTwo students, by hand

Use the fitted model, w=1.56w = 1.56 and b=−6.03b = -6.03.

A student who studied 3 hours. The score is 1.56×3−6.03=−1.351.56 \times 3 - 6.03 = -1.35, and the sigmoid turns it into 1/(1+e1.35)≈0.2061 / (1 + e^{1.35}) \approx 0.206. The model gives about a 21% chance of passing. If the student failed, the loss is −ln⁡(1−0.206)≈0.23-\ln(1 - 0.206) \approx 0.23. If they passed, it is −ln⁡(0.206)≈1.58-\ln(0.206) \approx 1.58.

A student who studied 6 hours. The score is 3.333.33 and the probability is about 0.965. If the student passed, the loss is −ln⁡(0.965)≈0.04-\ln(0.965) \approx 0.04. If they failed, it is −ln⁡(1−0.965)≈3.37-\ln(1 - 0.965) \approx 3.37.

Being this sure and wrong costs almost a hundred times as much as being this sure and right. That is what pushes the model away from overconfidence.

From probability to decision

Often a probability is not enough and a decision is needed: admit or not, flag or not. The usual rule is to answer yes when the probability is at least 50%. That cut-off is called the .

For our model, the probability reaches 50% at 3.85 hours. Students above that are predicted to pass, and the rule is right about 16 of the 18. The point where the answer flips is the .

With two features the same idea gives a boundary that is a line. Here are forty students with both their hours of study and their hours of sleep.

Figure

A boundary in two dimensions

5.5 h study, 7.9 h sleep, passed5.3 h study, 8.3 h sleep, passed6 h study, 7.2 h sleep, passed5.6 h study, 9.2 h sleep, passed5.9 h study, 8.2 h sleep, passed2.3 h study, 8.8 h sleep, passed7.2 h study, 4.2 h sleep, passed8.6 h study, 9.3 h sleep, passed5.1 h study, 4.8 h sleep, passed7.9 h study, 4.1 h sleep, passed6.2 h study, 6 h sleep, passed6.4 h study, 4 h sleep, passed4.8 h study, 8.8 h sleep, passed6.4 h study, 7.6 h sleep, passed3.8 h study, 8 h sleep, passed3.1 h study, 4 h sleep, failed1.9 h study, 3.6 h sleep, failed3.4 h study, 6.6 h sleep, failed3.2 h study, 8.9 h sleep, failed2.6 h study, 4.3 h sleep, failed2.9 h study, 5.3 h sleep, failed3.6 h study, 5 h sleep, failed2 h study, 3.6 h sleep, failed1.8 h study, 4.1 h sleep, failed1.8 h study, 5.8 h sleep, failed1.1 h study, 7.9 h sleep, failed4.2 h study, 3.9 h sleep, failed0.8 h study, 7.1 h sleep, failed4.3 h study, 4.6 h sleep, failed1.1 h study, 5 h sleep, failed4.9 h study, 5.3 h sleep, failed5.1 h study, 4.8 h sleep, failed1 h study, 5.7 h sleep, failed2.1 h study, 7.8 h sleep, failed1.7 h study, 7 h sleep, failed2.2 h study, 4.7 h sleep, failed1.5 h study, 4 h sleep, failed1.1 h study, 3.5 h sleep, failed3.4 h study, 5.9 h sleep, failed1.3 h study, 6.1 h sleep, failed
  • Passed (filled)
  • Failed (hollow)
  • Decision boundary
  • Darker = higher predicted chance of a pass
Predict a pass when chance ≥
50%
Students right
37 of 40
Fails predicted to pass
1
Passes predicted to fail
2
50%
The shading is the model's predicted chance of a pass. The dark line is where that chance equals the threshold. Try it: move the threshold up to 80%, then down to 20%. Watch the line slide, and the two kinds of mistake trade places.

Two things are worth noticing. First, the boundary is always straight, however the threshold moves. Logistic regression is a : it can only divide the plane with a straight cut. Second, moving the threshold never makes the model better or worse at telling the classes apart. It only changes which mistake it prefers to make. Choosing well between those mistakes is the subject of the next chapter.

Checkpoint

A model gives a patient a 30% chance of having a serious illness. With a threshold of 50% it answers 'healthy'. What is the best response?

In code

import numpy as np
from sklearn.linear_model import LogisticRegression

hours  = np.array([0.5, 1, 1.5, 2, 2.5, 3, 3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5, 7, 8, 8.5, 9])
passed = np.array([0,   0, 0,   0, 0,   0, 1, 0,   1, 0,   1, 1,   1, 1,   1, 1, 1,   1])
X = hours.reshape(-1, 1)

# penalty=None fits plain logistic regression, with no regularization.
model = LogisticRegression(penalty=None).fit(X, passed)
print(model.coef_[0][0], model.intercept_[0])      # 1.56  -6.03

print(model.predict_proba([[4.5]])[0, 1])          # 0.73: the chance of a pass
print(model.predict([[4.5]]))                      # [1]: the decision at a 50% threshold
print(model.score(X, passed))                      # 0.889: 16 of 18 right

predict_proba gives the probability; predict applies the 50% threshold for you. By default scikit-learn adds a ridge penalty to logistic regression, which is why it is switched off here to match the chapter.

Key Takeaways

  • For a yes/no question, predict a probability. A straight line cannot do that; a line passed through the sigmoid can.
  • Log loss scores the probability given to what actually happened, and punishes confident mistakes hardest.
  • There is no formula for the best weights, so the model is fitted by gradient descent. The gradient has the same form as for linear regression.
  • A threshold turns the probability into a decision. 50% is a default, not a law.
  • The decision boundary of logistic regression is always straight.
You can now
  • Turn a score into a probability with the sigmoid.
  • Work out the log loss of a prediction and say why confident mistakes cost so much.
  • Find where a model’s decision boundary lies for a given threshold.
  • Read a weight as a multiplier on the odds.

Exercises

Try each one before opening its solution. Getting stuck for a few minutes is where most of the learning happens.

Exerciseby hand

Work out the sigmoid of 0, of 2 and of −2. What do the last two answers add up to, and why?

Hint

The sigmoid is 1/(1+e−z)1 / (1 + e^{-z}). Note that e2≈7.39e^{2} \approx 7.39.

Solution

σ(0)=1/(1+1)=0.5\sigma(0) = 1 / (1 + 1) = 0.5.

σ(2)=1/(1+e−2)=1/1.135≈0.88\sigma(2) = 1 / (1 + e^{-2}) = 1 / 1.135 \approx 0.88.

σ(−2)=1/(1+e2)=1/8.39≈0.12\sigma(-2) = 1 / (1 + e^{2}) = 1 / 8.39 \approx 0.12.

The last two add up to 1. The sigmoid is symmetric: a score of −z-z gives the probability that a score of zz leaves over. Flipping the sign of the score swaps “yes” and “no”.

Exerciseby hand

The fitted model is w=1.56w = 1.56, b=−6.03b = -6.03. With a threshold of 50%, how many hours of study put a student exactly on the boundary? Where does the boundary move if the threshold is raised to 73%?

Hint

A probability of 50% means the score wx+bwx + b is zero. The chapter worked out which hours give 73%.

Solution

A probability of 50% means a score of zero: 1.56x−6.03=01.56x - 6.03 = 0, so x=6.03/1.56≈3.87x = 6.03 / 1.56 \approx 3.87 hours. Students above that are predicted to pass.

The chapter worked out that 4.5 hours gives a probability of 73%. So with a threshold of 73% the boundary sits at 4.5 hours. Raising the threshold moves the boundary towards the “yes” side, and fewer students are predicted to pass.

Exerciseby hand

A model makes three predictions. It gives a student who passed a 90% chance of passing, another student who passed a 60% chance, and a student who failed a 20% chance of passing. What is the log loss of each prediction, and the average? How does that compare with a model that says 50% for everyone?

Hint

Take minus the logarithm of the probability given to what actually happened. For the student who failed, that is 0.8.

Solution

Log loss is minus the logarithm of the probability given to what actually happened.

  • Passed, given 0.9: −ln⁡(0.9)≈0.105-\ln(0.9) \approx 0.105
  • Passed, given 0.6: −ln⁡(0.6)≈0.511-\ln(0.6) \approx 0.511
  • Failed, so the probability given to failing was 0.8: −ln⁡(0.8)≈0.223-\ln(0.8) \approx 0.223

The average is about 0.28. A model that always says 50% scores −ln⁡(0.5)≈0.693-\ln(0.5) \approx 0.693 on every example. That is the starting loss in the gradient descent figure, and any useful model must beat it.

Exerciseby hand

With w=1.56w = 1.56, each extra hour multiplies the odds of passing by e1.56≈4.76e^{1.56} \approx 4.76. At 3.87 hours the odds are even, 1 to 1. What are the odds, and the probability, one hour later?

Hint

Odds of 4.76 to 1 mean 4.76 passes for every fail. Turn that into a share of the total.

Solution

The odds become 4.76 to 1. Odds of 4.76 to 1 mean 4.76 passes for every fail, so the probability is 4.76/(4.76+1)≈0.834.76 / (4.76 + 1) \approx 0.83.

You can check with the sigmoid. One hour beyond the boundary the score is 1.561.56, and σ(1.56)≈0.83\sigma(1.56) \approx 0.83.

Notice that the same extra hour does not add a fixed amount of probability. From 50% it added 33 points. From 83% another hour would add far fewer, because the curve flattens.

Exercisewith the figure

In the figure “What the two numbers do”, set ww to about 1.55 and bb to −6.0, close to the fitted values. Where does the curve cross 50%? Now double ww to about 3.1 and adjust bb until the crossing is back in the same place. What changed about the curve, and what would that mean for the model’s predictions?

Hint

The crossing is where wx+b=0wx + b = 0. Doubling ww means bb must double too.

Solution

The curve crosses 50% where wx+b=0wx + b = 0, at about 3.9 hours. With ww doubled, bb has to be about −12 to keep the crossing there.

The crossing is the same and the curve is much steeper: it goes from nearly 0% to nearly 100% within about an hour. The model would make the same yes-or-no decisions and be far more confident about them. Whether that confidence is deserved is what the log loss checks, which is why the fitted model settled on the gentler slope.

Going further

When the classes separate perfectly

If one cut-off divides the passes from the fails with no mistakes, the data is , and something odd happens. The model can always lower the loss a little more by making the curve steeper, so the weights grow without limit and training never settles. A small ridge penalty from fixes it, which is one reason libraries apply one by default.

More than two classes

For three or more categories the sigmoid is replaced by a function called softmax, which turns one score per class into probabilities that add up to 1. The loss is the same idea: minus the log of the probability given to the correct class. Softmax appears in the neural network part of the book.

What the weight means

In linear regression a weight is “points per hour”. Here the score wx+bw x + b is the logarithm of the odds of passing, so each extra hour multiplies the odds by ewe^{w}. With w=1.56w = 1.56 that is a factor of about 4.8 per hour.

References and further reading

  • G. James, D. Witten, T. Hastie and R. Tibshirani, An Introduction to Statistical Learning, chapter 4. Free at statlearning.com.
  • H. Kinsley and D. Kukieła, Neural Networks from Scratch in Python, chapter 16, nnfs.io.
  • Google, Machine Learning Crash Course: Logistic regression.

Last updated Spotted a mistake? Suggest an editWhat changed

In this chapter
  1. Top of the chapter
  2. 6.1A line is the wrong shape
  3. 6.2Squashing a line into a probability
  4. 6.3Scoring a probability
  5. 6.4Fitting the curve
  6. 6.5From probability to decision
  7. 6.6In code
  8. Exercises
Search

    The Book of Machine Learning
    Search
    Reading settings
    Text size
    Colours

    Saved in this browser only.

    Keyboard shortcuts
    /
    Search the book
    ← →
    Previous and next chapter
    g
    Glossary
    c
    Table of contents
    e
    Jump to the exercises
    t
    Reading settings
    ?
    Show this list
    Esc
    Close a window or pop-in