Logistic Regression & Linear Classifiers
From scores to probabilities: the sigmoid, cross-entropy and decision boundaries.
When the answer is yes or no, logistic regression is the model to try first: a linear score, a sigmoid, and a loss that turns out to be convex. This lesson derives it from maximum likelihood, computes its gradient, proves the convexity that makes training reliable, turns probabilities into decisions, and compares it with its ancestor, the perceptron.
What you’ll learn
- Write logistic regression as a model of with labels , and interpret its weights as changes in log-odds.
- Derive the negative log-likelihood (binary cross-entropy) and its gradient .
- Prove that the loss is convex, and choose a decision threshold from misclassification costs.
- Compare the perceptron rule with stochastic gradient descent on the logistic loss, prove Novikoff's mistake bound, and preview the softmax.
From scores to probabilities
Labels are throughout this lesson. Logistic regression models the probability of class 1 by passing a linear score through the sigmoid:
Three properties of do most of the work: it is symmetric, ; its derivative is ; and its inverse is the logit, . Inverting the model shows what is really linear:
Reading the weights. is the change in the log-odds of class 1 per unit increase of , the other features held fixed; equivalently, the odds are multiplied by . If a spam filter has weight on the number of exclamation marks, each extra one multiplies the odds of spam by .
Reading the geometry. The decision boundary is the hyperplane , with normal vector , and is the signed distance of from it. Multiplying and by leaves the boundary where it is but sharpens every probability: the direction of sets where the model is unsure, and its length sets how unsure.
Maximum likelihood is cross-entropy
Treat the labels as independent Bernoulli draws with and . The likelihood of the training labels is
Maximizing it is minimizing its negative logarithm, which is the binary cross-entropy between the labels and the predictions, also called the log loss:
Substitute and ; the per-example loss simplifies to a smooth function of the score:
With labels recoded as the same loss reads , a function of the margin alone: near 0 for large positive margins, growing linearly for large negative ones.
Differentiate one term with respect to its score, using :
By the chain rule, with (absorb the bias into as a constant feature):
Compare least squares, : prediction minus target, times input, in both cases. The difference is that depends nonlinearly on , so has no closed-form solution. Its intercept component does say something exact: at the optimum, , so the average predicted probability equals the observed frequency of class 1.
Why not squared error on the probabilities? Two reasons. With the sigmoid inside, is not convex in . And its gradient with respect to a score, , vanishes for a confidently wrong prediction ( with ), so a badly misclassified point barely pushes back. The log loss keeps a gradient of there. It is also a proper scoring rule: its expected value over is minimized by predicting the true probability, which is why logistic regression's probabilities tend to be well calibrated when the model is right.
A classifier assigns probability 0.1 to the class that actually occurs. What is its log loss on this example (natural logarithm)?
Show the answer
2.3
. Had it given the true class probability 0.9, the loss would be , about 22 times smaller. As the probability of the true class goes to 0, the loss goes to infinity: confident mistakes are what the log loss punishes most.
Convexity, fitting and regularization
Differentiate the gradient once more, using :
For any direction , the curvature is a weighted sum of squares with nonnegative weights, so is a convex function: every local minimum is global. If has full column rank, every weight is positive at finite and the curvature is strictly positive.
The curvature is also bounded: . So the loss is smooth with constant , and gradient descent with any step decreases it steadily.
Training is therefore a smooth convex problem. Gradient descent and its stochastic version, which updates on one example at a time with , scale to huge data. Newton's method uses and converges in a handful of steps on moderate problems; it turns out to be iteratively reweighted least squares (Convergence lesson Logistic Regression in Depth). Quasi-Newton L-BFGS is a common default in libraries.
One case needs care. If some hyperplane separates the two classes perfectly, scaling up its weights drives every margin, and so the loss, toward zero without ever reaching it: the maximum-likelihood estimate does not exist and . Adding an penalty, , makes the objective strictly convex with a unique finite minimizer; it is the MAP estimate under a Gaussian prior on the weights.
import numpy as np
from scipy.special import expit # numerically safe sigmoid
from sklearn.linear_model import LogisticRegression
# by hand: gradient descent on the mean log loss (X has a column of ones)
w = np.zeros(X.shape[1])
for t in range(2000):
p = expit(X @ w)
w -= eta * X.T @ (p - y) / len(y)
# in practice: L2-penalized fit; C is the INVERSE penalty strength
clf = LogisticRegression(C=1.0).fit(X_train, y_train) # y in {0, 1}
p_test = clf.predict_proba(X_test)[:, 1] # estimates of P(y = 1 | x)With its default solver, scikit-learn fits the intercept separately and leaves it unpenalized, so do not add a column of ones there. Smaller means stronger regularization.
From probabilities to decisions
A probability is not yet a decision. Predicting class 1 when minimizes the expected number of mistakes if the probabilities are calibrated, but mistakes rarely cost the same. Let a false positive cost and a false negative .
Given , predicting 1 risks a false positive with probability ; predicting 0 risks a false negative with probability :
Predict 1 exactly when that is cheaper:
In feature space, the new threshold is the hyperplane : a parallel shift of the old boundary, not a rotation. Changing costs never requires refitting.
For a fraud detector, missing a fraud costs 9 times as much as a false alarm. Above what predicted probability of fraud should a transaction be flagged?
Show the answer
10 %
. Flag everything above 10%: a false alarm is cheap enough to be worth paying nine times for every fraud caught. The boundary moves to score .
Two related shifts. If the class balance at deployment differs from training while stays the same (label shift), the correct log-odds change by a constant: add to , where and are the old and new class proportions. And if the probabilities themselves are miscalibrated, no threshold rule is reliable until they are repaired (Convergence lesson Calibration & Proper Scoring Rules; for skewed classes, Imbalanced Data & Cost-Sensitive Learning).
The perceptron, and more than two classes
Rosenblatt's perceptron (1958) uses the same linear score but outputs a hard class, , and learns from mistakes only. With targets , as in the widget below, its rule is
Set it beside stochastic gradient descent on the log loss, : the same update with the hard prediction replaced by a probability. Logistic regression nudges on every example, in proportion to how far its probability is from the label; the perceptron moves only when it is wrong, and then by a fixed amount.
On a mistake, and the update is . Its component along grows by at least :
Its squared length grows by at most , because the cross term is not positive on a mistake:
After mistakes, Cauchy–Schwarz ties the two together, and cancels:
| Property | Perceptron | Logistic regression |
|---|---|---|
| Output | a class | a probability |
| Loss minimized | (the perceptron criterion) | |
| Separable data | stops at the first separator it finds | ; gradient descent drifts toward the maximum-margin direction |
| Overlapping (non-separable) classes | never settles: the weights keep cycling | converges to the unique maximum-likelihood fit (full-rank ) |
More than two classes. Give each class its own score and normalize with the softmax:
With this is , logistic regression again. Its gradient has the same "probability minus target" form, , as the next lessons show.
Key takeaways
- Logistic regression models with : linear in the log-odds, so is an odds ratio and the boundary is a hyperplane.
- Its negative log-likelihood is the binary cross-entropy, , with gradient : prediction minus target, times input, but with no closed-form zero.
- The Hessian , , makes the loss convex and smooth. On separable data the MLE does not exist; an penalty restores a unique finite solution.
- The cost-optimal threshold is , a parallel shift of the boundary.
- The perceptron replaces the probability by a hard output and learns only from mistakes: on separable data with margin and radius it makes at most of them, and on non-separable data it never settles. The softmax extends logistic regression to classes.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In a logistic regression for loan default, the weight on "number of missed payments" is . What does it mean?
- Each missed payment raises the probability of default by 0.7
- Each missed payment raises the probability of default by 70%
- Each missed payment multiplies the odds of default by about , other features held fixed
- The model is 70% accurate
Show the answer
C. Each missed payment multiplies the odds of default by about , other features held fixed
Weights are additive on the log-odds scale: one more missed payment adds to , multiplying the odds by . The change in the probability itself depends on where you start; it is largest near .
For logistic regression with labels and the bias absorbed into , what is the gradient of the negative log-likelihood?
Show the answer
A.
The derivative of with respect to is , and the chain rule multiplies by . The factor cancels: that is the magic of pairing the sigmoid with the log loss.
Why is logistic regression trained with the log loss rather than squared error on the predicted probabilities?
- Squared error cannot be computed for probabilities
- The log loss is convex in and keeps a strong gradient on confident mistakes; squared error on is neither
- The log loss always gives higher accuracy
- Squared error requires labels in
Show the answer
B. The log loss is convex in and keeps a strong gradient on confident mistakes; squared error on is neither
With the sigmoid inside, squared error is non-convex in , and its gradient vanishes when saturates on the wrong side. The log loss is convex (Hessian ), and its gradient stays near for confident mistakes. It is also the maximum-likelihood loss and a proper scoring rule.
A false negative costs 4 times as much as a false positive. With calibrated probabilities, where should the threshold be?
- 0.8
- 0.5
- 0.25
- 0.2
Show the answer
D. 0.2
: flag whenever , because the expected cost of a false alarm, , then no longer exceeds that of a miss, .
You run the perceptron and logistic regression (plain gradient descent, no penalty) on data that are not linearly separable. What happens?
- Both converge to the same line
- The perceptron never settles, while logistic regression converges to its unique maximum-likelihood fit
- The perceptron converges, while the weights of logistic regression grow without bound
- Neither can be run on such data
Show the answer
B. The perceptron never settles, while logistic regression converges to its unique maximum-likelihood fit
The perceptron updates whenever it errs, and on non-separable data some point is always misclassified, so the weights cycle forever (averaging the iterates helps in practice). The logistic loss with full-rank is strictly convex and attains its minimum when the classes overlap, so gradient descent converges. Unbounded weights are what logistic regression suffers on separable data.
Go deeper
- Logistic Regression in Depth · Convexity, Newton’s method, separable data and regularization.
- Softmax & Multiclass Classification · One-vs-rest, softmax regression and its gradient.
- Generative vs Discriminative Classifiers · LDA, naive Bayes and when modeling p(x | y) pays off.
Further reading
- D. R. Cox, "The regression analysis of binary sequences," Journal of the Royal Statistical Society B 20(2), 215–242 (1958).
- F. Rosenblatt, "The perceptron: a probabilistic model for information storage and organization in the brain," Psychological Review 65(6), 386–408 (1958).
- C. M. Bishop, Pattern Recognition and Machine Learning (Springer, 2006), chapter 4.
- T. Hastie, R. Tibshirani & J. Friedman, The Elements of Statistical Learning, 2nd ed. (Springer, 2009), chapter 4.