# Chapter 6: Logistic Regression

> Predicting a yes or no answer as a probability. Opening question: A student studied for four and a half hours. How likely are they to pass?

From *The Book of Machine Learning*, a free interactive machine learning textbook. Interactive version, with figures to use: https://thebookofml.com/logistic-regression/

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.

> **Interactive figure: Fitting a yes/no answer.** 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.
> (Use it at https://thebookofml.com/logistic-regression/)

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 probability 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 sigmoid, written $\sigma$:

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

The inside, $w x + b$, is the same line as in the [linear regression chapter](/linear-regression/). Call its value the score. The sigmoid turns the score into a probability:

| Score $w x + b$ | −4 | −2 | 0 | 2 | 4 |
|---|---|---|---|---|---|
| Probability | 2% | 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 logistic regression. Despite the name, it is used for classification.

> **Interactive figure: What the two numbers do.** 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.
> (Use it at https://thebookofml.com/logistic-regression/)

**Note:** The curve crosses 50% exactly where the score is zero, which is at x = −b / w.

## 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 log loss: take that probability and compute its negative logarithm.

| Model gave what happened a chance of | 90% | 50% | 10% | 1% |
|---|---|---|---|---|
| Loss | 0.11 | 0.69 | 2.30 | 4.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.

> **Interactive figure: The cost of being confidently wrong.** 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.
> (Use it at https://thebookofml.com/logistic-regression/)

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

$$
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 $y_i = 1$ the second term vanishes and the loss is $-\log p_i$. When $y_i = 0$ the first vanishes and the loss is $-\log(1 - p_i)$.

**Check your understanding:** 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?

- Model B, because it was more confident — B was superb on the first student and catastrophic on the second: giving 1% to what happened costs 4.61.
- Model A **(correct)** — A gave 60% to what happened both times, costing 0.51 + 0.51. B costs 0.01 + 4.61. One confident mistake outweighs everything else.
- They tie — A totals about 1.02 and B about 4.62. Log loss punishes confident errors very heavily.

## Fitting the curve

Unlike the straight line, this model has no formula for the best $w$ and $b$. That is no obstacle, because [chapter 3](https://thebookofml.com/gradient-descent/) gave us a method that needs only a loss and its slope. Start with $w = 0$ and $b = 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:

$$
\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 $p_i$ now comes out of the sigmoid.

> **Interactive figure: Gradient descent finds the curve.** 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.
> (Use it at https://thebookofml.com/logistic-regression/)

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

$$
p = \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.

**Example: Two students, by hand**

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

**A student who studied 3 hours.** The score is $1.56 \times 3 - 6.03 = -1.35$, and the sigmoid turns it into $1 / (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) \approx 0.23$. If they passed, it is $-\ln(0.206) \approx 1.58$.

**A student who studied 6 hours.** The score is $3.33$ and the probability is about 0.965. If the student passed, the loss is $-\ln(0.965) \approx 0.04$. If they failed, it is $-\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 threshold.

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 decision boundary.

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.

> **Interactive figure: A boundary in two dimensions.** 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.
> (Use it at https://thebookofml.com/logistic-regression/)

Two things are worth noticing. First, the boundary is always straight, however the threshold moves. Logistic regression is a linear classifier: 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.

**Check your understanding:** 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?

- Trust the answer, since 30% is below 50% — The 50% threshold is only a default. A missed illness may cost far more than an unnecessary test.
- Lower the threshold for this task **(correct)** — When missing a yes is costly, flag cases at a lower probability. The threshold should reflect the cost of each kind of mistake.
- Retrain the model until it says more than 50% — The probability may be accurate. The decision rule is what needs changing, not the model.

**Common mistake: Expecting a curved boundary**

The S-shape is in the probability, not in the boundary. Along any straight path that crosses the boundary, the probability rises in an S. The boundary itself, the set of places where the probability is exactly 50%, is a straight line however the weights are set. If two classes can only be separated by a curve, plain logistic regression will not find it. You would need to add features, such as squares of the inputs, or use one of the methods from the coming chapters.

## In code

```python
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**.

## What you should now be able to do

- 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

### Exercise (by 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})$. Note that $e^{2} \approx 7.39$.

**Solution:**

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

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

$\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$ gives the probability that a score of $z$ leaves over. Flipping the sign of the score swaps "yes" and "no".

### Exercise (by hand)

The fitted model is $w = 1.56$, $b = -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 + 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 = 0$, so $x = 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.

### Exercise (by 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) \approx 0.105$
- Passed, given 0.6: $-\ln(0.6) \approx 0.511$
- Failed, so the probability given to failing was 0.8: $-\ln(0.8) \approx 0.223$

The average is about 0.28. A model that always says 50% scores $-\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.

### Exercise (by hand)

With $w = 1.56$, each extra hour multiplies the odds of passing by $e^{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) \approx 0.83$.

You can check with the sigmoid. One hour beyond the boundary the score is $1.56$, and $\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.

### Exercise (with the figure)

In the figure "What the two numbers do", set $w$ to about 1.55 and $b$ to −6.0, close to the fitted values. Where does the curve cross 50%? Now double $w$ to about 3.1 and adjust $b$ 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 = 0$. Doubling $w$ means $b$ must double too.

**Solution:**

The curve crosses 50% where $wx + b = 0$, at about 3.9 hours. With $w$ doubled, $b$ 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 separable, 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 [the last chapter](https://thebookofml.com/regularization/) 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 $w x + b$ is the logarithm of the odds of passing, so each extra hour multiplies the odds by $e^{w}$. With $w = 1.56$ that is a factor of about 4.8 per hour.

## References

- G. James, D. Witten, T. Hastie and R. Tibshirani, *An Introduction to Statistical Learning*, chapter 4. Free at [statlearning.com](https://www.statlearning.com).
- H. Kinsley and D. Kukieła, *Neural Networks from Scratch in Python*, chapter 16, [nnfs.io](https://nnfs.io).
- Google, *Machine Learning Crash Course*: [Logistic regression](https://developers.google.com/machine-learning/crash-course/logistic-regression).

## Next

Choosing a threshold raised a question this chapter did not settle. A classifier can be wrong in two different ways, and they rarely cost the same. The next chapter is about measuring a classifier properly.
