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.
Fitting a yes/no answer
- Passed (filled)
- Failed (hollow)
- Straight-line fit
- Prediction at 0 hours
- -13%
- Prediction at 4.5 hours
- 56%
- Prediction at 9 hours
- 124%
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
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
chance of passing = sigmoid of (w × hours + b)
The inside, , is the same line as in the linear regression chapter. Call its value the score. The sigmoid turns the score into a probability:
| Score | −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
What the two numbers do
- 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
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
| 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.
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
For a whole dataset the loss is the average over all the students:
The formula looks heavy, but it is only the table above written compactly. When the second term vanishes and the loss is . When the first vanishes and the loss is .
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 and . That is no obstacle, because
The slopes turn out to be almost the same as for linear regression:
Again it is “prediction minus truth, times the input, averaged”. The only difference is that the prediction now comes out of the sigmoid.
Gradient descent finds the curve
- Current curve
- Best possible curve
- Step
- 0
- Log loss
- 0.693
- 50% point
- –
- Students right
- 10 of 18
Lowest possible log loss on these students is 0.259.
The run settles on and , with a loss of 0.259. That answers the opening question:
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.
Use the fitted model, and .
A student who studied 3 hours. The score is , and the sigmoid turns it into . The model gives about a 21% chance of passing. If the student failed, the loss is . If they passed, it is .
A student who studied 6 hours. The score is and the probability is about 0.965. If the student passed, the loss is . If they failed, it is .
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.
A boundary in two dimensions
- 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
Two things are worth noticing. First, the boundary is always straight, however the threshold moves. Logistic regression is a
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.
- 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.
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 . Note that .
Solution
.
.
.
The last two add up to 1. The sigmoid is symmetric: a score of gives the probability that a score of leaves over. Flipping the sign of the score swaps “yes” and “no”.
The fitted model is , . 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 is zero. The chapter worked out which hours give 73%.
Solution
A probability of 50% means a score of zero: , so 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.
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:
- Passed, given 0.6:
- Failed, so the probability given to failing was 0.8:
The average is about 0.28. A model that always says 50% scores on every example. That is the starting loss in the gradient descent figure, and any useful model must beat it.
With , each extra hour multiplies the odds of passing by . 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 .
You can check with the sigmoid. One hour beyond the boundary the score is , and .
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.
In the figure “What the two numbers do”, set to about 1.55 and to −6.0, close to the fitted values. Where does the curve cross 50%? Now double to about 3.1 and adjust 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 . Doubling means must double too.
Solution
The curve crosses 50% where , at about 3.9 hours. With doubled, 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
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 is the logarithm of the odds of passing, so each extra hour multiplies the odds by . With 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.