Logistic Regression in Depth
Convexity, Newton’s method, separable data and regularization.
Logistic regression looks finished once you know its gradient, but it still holds surprises. Newton's method on it is a sequence of weighted least-squares fits. Its maximum-likelihood estimate can fail to exist, and then gradient descent quietly converges, in direction, to a support vector machine. And when the number of features is a sizable fraction of the sample size, its textbook standard errors are wrong.
What you’ll learn
- Derive the Newton step for logistic regression and show that it is iteratively reweighted least squares (IRLS).
- Prove that the maximum-likelihood estimate exists if and only if the classes overlap, and relate separability to Cover's counting theorem.
- State the implicit-bias theorem for gradient descent on separable data, and sketch why the limiting direction is the maximum-margin separator.
- Use penalties, asymptotic standard errors and Firth's correction, and explain what changes when is not small.
Curvature and Newton's method
Absorb the bias into , use labels , and write , . The negative log-likelihood and its derivatives are
The curvature is bounded above () but not below: once a point is classified with confidence, and it stops contributing curvature. The bowl flattens far from the optimum, which slows plain gradient descent. Newton's method rescales each step by the local curvature.
The Newton step solves the local quadratic model of :
Factor out of both terms, writing and :
That is the solution of a weighted least-squares problem with the working response , a first-order Taylor expansion of the logit of around , and weights equal to the Bernoulli variances:
Each iteration recomputes , the weights and , then refits: hence "iteratively reweighted least squares". Points near the boundary () get the most weight, confidently classified points almost none. The same scheme fits every generalized linear model (Convergence lesson Generalized Linear Models).
Each IRLS step costs , like one least-squares fit, and near the optimum Newton converges quadratically, so on moderate problems a handful of iterations usually suffices (R's glm gives up after 25 by default). Far from the optimum a pure Newton step can overshoot; a line search (damped Newton) makes it converge from any start. For very large or , first-order and quasi-Newton methods (L-BFGS) win on cost per step.
import numpy as np
from scipy.special import expit
def irls(X, y, iters=25, tol=1e-10):
"""Logistic regression by Newton's method = IRLS. X includes a column of ones."""
w = np.zeros(X.shape[1])
for _ in range(iters):
s = X @ w
p = expit(s)
W = np.clip(p * (1 - p), 1e-12, None) # Bernoulli variances = weights
z = s + (y - p) / W # working response
XW = X * W[:, None]
w_new = np.linalg.solve(X.T @ XW, XW.T @ z) # weighted least squares
if np.max(np.abs(w_new - w)) < tol:
return w_new
w = w_new
return wOn separable data this loop never meets its tolerance: the weights keep growing, as the next step explains.
When the maximum-likelihood estimate does not exist
Recode labels as , so that . The data are completely separated if some has for all ; quasi-completely separated if some has for all without complete separation; and they overlap otherwise.
Separation rules it out. Suppose for all with . Full column rank gives , so at least one inequality is strict. Then for any , moving along lowers every term weakly and one term strictly, so no is a minimizer:
Overlap guarantees it. The function is continuous and, by overlap, positive on the unit sphere, which is compact, so . Writing with , the worst term alone gives
So is coercive: it grows without bound in every direction. A continuous coercive function attains its minimum, and strict convexity (the Hessian is positive definite for full-rank at finite ) makes the minimizer unique.
In practice, separation announces itself through exploding coefficients and standard errors, IRLS iterations that never meet their tolerance, and warnings such as R's "fitted probabilities numerically 0 or 1 occurred". It is common with rare outcomes, with a categorical level whose examples all share one label, and whenever is not small compared with , because separability is then likely by chance.
How likely? Cover (1965) counted the labelings of points in general position in that a hyperplane through the origin can realize: . With labels assigned at random, the chance of separability is , which equals exactly at ; as grows it rises sharply toward 1 for and falls sharply toward 0 for . So with pure-noise labels the MLE fails to exist once exceeds about . Candès & Sur (2020) computed the boundary with real signal: for Gaussian features the MLE exists asymptotically if and only if is below a threshold that equals without signal and shrinks as the signal grows.
points in general position in get independent fair-coin labels. What is the probability that some hyperplane through the origin separates them perfectly?
Show the answer
50 %
At , is exactly half of (the binomial coefficients of are symmetric), so and the probability is . With 150 points it falls to about ; with 50 it is 1. Every logistic regression with 50 columns (intercept included) and 100 noise labels has a coin-flip chance of having no maximum-likelihood estimate at all.
Gradient descent on separable data
If the MLE does not exist, what does gradient descent do? The loss can only be driven toward zero by pushing , so the interesting question is the direction the iterates take. The answer, an implicit bias of the algorithm, connects logistic regression to support vector machines.
With labels absorbed (), the negative gradient is a positive combination of the data points, each weighted by its loss slope. For large margins the logistic slope behaves like :
As grows along a direction , the margins scale like , and the exponential weights of the points with the smallest normalized margin dominate all others by factors that grow without bound. Asymptotically, every step adds a nonnegative combination of those points only:
The iterates are sums of these steps, so the limit direction is itself a nonnegative combination of the points that attain the minimal margin. Those are exactly the KKT conditions of the hard-margin SVM: with , and only for support vectors. The convex SVM problem has a unique solution, so the direction must be .
The loss decays like , so the margins grow only like , and the bounded correction fades from the direction at rate : to halve the angular error you must roughly square the number of steps.
Three consequences. Regularization without a penalty: unregularized gradient descent ends up at the maximum-margin classifier, whose generalization can be controlled by its margin rather than the dimension (Convergence lesson Margin-Based Generalization); the same direction is also the limit of the normalized -penalized solutions as . Loss curves mislead: because keeps growing, the log loss on any misclassified test point grows like , so test loss can rise while test error holds steady or improves. Non-separable data: Ji & Telgarsky (2019) showed that the direction still converges, to the maximum-margin direction of a maximal separable subset of the data, while the remaining component converges to the bounded optimum of the loss on the rest.
You train unregularized logistic regression by gradient descent on linearly separable data, twice: once from and once from a large random . What happens to ?
- It converges to a different separator in each run, depending on the start
- It stops at the first separating direction reached
- Both runs converge to the same direction, that of the hard-margin SVM
- It oscillates forever, because the loss has no minimum
Show the answer
C. Both runs converge to the same direction, that of the hard-margin SVM
The theorem holds from any initialization: the start enters only through the bounded term , which is swamped by the term. This differs from underdetermined least squares, where the initialization's component in the null space of never fades.
Regularization, uncertainty and high dimensions
Explicit penalties. Minimizing is MAP estimation under a prior; the objective is strictly convex and coercive for every , so a unique finite minimizer exists even under separation, and Newton's step becomes . In practice the intercept is left unpenalized and is chosen by cross-validation.
Standard errors. When the model is correctly specified and is fixed as , the MLE is consistent and asymptotically normal with covariance given by the inverse Fisher information, estimated by at the fit. Wald intervals and likelihood-ratio tests (twice the drop in negative log-likelihood, asymptotically for restrictions) follow. Near separation the Wald approximation degrades badly, and likelihood-ratio or profile-likelihood intervals are more trustworthy.
Bias. The MLE is biased away from zero in small samples, at order . Firth (1993) removed that leading bias by maximizing , a Jeffreys-prior penalty; his estimates also stay finite under separation, which Kosmidis and Firth later proved holds in general.
Key takeaways
- The Newton step for logistic regression is a weighted least-squares fit to the working response with weights : iteratively reweighted least squares.
- The MLE exists exactly when the classes overlap (Albert & Anderson). With random labels, separability is a coin flip at (Cover), and with signal the existence threshold for is lower (Candès & Sur).
- On separable data, gradient descent drives to infinity while its direction converges, at rate , to the hard-margin SVM: an implicit bias with no penalty in sight.
- penalties and Firth's Jeffreys-prior correction give finite estimates under separation. Inverse-Fisher standard errors are valid only for ; when is moderate the MLE is inflated and its uncertainty underestimated.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In IRLS for logistic regression, which observations receive the largest weights?
- Those classified with the highest confidence
- Those with the largest feature values
- All observations receive equal weight
- Those whose current predicted probability is near
Show the answer
D. Those whose current predicted probability is near
The weights are the Bernoulli variances , maximal at and vanishing as or . Points the model is unsure about determine the curvature, and so the next weighted least-squares fit, the most.
A logistic regression on completely separable data is fitted by unpenalized maximum likelihood. Which statement is correct?
- The likelihood can be pushed arbitrarily close to its supremum, but no finite attains it; the weights diverge
- The MLE exists and is unique, with very small standard errors
- The MLE exists but is not unique
- The log-likelihood has several local maxima
Show the answer
A. The likelihood can be pushed arbitrarily close to its supremum, but no finite attains it; the weights diverge
Along a separating direction , as , and for every finite . Albert & Anderson: the MLE exists if and only if the classes overlap. Software shows exploding coefficients and standard errors; a penalty or Firth's correction restores a finite estimate.
Unregularized gradient descent on the logistic loss with separable data and a small fixed step: what does converge to, and how fast?
- The least-squares direction, at rate
- The hard-margin SVM direction, at rate
- The hard-margin SVM direction, at a linear (geometric) rate
- It does not converge
Show the answer
B. The hard-margin SVM direction, at rate
Soudry et al. (2018): with bounded (for almost all datasets), so the direction approaches the max-margin solution, but only at rate , even though the loss itself falls like .
You fit logistic regression with examples and independent Gaussian features, and the MLE exists. What does high-dimensional theory predict for the usual output?
- Nothing changes: with , classical asymptotics are accurate
- The coefficients are biased toward zero, and the standard errors are too large
- The coefficients are inflated in magnitude, their real variability exceeds the reported standard errors, and likelihood-ratio -values are miscalibrated
- The fit is unbiased, but Newton's method cannot converge
Show the answer
C. The coefficients are inflated in magnitude, their real variability exceeds the reported standard errors, and likelihood-ratio -values are miscalibrated
With , Sur & Candès (2019) show that the MLE overestimates effect magnitudes, its variance exceeds the inverse-Fisher-information estimate, and the likelihood-ratio statistic follows a rescaled , so classical -values are wrong. What matters is , not alone.
Further reading
- A. Albert & J. A. Anderson, "On the existence of maximum likelihood estimates in logistic regression models," Biometrika 71(1), 1–10 (1984).
- D. Soudry, E. Hoffer, M. S. Nacson, S. Gunasekar & N. Srebro, "The implicit bias of gradient descent on separable data," Journal of Machine Learning Research 19, 1–57 (2018).
- D. Firth, "Bias reduction of maximum likelihood estimates," Biometrika 80(1), 27–38 (1993).
- P. Sur & E. J. Candès, "A modern maximum-likelihood theory for high-dimensional logistic regression," Proceedings of the National Academy of Sciences 116(29), 14516–14525 (2019).
- P. McCullagh & J. A. Nelder, Generalized Linear Models, 2nd ed. (Chapman & Hall, 1989).