Logistic Regression
A linear model of the log-odds, trained with cross-entropy. Why the loss has that form, and why separable data has no best fit.
Jump to a section
A linear model of the log-odds
Logistic regression is a classifier, despite the name. What it regresses is the log-odds of the positive class, as a linear function of the features:
Solve for and the sigmoid appears:
The sigmoid is steep around a score of 0 and flat far from it: , , . Points near the decision boundary get probabilities near one half, and points far from it get probabilities near 0 or 1.
The log-odds form is also what gives the coefficients their meaning. Raising feature by one unit, with the others held fixed, adds to the log-odds and so multiplies the odds by . A weight of 0.7 roughly doubles the odds, since ; a weight of 2 multiplies them by about 7.4.
Score, probability and decision
Take a single feature with score . At the score is 0 and the probability is 0.5. At the score is 1 and the probability is about 0.731.
A linear score becomes a probability
The sigmoid surface crosses probability 0.5 where the linear score equals zero.
Exact inputs and equations appear with the figure.
Preparing the scientific figure…
Exact sigmoid probabilities for supplied coefficients. Fitting, calibration, and threshold selection are separate tasks.
Authored analytic exampleExperiment with related Studio inputs
Read the probability at zero, then compare equally sized changes near the center and in the tails.
Exact sigmoid values for a single logit. Choosing a decision threshold is separate from fitting or calibrating a classifier.
Inspect the related Studio values
x,y,series -6,0.0024726231566347743,Sigmoid -5.8,0.0030184163247084245,Sigmoid -5.6,0.003684239899435989,Sigmoid -5.4,0.004496273160941178,Sigmoid -5.2,0.005486298899450404,Sigmoid -5,0.0066928509242848554,Sigmoid -4.8,0.008162571153159897,Sigmoid -4.6,0.009951801866904324,Sigmoid -4.4,0.012128434984274237,Sigmoid -4.2,0.014774031693273055,Sigmoid -4,0.01798620996209156,Sigmoid -3.8,0.021881270936130476,Sigmoid -3.5999999999999996,0.026596993576865863,Sigmoid -3.4,0.032295464698450516,Sigmoid -3.1999999999999997,0.03916572279676437,Sigmoid -3,0.04742587317756678,Sigmoid -2.8,0.057324175898868755,Sigmoid -2.5999999999999996,0.06913842034334684,Sigmoid -2.4,0.08317269649392238,Sigmoid -2.1999999999999997,0.09975048911968518,Sigmoid -2,0.11920292202211755,Sigmoid -1.7999999999999998,0.14185106490048782,Sigmoid -1.5999999999999996,0.16798161486607557,Sigmoid -1.3999999999999995,0.19781611144141834,Sigmoid -1.1999999999999993,0.23147521650098246,Sigmoid -1,0.2689414213699951,Sigmoid -0.7999999999999998,0.31002551887238755,Sigmoid -0.5999999999999996,0.35434369377420466,Sigmoid -0.39999999999999947,0.40131233988754816,Sigmoid -0.1999999999999993,0.4501660026875223,Sigmoid 0,0.5,Sigmoid 0.20000000000000018,0.549833997312478,Sigmoid 0.40000000000000036,0.5986876601124521,Sigmoid 0.6000000000000005,0.6456563062257956,Sigmoid 0.8000000000000007,0.6899744811276126,Sigmoid 1,0.7310585786300049,Sigmoid 1.2000000000000002,0.7685247834990178,Sigmoid 1.4000000000000004,0.8021838885585818,Sigmoid 1.6000000000000005,0.8320183851339246,Sigmoid 1.8000000000000007,0.8581489350995123,Sigmoid 2,0.8807970779778823,Sigmoid 2.200000000000001,0.900249510880315,Sigmoid 2.4000000000000004,0.9168273035060777,Sigmoid 2.5999999999999996,0.9308615796566531,Sigmoid 2.8000000000000007,0.9426758241011313,Sigmoid 3,0.9525741268224334,Sigmoid 3.200000000000001,0.9608342772032357,Sigmoid 3.4000000000000004,0.9677045353015495,Sigmoid 3.6000000000000014,0.9734030064231343,Sigmoid 3.8000000000000007,0.9781187290638694,Sigmoid 4,0.9820137900379085,Sigmoid 4.200000000000001,0.9852259683067269,Sigmoid 4.4,0.9878715650157257,Sigmoid 4.600000000000001,0.9900481981330957,Sigmoid 4.800000000000001,0.9918374288468401,Sigmoid 5,0.9933071490757153,Sigmoid 5.200000000000001,0.9945137011005495,Sigmoid 5.4,0.9955037268390589,Sigmoid 5.600000000000001,0.9963157601005641,Sigmoid 5.800000000000001,0.9969815836752917,Sigmoid 6,0.9975273768433653,Sigmoid
The decision is a third, separate step. The default rule predicts class 1 when , which is the same as . A threshold of 0.8 would call the example negative: means , which here needs . Moving the threshold changes decisions without refitting anything, while changing the weights changes the scores. Keep the two apart when explaining a precision-recall trade-off.
The right threshold comes from costs, not from the model. If a false negative costs and a false positive , predicting positive pays off when , which is when . If a missed positive costs four times as much as a false alarm, the threshold is 0.2. That calculation is only as good as the model's calibration.
Every threshold picks out a level set of the score, so the decision boundary is always a hyperplane in the features. Overlapping, non-separable classes are fine. A curved boundary is not, unless you add features that straighten it. XOR on two binary features is the standard case: no line separates it, but with the product as a third feature, one plane does.
Why the loss is cross-entropy
Treat each label as a Bernoulli draw with probability and maximise the likelihood of the training labels. The average negative log-likelihood is binary cross-entropy, over examples with :
Its gradient is the prediction error times the input:
Per example, the derivative with respect to the score is . With label 1 and score 1 it is about , and multiplying by each input feature gives that example's share of the weight gradient. The loss is convex in and , so any minimum gradient descent finds is the global one.
Squared error on the sigmoid output loses both properties. It is not convex, and its gradient picks up an extra factor that vanishes exactly when the model is confidently wrong. At a score of with label 1, the model gives . Cross-entropy's gradient with respect to the score is . The squared-error gradient, , is about : 75 times weaker on the very example that most needs correcting.
Setting the bias gradient to zero gives a useful identity. At the optimum , so the average predicted probability on the training data equals the training base rate exactly. The weight gradients give the same matching for every feature: .
In code
Batch gradient descent on 200 synthetic examples whose labels come from a noisy linear rule.
1import numpy as np
2
3rng = np.random.default_rng(0)
4X = rng.normal(size=(200, 3))
5true_w = np.array([2.0, -1.0, 0.5])
6y = (X @ true_w + rng.normal(0, 0.5, 200) > 0).astype(float)
7
8def sigmoid(z): return 1 / (1 + np.exp(-z))
9
10w, b, lr = np.zeros(3), 0.0, 0.1
11for _ in range(2000):
12 p = sigmoid(X @ w + b)
13 grad_w = X.T @ (p - y) / len(y) # (p - y)·x, averaged
14 grad_b = (p - y).mean()
15 w -= lr * grad_w
16 b -= lr * grad_b
17
18p = sigmoid(X @ w + b)
19acc = ((p >= 0.5) == y).mean()
20print(f"accuracy {acc:.2f}, weights {w.round(2)}")
21assert acc > 0.9
22assert abs(p.mean() - y.mean()) < 1e-3 # mean prediction matches the base rate
23assert w @ true_w / (np.linalg.norm(w) * np.linalg.norm(true_w)) > 0.99The fitted weights come out near , not the that generated the labels. The direction matches; the scale does not. Logistic regression's weights measure how fast the probability changes along each feature, and that depends on the label noise (standard deviation 0.5 here) as much as on the rule underneath it.
Separable data has no best fit
If a hyperplane separates the classes perfectly, scaling up always moves every closer to its label and lowers the loss. No finite weight vector minimises it, so unregularised gradient descent keeps growing the weights for as long as it runs, and the probabilities grow ever more extreme.
Four points make it visible. With inputs labelled 0, 0, 1, 1, the single weight reaches about 5.5 after 1,000 steps, 7.8 after 10,000 and 10.1 after 100,000, growing with the logarithm of the step count. Add an L2 penalty with and it settles at about 2.42.
1import math
2
3xs, ys = [-2.0, -1.0, 1.0, 2.0], [0, 0, 1, 1] # separable at x = 0
4
5
6def sigmoid(z):
7 return 1 / (1 + math.exp(-z))
8
9
10def fit(steps, lr=0.5, lam=0.0):
11 w = 0.0
12 for _ in range(steps):
13 grad = sum((sigmoid(w * x) - y) * x for x, y in zip(xs, ys)) / len(xs)
14 w -= lr * (grad + 2 * lam * w)
15 return w
16
17
18assert 5 < fit(1_000) < fit(10_000) < fit(100_000) # no finite optimum
19assert abs(fit(10_000, lam=0.01) - fit(100_000, lam=0.01)) < 1e-9
20assert abs(fit(100_000, lam=0.01) - 2.42) < 0.01scikit-learn's LogisticRegression applies an L2 penalty by default, with C=1.0 as the inverse of its strength. That keeps separable problems finite, but it also means the coefficients you read off are shrunk toward zero.
Where it goes wrong
Reading coefficients as causes. A weight is the change in log-odds per unit of its feature with the other features held fixed. That is an association within this particular feature set. Correlated features split credit between them unpredictably, and a feature's units set the size of its weight.
Unscaled features under a penalty. The L2 penalty charges every weight the same rate. Record a length in millimetres instead of metres and its weight shrinks a thousandfold, so the penalty on it all but disappears. Standardise features before fitting a regularised model.
A base rate that changed. The identity above ties the mean prediction to the training base rate. Train on balanced 50/50 data and deploy where 1% of cases are positive, and every probability is too high. If only the class balance changed, Bayes' rule gives the fix: shift the intercept by the change in prior log-odds, here .
Interactions the score cannot see. When the effect of one feature depends on another, a linear score misses it unless you supply the product as a feature, as in the XOR case.
More than two classes. Softmax regression gives each class its own score and trains with categorical cross-entropy. With two classes and one score fixed at 0, the softmax of is exactly , so logistic regression is the two-class case.
Sources and further reading
- scikit-learn, Logistic regression: linear logits, classification loss, and regularization.
- scikit-learn, LogisticRegression API reference: the default penalty and the
Cparameter.
Keep going
Ask your own question about Logistic Regression, or start a guided session on it: six short pages, from the big picture to code you can run.