ML fundamentals4 / 22

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.

on time late P = 0.5
The rush-hour data: 200 deliveries, ○ on time and × late. The curve is the rule that made the data (5% of labels were then flipped at random). Late trips sit above it. Around 19:00 even short trips run late.

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 w⋅x+b\mathbf{w} \cdot \mathbf{x} + b can be any number at all, like −3-3 or 1212. 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, z=w⋅x+bz = \mathbf{w} \cdot \mathbf{x} + b. A high score should mean "probably late", and a low one "probably on time". Then pass it through this function:

σ(z)=11+e−z.\sigma(z) = \frac{1}{1 + e^{-z}} .

This is the sigmoid, written σ\sigma (sigma). For a large positive zz, e−ze^{-z} is tiny, so σ(z)\sigma(z) is close to 1. For a large negative zz, e−ze^{-z} is huge, so σ(z)\sigma(z) is close to 0. At z=0z = 0, e0=1e^{0} = 1, so σ(0)=1/2\sigma(0) = 1/2. The Softmax lesson met this same curve as softmax with two options.

Putting the two together gives logistic regression:

P(late)=σ(w⋅x+b).P(\text{late}) = \sigma(\mathbf{w} \cdot \mathbf{x} + b) .

The figure uses weights trained later in this lesson, rounded: 0.64 per km, −0.37-0.37 per hour, and an intercept of 4.9. Move the delivery and watch its score slide along the curve.

−8−6−4−20246800.20.40.60.81score zP(late)late above 0.5

Score z = 0.64 × 2.0 − 0.37 × 19.0 + 4.9 = −0.85

P(late) = σ(−0.85) = 0.299 → predict on time

Score → sigmoid → probability. The delivery's score z sets where the dot sits on the S-shaped curve. Above the dashed 0.5 line, the model says late.

Things to notice:

  • Longer trips raise the score, since their weight is positive. Later hours lower it.
  • In the middle, near z=0z = 0, 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".
  • z=0z = 0 gives exactly 0.5. That's where the answer flips.

Worked example

A 2 km delivery sent at 19:00

  1. Weighted sum: 0.64×2=1.280.64 \times 2 = 1.28 for the distance, and −0.37×19=−7.03-0.37 \times 19 = -7.03 for the hour.

The decision boundary

The model predicts late when P(late)>0.5P(\text{late}) > 0.5. Since σ(z)>0.5\sigma(z) > 0.5 exactly when z>0z > 0, that's the same as

w⋅x+b>0.\mathbf{w} \cdot \mathbf{x} + b > 0 .

The points where w⋅x+b=0\mathbf{w} \cdot \mathbf{x} + b = 0 split the plane into a "late" side and an "on time" side. That dividing line is the model's decision boundary.

With two features, w1⋅km+w2⋅hour+b=0w_1 \cdot \text{km} + w_2 \cdot \text{hour} + b = 0 is a straight line. Solve it for the distance: km=(0.37×hour−4.9)/0.64\text{km} = (0.37 \times \text{hour} - 4.9) / 0.64. At 19:00 that's (7.03−4.9)/0.64=3.3(7.03 - 4.9) / 0.64 = 3.3 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?

on time late P = 0.5

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.

The trained model with every weight and the intercept multiplied by the same number. Shading shows P(late); the line marks where it equals 0.5.

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 (y=1y = 1) given P(late)=pP(\text{late}) = p, it's (1−p)2(1 - p)^2. 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 −log⁡-\log. For a late delivery, that's −log⁡p-\log p. For an on-time one, it's −log⁡(1−p)-\log(1 - p).

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

  1. The 2 km delivery at 19:00 was late, and the model said p=0.30p = 0.30.

00.20.40.60.81012345the model's P(late), for a delivery that was lateloss

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.

One late delivery, scored by cross-entropy (solid) and squared error (dashed), as the model's P(late) changes. The second tab shows how hard each loss pushes the score z during training.

Things to notice:

  • On the Loss tab, cross-entropy shoots up as pp 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 1−p1 - p: the more wrong, the harder it pushes. Near p=0p = 0 it pushes with almost full force.
  • Squared error's push falls to 0 as pp 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, p(1−p)p(1 - p), which is tiny out at the flat ends of the S. Cross-entropy's −log⁡-\log cancels that slope exactly, leaving p−yp - y.

The maths

Over nn examples, with labels yiy_i (1 or 0) and predictions pi=σ(w⋅xi+b)p_i = \sigma(\mathbf{w} \cdot \mathbf{x}_i + b), the loss is

L=1n∑i=1nℓi,L = \frac{1}{n} \sum_{i=1}^{n} \ell_i ,

where each example's loss is

ℓi=−[ yilog⁡pi+(1−yi)log⁡(1−pi)].\ell_i = -\Big[\, y_i \log p_i + (1 - y_i) \log (1 - p_i) \Big] .

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 yi=1y_i = 1, only −log⁡pi-\log p_i is left. If yi=0y_i = 0, only −log⁡(1−pi)-\log(1 - p_i). 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 pi−yip_i - y_i, so

∂L∂w=1n∑i=1n(pi−yi) xi,\frac{\partial L}{\partial \mathbf{w}} = \frac{1}{n} \sum_{i=1}^{n} (p_i - y_i)\, \mathbf{x}_i , ∂L∂b=1n∑i=1n(pi−yi).\frac{\partial L}{\partial b} = \frac{1}{n} \sum_{i=1}^{n} (p_i - y_i) .

It has the same shape as linear regression's gradient: each example's miss times its features. Here the miss is pi−yip_i - y_i, 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.

on time late P = 0.5

Step 0 · validation accuracy 53.5%

score = 0.00 × km + 0.00 × hour + 0.00 · learning rate 0.5, all 200 deliveries per step

00.20.40.60.8100.20.40.6steploss00.20.40.60.810%50%100%stepaccuracy
train 0.693 (50%)validation 0.693 (54%)
Logistic regression training live on the rush-hour data, by full-batch gradient descent at learning rate 0.5. Shading shows P(late); the line is the decision boundary. Below: loss and accuracy on the training (solid) and validation (dashed) deliveries.

Things to notice:

  • At step 0 every weight is 0, so every delivery gets P(late)=0.5P(\text{late}) = 0.5. The loss starts at −log⁡0.5=0.693-\log 0.5 = 0.693.
  • 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:

∑i=1n(σ(w⋅xi+b)−yi) xi=0.\sum_{i=1}^{n} \big(\sigma(\mathbf{w} \cdot \mathbf{x}_i + b) - y_i\big)\, \mathbf{x}_i = \mathbf{0} .

The unknowns w\mathbf{w} and bb 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.

Logistic regression with scikit-learn
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.76

What 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.
  • .score gives accuracy: 76% of the validation deliveries are on the right side of the line.
  • .predict_proba returns one column per class: P(on time), then P(late). The 2 km delivery at 19:00 gets P(late)=0.31P(\text{late}) = 0.31, close to our 0.30. .predict cuts at 0.5, so it says 0, on time.
  • The defaults matter. LogisticRegression() adds a small penalty on large weights (an L2 penalty with C=1; smaller C means a stronger penalty). It also uses the lbfgs solver, a cousin of gradient descent that uses curvature to take smarter steps. The penalty pulls the weights slightly towards 0: 1.37 and −0.56-0.56, against 1.43 and −0.59-0.59 with no penalty.
  • C=np.inf turns the penalty off. (Older code writes penalty=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 −0.37-0.37 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.

Logistic regression in PyTorch
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.76
0.6931 0.5091
tensor([[ 1.4325, -0.5883]]) tensor([0.0557])
0.76

The 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:

Why the loss takes logits
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, σ(200)\sigma(200) rounds to exactly 1, so −log⁡(1−p)-\log(1 - p) is −log⁡0-\log 0. 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 e1=2.72e^{1} = 2.72, e2=7.39e^{2} = 7.39 and e0.5=1.65e^{0.5} = 1.65. 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: −log⁡-\log 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 LogisticRegression switches to softmax regression by itself when the labels have three or more classes.
  • In PyTorch, use nn.Linear(n_features, 3) and nn.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:

  1. Score: z=0.64×km−0.37×hour+4.9z = 0.64 \times \text{km} - 0.37 \times \text{hour} + 4.9, a linear model.
  2. Probability: P(late)=σ(z)P(\text{late}) = \sigma(z). The 2 km delivery at 19:00 gets 0.30.
  3. Decision: late if P>0.5P > 0.5, which means z>0z > 0. The boundary is a straight line, at 3.3 km for 19:00.
  4. Loss: cross-entropy, the average of −log⁡-\log(probability given to the true label). It ends at 0.509.
  5. Training: gradient descent, since there's no formula. scikit-learn and PyTorch find the same weights.
  6. 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 zz is a linear regression on the log of the odds, log⁡(p/(1−p))\log\big(p / (1 - p)\big). What it predicts is a class probability.

"The sigmoid makes the boundary curved." The boundary is where z=0z = 0, and zz 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 z=w⋅x+bz = \mathbf{w} \cdot \mathbf{x} + b and squashes it with the sigmoid, σ(z)=1/(1+e−z)\sigma(z) = 1 / (1 + e^{-z}), into P(class 1)P(\text{class } 1).
  • The decision boundary is where z=0z = 0: 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 −log⁡-\log(probability given to the true label). Its gradient is (p−y)(p - y) 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's nn.Linear, nn.BCEWithLogitsLoss and F.binary_cross_entropy_with_logits, torch.sigmoid and torch.optim.SGD.