Lesson 4 · Learning from data
Logistic regression and classification
The problem
The shop wants to text customers whose pizza will probably be late. So for each new order it needs a yes-or-no answer: late, or on time?
That's a different kind of question from "how many minutes?". The answer is one of a fixed set of categories, not a number. Predicting a category is classification. With two categories, as here, it's binary classification. The two categories are called classes, and we code them as numbers: 1 for late, 0 for on time.
Here is the shop's data: 200 past deliveries. Each has two features, the distance and the hour it was sent. Each also has a label: late or not. Another 200 deliveries are held back to check the model on orders it never trained on. Lesson 5 explains why that matters.
Long trips tend to be late. So do trips sent around 19:00, when the roads are jammed. A good model should output a probability of being late, between 0 and 1. Then the shop can decide what's worth a text.
A linear model can't do that directly. Its weighted sum can be any number at all, like or . We need a way to squash it into the range 0 to 1.
From a score to a probability
Call the linear model's output the score, . A high score should mean "probably late", and a low one "probably on time". Then pass it through this function:
This is the sigmoid, written (sigma). For a large positive , is tiny, so is close to 1. For a large negative , is huge, so is close to 0. At , , so . The Softmax lesson met this same curve as softmax with two options.
Putting the two together gives logistic regression:
The figure uses weights trained later in this lesson, rounded: 0.64 per km, per hour, and an intercept of 4.9. Move the delivery and watch its score slide along the curve.
Score z = 0.64 × 2.0 − 0.37 × 19.0 + 4.9 = −0.85
P(late) = σ(−0.85) = 0.299 → predict on time
Things to notice:
- Longer trips raise the score, since their weight is positive. Later hours lower it.
- In the middle, near , a small change in the score moves the probability a lot. Out at the ends it barely moves: a score of 6 and a score of 8 both mean "almost surely late".
- gives exactly 0.5. That's where the answer flips.
Worked example
A 2 km delivery sent at 19:00
Weighted sum: for the distance, and for the hour.
The decision boundary
The model predicts late when . Since exactly when , that's the same as
The points where split the plane into a "late" side and an "on time" side. That dividing line is the model's decision boundary.
With two features, is a straight line. Solve it for the distance: . At 19:00 that's km. So at 19:00 the model calls anything over 3.3 km late. Our 2 km delivery falls on the "on time" side.
The 0.5 cut-off is a choice. A shop that hates missing a late delivery might text at 0.3 instead. Lesson 7 covers how to pick it (decision thresholds).
Predict first
You double every weight and the intercept. Does the decision boundary move?
Weights and intercept × 1.00
A 5 km delivery at 18:00: score 1.45, P(late) = 0.810
The line where P(late) = 0.5 doesn't move. Only the width of the blurry band around it changes.
Things to notice:
- The boundary line never moves, whatever the multiplier.
- At 0.25×, the shading is a wide, soft blur. Every delivery gets a probability near 0.5.
- At 5×, the shading is almost two flat colours. The model is nearly certain about every delivery, including the ones it gets wrong.
Scoring probabilities: cross-entropy
To train the model, we need a loss that scores its probabilities. The squared error from Lesson 2 is one option: for a late delivery () given , it's . It can never be more than 1.
The usual choice is different. Take the probability the model gave to what happened, and score it with . For a late delivery, that's . For an on-time one, it's .
This is the surprise from the Entropy lesson: a sure, right answer costs 0, and a sure, wrong one costs a lot. Logs here are natural logs (log).
Worked example
Two losses for one late delivery
The 2 km delivery at 19:00 was late, and the model said .
The model gives this late delivery P(late) = 0.30
Cross-entropy (solid): −log 0.30 = 1.20 · push 0.700
Squared error (dashed): (1 − 0.30)² = 0.49 · push 0.294
Drag the dot on the axis towards 0: the model gets more sure, and more wrong.
Things to notice:
- On the Loss tab, cross-entropy shoots up as goes to 0. Squared error flattens out at 1. It treats "sure and wrong" as hardly worse than "unsure".
- On the Push tab, cross-entropy's push on the score is : the more wrong, the harder it pushes. Near it pushes with almost full force.
- Squared error's push falls to 0 as goes to 0. A model that's sure and wrong gets almost no signal to change. Training stalls on exactly the mistakes that matter most.
Why does squared error go quiet? Its push includes the sigmoid's slope, , which is tiny out at the flat ends of the S. Cross-entropy's cancels that slope exactly, leaving .
The maths
Over examples, with labels (1 or 0) and predictions , the loss is
where each example's loss is
This is the cross-entropy loss, also called log loss or binary cross-entropy. Read it back: for each example, one of the two terms is zero. If , only is left. If , only . So it's the average surprise at the true labels: the cross-entropy between the labels and the model's probabilities.
Its gradient is short. The slope with respect to each example's score is , so
It has the same shape as linear regression's gradient: each example's miss times its features. Here the miss is , a probability minus a label.
Training the boundary
There's no formula for the best weights this time (the aside below says why). So train with gradient descent, exactly as in the last lesson.
One change first: rescale each feature to have mean 0 and standard deviation 1, using the training deliveries. The hours run from 17 to 23 and the distances from 0 to 8. Without rescaling, the loss would be a long, narrow valley, as in Lesson 3's aside. The figure converts the weights back to km and hours for display.
Step 0 · validation accuracy 53.5%
score = 0.00 × km + 0.00 × hour + 0.00 · learning rate 0.5, all 200 deliveries per step
Things to notice:
- At step 0 every weight is 0, so every delivery gets . The loss starts at .
- The boundary is a straight line the whole time. Training only tilts and slides it.
- The training loss settles at 0.509. Accuracy settles at 75% on the training deliveries and 76% on the validation ones. About 1 delivery in 4 is on the wrong side.
- The mistakes come in two groups. Around 19:00, short trips run late, and the line misses them. At 17:00 and after 21:00, the line calls medium trips late, though they arrive on time. The rule dips down at 19:00 and back up after. A straight line can only split the difference.
Data whose classes a straight line can split perfectly is linearly separable. The rush-hour data isn't, and not only because of the 5% of flipped labels. The rule that made it is a curve. Even the best possible straight line gets only 78% of the training deliveries right. So no amount of training lifts logistic regression much past 76% here.
DeeperWhy there's no exact formula for the weightsSetting the gradient to zero gives equations with the weights stuck inside the sigmoid. · 2 min
For linear regression, setting the gradient to zero gave the normal equations: a linear system you can solve.
Try the same here. The best weights must make the gradient zero:
The unknowns and sit inside the sigmoid, inside a sum of 200 terms. No algebra pulls them out. So you search.
The search is safe, though. The cross-entropy of logistic regression is convex in the weights: a single bowl with no false bottoms. Gradient descent can't get stuck in the wrong valley. (Squared error with a sigmoid is not convex, which is another reason to avoid it.)
One catch: if the data were linearly separable, the loss would keep falling as the weights grew. It would never reach a bottom, so the weights would grow forever, as in the weight-multiplier figure at 5× and beyond. A small penalty on large weights stops that. scikit-learn adds one by default, as the code below shows.
In scikit-learn
scikit-learn's LogisticRegression is an estimator like LinearRegression: make it, .fit, then predict.
x_train, y_train, x_val, y_val, mean, std = standardised_rush_hour() # (200, 2), (200,) each
model = LogisticRegression() # defaults: an L2 penalty with C=1, fitted by the lbfgs solver
model.fit(x_train, y_train)
print(model.coef_, model.intercept_) # [[ 1.37 -0.56]] [0.05]: on standardised inputs
print(model.score(x_val, y_val)) # 0.76: validation accuracy
new = (np.array([[2.0, 19.0]]) - mean) / std # a 2 km delivery sent at 19:00
print(model.predict_proba(new)) # [[0.69 0.31]]: P(on time), P(late)
print(model.predict(new)) # [0]: "on time", since P(late) < 0.5
plain = LogisticRegression(C=np.inf).fit(x_train, y_train) # no penalty at all
print(plain.coef_, plain.intercept_, plain.score(x_val, y_val)) # [[ 1.43 -0.59]] [0.06] 0.76[[ 1.36768451 -0.55555101]] [0.05204448]
0.76
[[0.68811626 0.31188374]]
[0]
[[ 1.43252155 -0.58829699]] [0.05567703] 0.76What to notice:
- The features are rescaled with the training mean and standard deviation, as in the figure. The validation deliveries use the training numbers too.
.scoregives accuracy: 76% of the validation deliveries are on the right side of the line..predict_probareturns one column per class: P(on time), then P(late). The 2 km delivery at 19:00 gets , close to our 0.30..predictcuts at 0.5, so it says 0, on time.- The defaults matter.
LogisticRegression()adds a small penalty on large weights (an L2 penalty withC=1; smallerCmeans a stronger penalty). It also uses thelbfgssolver, a cousin of gradient descent that uses curvature to take smarter steps. The penalty pulls the weights slightly towards 0: 1.37 and , against 1.43 and with no penalty. C=np.infturns the penalty off. (Older code writespenalty=None. That argument is deprecated from scikit-learn 1.8.) Here both versions get 76%, so the penalty doesn't change the answer.
In raw units, the unpenalised weights are 0.64 per km and per hour, with an intercept of about 4.9. Those are the rounded weights the figures used.
In PyTorch
The same model in PyTorch is one nn.Linear(2, 1), trained on cross-entropy by gradient descent.
def train_logistic(lr: float = 0.5, steps: int = 500) -> tuple[nn.Linear, list[float]]:
"""Logistic regression in PyTorch: nn.Linear(2, 1) and BCEWithLogitsLoss, by full-batch gradient descent."""
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
x_train, y_train, _, _, _, _ = standardised_rush_hour()
X = torch.tensor(x_train, dtype=torch.float32, device=device) # (200, 2)
y = torch.tensor(y_train, dtype=torch.float32, device=device).unsqueeze(1) # (200, 1): 1 = late
model = nn.Linear(2, 1).to(device) # one score per delivery: w · x + b
with torch.no_grad():
model.weight.zero_() # start with every P(late) at 0.5
model.bias.zero_()
loss_fn = nn.BCEWithLogitsLoss() # sigmoid + cross-entropy in one safe step
optimizer = torch.optim.SGD(model.parameters(), lr=lr)
losses = []
model.train()
for _ in range(steps):
optimizer.zero_grad()
logits = model(X) # raw scores z, not probabilities (200, 1)
loss = loss_fn(logits, y)
loss.backward()
optimizer.step()
losses.append(loss.item())
return model, losses
def validation_accuracy(model: nn.Linear) -> float:
_, _, x_val, y_val, _, _ = standardised_rush_hour()
device = next(model.parameters()).device
model.eval()
with torch.inference_mode():
p_late = torch.sigmoid(model(torch.tensor(x_val, dtype=torch.float32, device=device))).squeeze(1)
return ((p_late > 0.5).cpu().numpy() == y_val).mean()
net, losses = train_logistic()
print(round(losses[0], 4), round(losses[-1], 4)) # 0.6931 0.5091: from log 2 down to the minimum
print(net.weight.data, net.bias.data) # [[ 1.43 -0.59]] [0.06]: scikit-learn's weights with C=inf
print(validation_accuracy(net)) # 0.760.6931 0.5091
tensor([[ 1.4325, -0.5883]]) tensor([0.0557])
0.76The weights match scikit-learn's with C=np.inf to four decimals, and the accuracy is the same 76%.
Notice that the model outputs raw scores, not probabilities. Raw scores that are meant to go into a sigmoid or softmax are called logits.
The loss takes the logits and applies the sigmoid itself. That's nn.BCEWithLogitsLoss, or F.binary_cross_entropy_with_logits as a function. It wants the labels as floats, in the same shape as the logits. That's what .unsqueeze(1) is for.
Why not apply torch.sigmoid yourself and then compute the loss? Because of rounding:
z = torch.tensor([200.0]) # a confident score for "late"
y = torch.tensor([0.0]) # but the delivery was on time
print(F.binary_cross_entropy(torch.sigmoid(z), y)) # 100: sigmoid(200) rounds to 1, log(0) is clamped
print(F.binary_cross_entropy_with_logits(z, y)) # 200: the right answer, −log(1 − σ(200))tensor(100.)
tensor(200.)A score of 200 for a delivery that was on time deserves a loss of 200. But in 32-bit floats, rounds to exactly 1, so is . PyTorch clamps that to 100. Working from the logit avoids the rounding, and gives the right answer. It's the same idea as F.cross_entropy in the PyTorch primer, which takes scores rather than probabilities.
DigressionSoftmax regression: more than two classesOne score per class, then softmax instead of the sigmoid. · 2 min
Suppose the shop wants three classes: early, on time and late. Give each class its own linear score, with its own weights. Then turn the three scores into three probabilities that add up to 1, with softmax.
For example, scores of 1 (early), 2 (on time) and 0.5 (late) give , and . Their total is 11.76, so the probabilities are 0.23, 0.63 and 0.14.
This model is softmax regression (also called multinomial logistic regression). Its loss is the same cross-entropy: of the probability given to the true class. With two classes it's exactly logistic regression, because softmax with two options is the sigmoid.
- scikit-learn's
LogisticRegressionswitches to softmax regression by itself when the labels have three or more classes. - In PyTorch, use
nn.Linear(n_features, 3)andnn.CrossEntropyLoss. It takes the three logits and the class number, and applies softmax inside, for the same reason as above.
DigressionLogistic regression is a neuronA weighted sum, then a bend. That's the building block of neural networks. · 1 min
Look at the model again: a weighted sum of the inputs plus a bias, then a fixed S-shaped function. That's exactly a neuron, the building block of neural networks, with the sigmoid as its bend.
The Neural-net foundations course starts from this lesson. It trains this same model on this same rush-hour data, calls it one neuron, and gets the same 76%. Then it combines many neurons into a network whose boundary can curve.
Putting it together
Here is the whole lesson in one pass, on the rush-hour data:
- Score: , a linear model.
- Probability: . The 2 km delivery at 19:00 gets 0.30.
- Decision: late if , which means . The boundary is a straight line, at 3.3 km for 19:00.
- Loss: cross-entropy, the average of (probability given to the true label). It ends at 0.509.
- Training: gradient descent, since there's no formula. scikit-learn and PyTorch find the same weights.
- Result: 76% of new deliveries right. The misses sit where the true rule curves: the 19:00 dip, and the evening on either side of it.
That last point is a limit of the model, not of training. No amount of training bends a straight line.
There are two ways out. This course's next levels meet models whose boundaries can bend, like nearest neighbours and decision trees. And the Neural-net foundations course stacks many of these neurons together. A small network gets over 90% on this same data.
Common misconceptions
"Logistic regression is a regression method." It's for classification. The name is historical: the score is a linear regression on the log of the odds, . What it predicts is a class probability.
"The sigmoid makes the boundary curved." The boundary is where , and is linear in the features. So the boundary is a straight line, whatever the S-shaped curve does to the probabilities.
"Bigger weights mean a better model." Doubling every weight keeps the same boundary and the same accuracy. It only makes the probabilities more extreme, including on the deliveries the model gets wrong.
"Squared error works fine for probabilities." It tops out at 1, and its push on the score fades when the model is sure and wrong. Cross-entropy keeps pushing hardest on exactly those mistakes.
"A 76% model is badly trained." Training has finished: the loss stopped falling long ago. Even the best straight line gets only 78% of the training deliveries right. The fix is a model that can draw curves, not more training.
Recap
- Classification predicts a category. Binary classification codes the two classes as 1 and 0.
- Logistic regression computes a linear score and squashes it with the sigmoid, , into .
- The decision boundary is where : a straight line. The weights' direction sets where it is; their size sets how sure the model is.
- The cross-entropy loss is the average of (probability given to the true label). Its gradient is times the features, and it pushes hardest on confident mistakes.
- On the rush-hour data, which isn't linearly separable, logistic regression gets 76% on validation.
- Code names: scikit-learn's
LogisticRegression(C,.predict_proba,.score); PyTorch'snn.Linear,nn.BCEWithLogitsLossandF.binary_cross_entropy_with_logits,torch.sigmoidandtorch.optim.SGD.