Logistic regression
A linear model that outputs probabilities: the sigmoid from the log-odds, likelihood and the log-loss, the gradient as residuals times inputs, convexity and Newton's method, runaway weights on separable data, and calibration.
From a score to a probability
The topic Linear classifiers and surrogate losses ended with a table of what each surrogate loss estimates. The hinge loss recovers only the side of the boundary. The logistic loss recovers the log-odds, and the probability itself follows from the log-odds.
Many decisions need that probability, not just the side. The previous topic's example was the chance of default against the price of a loan. Here take the churn task: a telecom offers a discount to customers who are likely to leave. Whether the discount pays off depends on how likely each customer is to leave, compared with what the discount costs. Logistic regression is the linear model built to output that probability.
In this topic the labels are , with for a customer who left. They suit the Bernoulli distribution. The margin form of the previous topic uses labels , which here are . The score is . To shorten the formulas, add a constant feature to every , so that the bias becomes one of the weights and .
Why not model the probability as a linear function? A linear score takes every real value, while a probability lives in , so a linear model would happily predict or . The odds live in , and the log-odds in . So the log-odds is a quantity a linear score can describe without leaving its range. Logistic regression sets it equal to the score:
The sigmoid is just the inverse of the log-odds. A score of means ; a score of gives , and a score of gives . Two properties of from the topic Derivatives and Taylor series in Mathematics for ML are used below: and .
Why linear log-odds
Why should the log-odds be linear in the features? Bayes' formula in odds form, from the topic Conditional probability and Bayes' formula, says that the posterior log-odds are the prior log-odds plus the log likelihood ratio:
Suppose both classes are Gaussian with a common covariance (see The multivariate Gaussian). Then the quadratic terms of the two log-densities cancel, and the log likelihood ratio is linear in . Logistic regression keeps the conclusion, linear log-odds, and drops the assumption: it models directly and never says how itself is distributed.
A worked example on a line. The classes are and , equally likely. The log likelihood ratio is
so at the probability of class 1 is . If class 1 is rarer, with prior , the prior log-odds are added, and the probability drops to . A change of base rate shifts every log-odds by the same constant.
Reading the weights. Increasing feature by one unit adds to the log-odds. That multiplies the odds by , whatever the values of the other features. A weight of doubles the odds, since . This number is the odds ratio that medical and social-science papers report. It describes the model. It is a causal effect only if the data allow a causal reading.
Likelihood gives the log-loss
How to fit ? Treat each label as a Bernoulli variable with success probability , and the labels as independent given the features. The likelihood of the training labels is . Its negative logarithm is
the log-loss, or binary cross-entropy. That cross-entropy is a negative log-likelihood was shown in the topic Maximum likelihood of Probability Theory; here is its two-class case. Divided by , it is the empirical risk of the model.
It is the logistic surrogate of the previous topic, written without the factor , which does not move the minimizer. For the term is . The case follows from . With the margin , both cases read
So the surrogate chosen in the previous topic for its shape is exactly maximum likelihood under the model of linear log-odds.
A worked example: one feature, , no bias, three customers with and labels . The probabilities are . The losses are:
- for the first customer, confidently right;
- for the second, moderately right;
- for the third, on the wrong side of the boundary.
The total is . A model that gave the third customer would pay for that customer alone. The log-loss punishes confident mistakes without limit.
The gradient: residuals times inputs
Differentiate one term with respect to its score. For the derivative of is . For the derivative of is . Both cases equal . The chain rule with gives
This is the form of least squares, from the topic Least squares: prediction minus target, times the input. Each object pulls the weights in proportion to how wrong its probability is. A correctly and confidently classified object, with , hardly pulls at all. In the worked example , and the derivative with respect to is
Everything from Gradient descent and Stochastic and adaptive optimizers applies unchanged. One SGD step on object is . Compare it with the perceptron of the previous topic: the perceptron moves only on mistakes and by the whole , while logistic regression moves on every object by a soft amount.
What the optimum guarantees. The bias is the weight of the constant feature . Its component of the gradient is , and at the optimum it is zero. So at the maximum likelihood fit, the average predicted probability equals the share of positives in the training set. The same holds inside any group marked by a binary feature of the model: the predictions of each group add up to the number of positives in it.
Convexity and Newton's method
Differentiating once more, with , gives the Hessian
For any vector , . So the log-loss is convex, and strictly convex when has full column rank. By Convex sets and functions, every local minimum is global.
There is no closed form. The equations are nonlinear in , unlike the normal equations of least squares. With up to a few hundred features, Newton's method from Unconstrained optimization solves them in a handful of steps:
Each step is a weighted least-squares problem with weights , which is why the method is called iteratively reweighted least squares (IRLS). Here it is on 1000 synthetic customers with two features and true weights :
import numpy as np
rng = np.random.default_rng(0)
X = np.c_[np.ones(1000), rng.normal(size=(1000, 2))] # column of ones: the bias
y = (rng.random(1000) < 1 / (1 + np.exp(-X @ [-1.0, 2.0, -1.0]))).astype(float)
w = np.zeros(3)
for step in range(7):
p = 1 / (1 + np.exp(-X @ w))
grad = X.T @ (p - y) # X^T (p - y)
H = X.T @ (X * (p * (1 - p))[:, None]) # X^T S X
w -= np.linalg.solve(H, grad)
print(step, f"{np.abs(grad).max():.1e}", w.round(3))
print(p.sum().round(2), y.sum())0 2.9e+02 [-0.492 1.081 -0.459]
1 7.3e+01 [-0.763 1.703 -0.723]
2 1.9e+01 [-0.901 2.015 -0.862]
3 2.6e+00 [-0.927 2.073 -0.888]
4 7.1e-02 [-0.927 2.075 -0.889]
5 5.6e-05 [-0.927 2.075 -0.889]
6 3.5e-11 [-0.927 2.075 -0.889]
372.0 372.0Near the optimum the largest gradient component goes from to , and : the number of correct digits roughly doubles per step. The last line checks the bias equation: the predicted probabilities add up to the number of customers who left. The fitted weights differ from the true ones because 1000 objects is a finite sample. A Newton step costs about operations, so with many features scikit-learn uses L-BFGS by default, and very large data sets use SGD.
Separable data and the penalty
Newton's method needs a minimum to converge to. The previous topic warned that on separable data the logistic loss has none; here is why, and how fast the weights run away. Suppose some classifies the training set perfectly, so every margin is positive. Scaling by multiplies every margin by , and each term decreases towards zero as grows. Yet for every finite . The infimum, zero, is never attained: the maximum likelihood estimate does not exist. Albert and Anderson (1984) showed that it exists exactly when the classes overlap, that is, when no hyperplane separates them, not even with some points lying on it.
The geometry explains what goes wrong. The probability depends on only through the score, so its level sets are hyperplanes parallel to the boundary. The distance between the levels and is . As grows, this band shrinks, and the predicted probabilities on the training set drift to and .
Gradient descent on separable data never stops. Take four points with the two right ones positive, and run gradient descent on the mean log-loss with step from zero. The slope is after steps, after and after , about after steps. The mean loss falls like . The direction of settles, towards the widest-margin separator of the later topic Support vector machines (Soudry et al., 2018), while its length grows without bound.
Separation is not exotic. The previous topic showed that random labels on points in dimensions are separable with probability already at .
The penalty fixes it. Minimize
instead. The penalty adds to the Hessian, so the objective is strictly convex and grows without bound in every direction. A unique, finite minimizer exists for any data. As in the topic Regularization, the penalty is a Gaussian prior , and the fit is its MAP estimate from Bayesian inference. The bias is usually left unpenalized. scikit-learn's LogisticRegression applies this penalty by default, with C = 1 the inverse of its strength; C=np.inf gives plain maximum likelihood.
Calibration: do the probabilities mean what they say?
A model is calibrated if, among the objects to which it assigns probability , a share is positive:
A weather forecaster who says "70% chance of rain" is calibrated if it rains on 70% of such days. Calibration is checked with a reliability diagram. Split the test predictions into bins, often ten of equal width. In each bin plot the mean prediction against the share of positives. A calibrated model's points lie on the diagonal. The expected calibration error sums the gaps, weighted by the share of objects in each bin:
where bin holds objects with mean prediction and share of positives . The share in each bin is noisy, so even perfectly calibrated predictions have a positive ECE: on 10,000 objects it averages with ten bins and with fifty. Show the count of each bin on the diagram, and read the ECE next to the log-loss, which needs no bins.
Calibration alone is not quality. A model that predicts the base rate for everyone is perfectly calibrated and useless. A good probabilistic classifier is calibrated and separates the classes.
Why the log-loss aims at calibrated probabilities. Take a single point where the true probability of class 1 is . A prediction has expected log-loss . Its derivative vanishes at . The expected loss is smallest when the model tells the truth. Losses with this property are called proper scoring rules. The squared error , known as the Brier score, is proper too. Not every loss is.
A fitted logistic regression is calibrated on average over its training set, by the bias equation. It is calibrated everywhere only to the extent that the true log-odds are linear and the sample is large. Overfitting makes it overconfident; a strong penalty makes it underconfident.
Recalibration and what comes next
Other models do not even aim at probabilities. A score trained with the hinge loss is not a probability at all. Naive Bayes, which treats the features as independent given the class, counts correlated evidence several times and pushes its probabilities towards and . Boosted trees and max-margin methods tend to push them away from and . On eight correlated Gaussian features, naive Bayes has ECE and log-loss on 10,000 test objects. Logistic regression, the correct model there, has and .
A score that ranks well but is miscalibrated can be repaired by a monotone map. The map is fitted on data not used for training: a held-out set or cross-validation, as in Validation and overfitting.
- Platt scaling fits a one-feature logistic regression on the score : , by maximum likelihood.
- Isotonic regression fits the best non-decreasing step function of the score in squared error. Walk through the objects sorted by score, and whenever a block's mean exceeds the next block's, merge them. For labels in score order, the result is . It fixes any monotone distortion, but needs more data: with fewer than a few hundred calibration objects, Platt scaling usually does better.
With , Platt's map is strictly increasing, so it keeps the order of the objects. Isotonic regression can only merge neighbours into ties. After either map, naive Bayes above has ECE near , while its ability to rank the objects is unchanged.
With classes, each class gets its own weights and score , and the softmax turns the scores into probabilities:
For it is , binary logistic regression again. The topic Multiclass and multilabel classification develops it.
So the model's output is , a probability that a reliability diagram can check and Platt scaling can repair. A probability is not yet a decision. A threshold turns it into "offer the discount" or "do nothing". scikit-learn's predict uses by default, but the right threshold depends on how rare the positives are and on what each kind of error costs. Judging the model needs a number too, and accuracy says almost nothing when positives are rare: a model that never flags anyone scores 99% when 1% leave. The next topic, Classification metrics, builds the tools for both questions.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Go deeper — optional
Code and labs do not count toward the main percentage or the certificate.
- Sigmoid and logistic NLLoptional
σ(z), NLL and ∇w on a tiny dataset. Self-check in the notebook.
~20 min · easier on a computer · Logistic regression topic read.
Self-check in the notebook — not part of mastery or the certificate.
Answers are saved on the server and tied to this browser until you sign in.