AI Wiki中文/EN

Logistic regression

逻辑回归

Derive conditional odds, gradients and curvature; fit stable regularized probabilities and identify when separation prevents a finite MLE.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Fit a probability curve, not a line through zeroes and ones

Imagine eight labeled examples, each with one feature. Four have x=−1x=-1, with labels 0,0,0,10,0,0,1; four have x=1x=1, with labels 0,1,1,10,1,1,1. The observed success proportions are 1/41/4 and 3/43/4. A logistic model can fit these probabilities with intercept 0 and slope log⁡3\log3. Its output is a probability conditional on the feature, not a continuous response that happens to resemble a class label.

The model is called regression because it relates predictors to an outcome through a parameterized function. It is commonly used for classification, but probability estimation and the final classification rule are different steps. Predicting class 1 whenever the probability exceeds 1/21/2 is one decision rule; unequal error costs can call for another threshold.

Make log-odds linear

Let Y∈{0,1}Y\in\{0,1\} and let xx contain fixed predictors. Logistic regression assumes

p(x)=P(Y=1∣x)=σ(b+x⊤w),σ(z)=11+e−z,log⁡p(x)1−p(x)=b+x⊤w.p(x)=P(Y=1\mid x)=\sigma(b+x^\top w),\qquad \sigma(z)=\frac1{1+e^{-z}},\qquad\log\frac{p(x)}{1-p(x)}=b+x^\top w.

The logit maps (0,1)(0,1) to the real line; finite logits give probabilities strictly between zero and one in exact arithmetic. The odds are p/(1−p)p/(1-p). Holding other predictors fixed, increasing xjx_j by one multiplies the odds by ewje^{w_j}. It does not add a constant to the probability: the local derivative is wjp(1−p)w_jp(1-p) and depends on the starting point. CMU’s logistic-regression lecture derives the conditional likelihood and logit model.

Assume responses are independent conditional on their features and a shared parameter vector. Different inputs generally have different success probabilities pip_i; conditional independence does not require them to share a single Bernoulli probability. The joint likelihood is ∏ipiyi(1−pi)1−yi\prod_i p_i^{y_i}(1-p_i)^{1-y_i}. Minimizing its negative log gives binary cross-entropy. With an L2 penalty on slopes, use the explicit average-loss convention

J(b,w)=1n∑i=1n[log⁡(1+ezi)−yizi]+λ2∥w∥22,zi=b+xi⊤w.J(b,w)=\frac1n\sum_{i=1}^n\bigl[\log(1+e^{z_i})-y_i z_i\bigr]+\frac\lambda2\|w\|_2^2,\qquad z_i=b+x_i^\top w.

The intercept is unpenalized. Setting λ=0\lambda=0 gives maximum likelihood; positive λ\lambda changes the estimator. Dividing a summed loss by nn requires rescaling the penalty if the intended objective is to remain unchanged. Its Gaussian-prior interpretation depends on that scaling, as explained in MAP estimation.

Put ai=(1,xi⊤)⊤a_i=(1,x_i^\top)^\top, stack their transposes into matrix AA, and write θ=(b,w⊤)⊤\theta=(b,w^\top)^\top. Differentiating σ\sigma gives σ′(z)=σ(z)(1−σ(z))\sigma'(z)=\sigma(z)(1-\sigma(z)). Therefore

∇J=1nA⊤(p−y)+λDθ,∇2J=1nA⊤WA+λD,\nabla J=\frac1nA^\top(p-y)+\lambda D\theta,\qquad\nabla^2J=\frac1nA^\top W A+\lambda D,

where D=diag⁡(0,1,…,1)D=\operatorname{diag}(0,1,\ldots,1) and W=diag⁡(pi(1−pi))W=\operatorname{diag}(p_i(1-p_i)). Since each weight is nonnegative, every quadratic form of the Hessian is nonnegative: the objective is convex. Without regularization, full column rank of AA makes the Hessian positive definite at finite parameters. This gives strict convexity, not a guarantee that a minimizer exists. The weighted quadratic approximation also leads to iteratively reweighted least squares, or IRLS. Friedman, Hastie and Tibshirani’s 2009 manuscript, Section 3 derives that approximation.

In the opening example, the map from (b,w)(b,w) to the two group logits (b−w,b+w)(b-w,b+w) is invertible. Each group contains both outcomes, and its likelihood is uniquely maximized at its observed proportion. The group logits are −log⁡3-\log3 and log⁡3\log3, giving (b,w)=(0,log⁡3)(b,w)=(0,\log3). The average negative log likelihood is approximately 0.562335. With slope penalty λ=0.1\lambda=0.1, symmetry still gives b=0b=0, but the new optimum solves σ(w)−3/4+0.1w=0\sigma(w)-3/4+0.1w=0, yielding approximately 0.736876 for the slope.

A stable loss and a conservative gradient step

The expression log⁡(1+ez)\log(1+e^z) can overflow even when the final loss is representable. Let t=(2y−1)zt=(2y-1)z be the signed margin. The same single-observation loss can be evaluated as

log⁡(1+e−t)=max⁡(0,−t)+log⁡(1+e−∣t∣).\log(1+e^{-t})=\max(0,-t)+\log\bigl(1+e^{-|t|}\bigr).

The program uses log1p for the last term and a branched sigmoid. For label 1 it computes the gradient residual as −σ(−z)-\sigma(-z), avoiding premature cancellation in σ(z)−1\sigma(z)-1. This is numerical stabilization of the same objective, not probability clipping.

The complete standard-library fitter uses positive L2 regularization and requires both classes. Those restrictions ensure a finite unique optimum with the unpenalized intercept: the penalty bounds slopes on a sublevel set, and either direction of an unbounded intercept would give an arbitrarily large loss for one class. The Hessian is then positive definite. From Wii≤1/4W_{ii}\le1/4, a global gradient-Lipschitz bound is L=∥A∥F2/(4n)+λL=\|A\|_F^2/(4n)+\lambda. A step of 1/L1/L is conservative; it avoids computing or inverting a Hessian.

import math

def sigmoid(z):
    if not math.isfinite(z):
        raise ValueError("finite logit required")
    if z >= 0:
        return 1/(1+math.exp(-z))
    ez = math.exp(z)
    return ez/(1+ez)

def binary_loss(z,y):
    # y is a validated binary label. This also avoids subtracting two large logits.
    margin = (2*y-1)*z
    return max(0,-margin)+math.log1p(math.exp(-abs(margin)))

def value_gradient(a,y,theta,penalty):
    # Internal helper: matching finite arrays, binary labels, nonnegative penalty.
    logits = [math.fsum(v*t for v,t in zip(row,theta)) for row in a]
    residual = [sigmoid(z) if label == 0 else -sigmoid(-z) for z,label in zip(logits,y)]
    n = len(y)
    value = math.fsum(binary_loss(z,label) for z,label in zip(logits,y))/n
    value += penalty*math.fsum(t*t for t in theta[1:])/2
    gradient = [math.fsum(row[j]*r for row,r in zip(a,residual))/n
                +(penalty*theta[j] if j else 0) for j in range(len(theta))]
    if not math.isfinite(value) or not all(map(math.isfinite,gradient)):
        raise ValueError("nonfinite intermediate result; rescale the data")
    return value,gradient

def fit_logistic(x,y,penalty=.1,tol=1e-9,max_steps=20000):
    x = [list(map(float,row)) for row in x]
    y = list(y)
    if not y or len(x) != len(y):
        raise ValueError("nonempty matching data required")
    if any(type(label) is not int or label not in (0,1) for label in y):
        raise ValueError("integer binary labels required")
    if set(y) != {0,1}:
        raise ValueError("both classes required with an unpenalized intercept")
    p = len(x[0])
    if any(len(row) != p for row in x) or not all(math.isfinite(v) for row in x for v in row):
        raise ValueError("finite rectangular features required")
    if not math.isfinite(penalty) or penalty <= 0 or not math.isfinite(tol) or tol <= 0:
        raise ValueError("positive finite penalty and tolerance required")
    if type(max_steps) is not int or max_steps < 1:
        raise ValueError("positive integer step limit required")
    a = [[1.0]+row for row in x]
    bound = math.fsum(v*v for row in a for v in row)/(4*len(y))+penalty
    if not math.isfinite(bound):
        raise ValueError("feature scale is outside this example's range")
    theta = [0.0]*(p+1)
    for step in range(max_steps+1):
        value,gradient = value_gradient(a,y,theta,penalty)
        violation = max(abs(g) for g in gradient)
        if violation <= tol:
            return theta,value,violation,step
        if step == max_steps:
            break
        theta = [t-g/bound for t,g in zip(theta,gradient)]
    raise RuntimeError("gradient tolerance not reached within max_steps")

x = [[-1]]*4+[[1]]*4
y = [0,0,0,1,0,1,1,1]
theta,value,gradient_size,steps = fit_logistic(x,y,.1)
assert abs(theta[0]) < 1e-9
assert math.isclose(theta[1],.7368761691015351,abs_tol=1e-8)
a = [[1.0]+row for row in x]
plain,gradient = value_gradient(a,y,[0,math.log(3)],0)
assert max(map(abs,gradient)) < 1e-14
assert math.isclose(plain,.5623351446188084)
assert binary_loss(1000,0) == 1000
assert math.isfinite(binary_loss(-1000,1))

The first returned coefficient is the intercept. The internal value_gradient helper assumes already validated matching arrays; the fitter validates its public inputs. A gradient evaluation costs O(n(p+1))O(n(p+1)) arithmetic for pp original features, so TT updates cost O(Tn(p+1))O(Tn(p+1)), with O(np+n+p)O(np+n+p) storage including copied data. Empty feature rows are allowed for an intercept-only baseline. An explicit dense Hessian would cost O(n(p+1)2)O(n(p+1)^2) to construct; this implementation does not use one.

The returned gradient tolerance records approximate stationarity. The iteration cap can still be reached for poorly scaled features, and a finite input can produce an unrepresentable intermediate dot product or squared norm. Rescale the data rather than interpreting such failures as statistical evidence. Extreme correct predictions may numerically underflow to loss zero; the exact mathematical probability remains below one. Stable arithmetic reduces avoidable errors, not the finite range of floating point.

Separation can send the maximum to infinity

Take only (x,y)=(−1,0),(1,1)(x,y)=(-1,0),(1,1) and set b=0,w=sb=0,w=s. Their average unpenalized loss is log⁡(1+e−s)\log(1+e^{-s}). It decreases toward zero as s→∞s\to\infty but stays positive for every finite ss. The data are completely separated: a direction gives strictly positive signed margins for all observations. There is no finite MLE, even though the finite-parameter Hessian is positive definite and gradients become arbitrarily small. Geyer’s notes, Sections 9–10 distinguish finite estimates from these limiting models.

Quasi-complete separation is subtler. Add the conflicting points (0,0),(0,1)(0,0),(0,1). Along the same direction, those two margins are zero while the others are positive. With b=0,w=s→∞b=0,w=s\to\infty, average loss approaches (log⁡2)/2(\log2)/2, and again no finite parameter attains the best likelihood. When complete separation is absent, a weak separating direction with at least one positive and one zero margin gives quasi-complete separation. A direction making every margin zero can instead be simple non-identifiability.

Positive slope regularization handles the separating slope in these examples. It does not fix every existence issue: if all labels equal 1, the unpenalized intercept can still increase without bound while slopes stay zero. That is why the teaching fitter requires both classes. Penalizing the intercept would define another model, and should be stated explicitly.

A straight logit boundary may also be inappropriate. Feature transformations can model nonlinear boundaries, but fitting more features does not establish calibration or good future performance. Collinearity, population changes, outcome selection and inaccurate labels can all affect interpretation. A coefficient’s conditional odds ratio is not automatically a causal effect. Compare predictive log loss and calibration against a simpler baseline, as well as classification accuracy at a stated threshold.

Separate the probability, objective and decision

  1. In the opening data, why is the unpenalized slope log⁡3\log3 rather than 3/43/4? Answer: slopes act on log-odds. The logits at x=±1x=\pm1 are ±log⁡3\pm\log3, which invert to probabilities 1/41/4 and 3/43/4.
  2. Does a small gradient prove that a finite logistic MLE exists? Answer: no. In the two-point separated example, loss and gradient approach zero while the slope grows without bound.
  3. If every label is 1, does a positive penalty on slopes alone give a finite estimate? Answer: no. Set slopes to zero and increase the unpenalized intercept. The likelihood keeps improving.
  4. What loss should a prediction with logit 1000 incur when the true label is 0? Answer: approximately 1000. The stable formula returns a finite value; computing e1000e^{1000} first would overflow even though the loss itself is representable.

A small model with separate statistical and numerical questions

Logistic regression links Bernoulli likelihoods, generalized linear models and convex optimization. Newton and IRLS use curvature; gradient methods use cheaper iterations; L1 penalties introduce nonsmooth coordinates and require an appropriate proximal or coordinate method. The algorithm, the penalty and the feature representation should each be named when comparing results.

Start with an intercept-only model and a clear evaluation split. Then test whether features improve probability forecasts, not merely whether the optimizer reduces training loss. A model may rank cases usefully while overstating confidence, or supply reasonable probabilities while a poor decision threshold causes expensive errors. Keeping these questions separate makes the method easier to debug and its results easier to trust.

Make a prediction, then check

The data are only (x,y)=(-1,0),(1,1), with no logistic penalty. An optimizer reports a tiny gradient at a very large slope. What follows?

Choose one answer

Learning objectives

  • Derive averaged log loss, gradient and Hessian from a conditional Bernoulli likelihood, separating probabilities, odds and odds ratios.
  • Fit a regularized model with stable signed-margin loss and a conservative gradient step, explaining iteration cost, storage and numerical boundaries.
  • Use complete and quasi-complete separation to explain absent finite MLEs, distinguishing strict convexity, stationarity tolerances and existence.

Prerequisites & connections

Explore related knowledge →

References

  1. Data Mining — Lecture 7: Logistic Regression
    Cosma Rohilla Shalizi; Carnegie Mellon University · 2020
  2. Regularization Paths for Generalized Linear Models via Coordinate Descent — author manuscript, 29 April 2009
    Jerome Friedman; Trevor Hastie; Robert Tibshirani · 2009
  3. Stat 5421 Lecture Notes: Completion of Exponential Families
    Charles J. Geyer; University of Minnesota · 2026

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex multi-agent technical check: primary-source verification, derivation and numerical assertions, bilingual comparison, and review by another agent or the parent; no independent human peer review.

  • Inspected the specified CMU lecture, Stanford manuscript and Geyer passages; derived conditional independence, loss averaging, gradient/Hessian, finite-solution restrictions and separation counterexamples.
  • Checked gradients and Hessians on 12 datasets by finite differences of objective values and gradients; compared the fitter to an exact grouped likelihood, independent bisection roots for four penalties, and the closed-form intercept-only fit.
  • Checked the actual descent bound over 30 Lipschitz steps, complete/quasi-complete separation limits, logits ±1000, one-class and invalid inputs, and iteration caps; matched bilingual code, formulas, anchors and all four answers.
  • Independent cross-review checked conditional likelihood, stable signed margins, full gradients/Hessians, strict convexity without a finite MLE, and existence with penalized slopes/unpenalized intercept. Geyer’s dynamic page was reverified as the 2026-08-26 version.
  • The parent executed all 37 independent classical-method checks successfully; bilingual code, display equations, six main anchors and four answered exercises were individually compared.

Source locations checked:

  • Data Mining — Lecture 7: Logistic Regression · Read Think About the Likelihood, Logistic Regression, How to Estimate the Model, and Backup: Optimizing the Likelihood (approximately rendered lines 116–181 and 206–221): conditional Bernoulli likelihood, logit parametrization and optimization. Article corrects source shorthand that labels odds p/(1−p) an odds ratio; avoids its closed-interval logit domain and blanket no-closed-form wording by supplying an exact grouped-data example.
  • Regularization Paths for Generalized Linear Models via Coordinate Descent — author manuscript, 29 April 2009 · 2009-04-29 author manuscript, PDF pp. 9–11 section 3, equations 11–18: logistic likelihood, weighted quadratic approximation, p(1−p) curvature and upper bound 1/4. Teaching implementation is original full-gradient L2 optimization with a Frobenius-norm Lipschitz bound, not a reproduction of glmnet or its coordinate IRLS code.
  • Stat 5421 Lecture Notes: Completion of Exponential Families · Official page reopened on 2026-09-05; title and byline show Charles J. Geyer and August 26, 2026 (rendered lines 0–3). Inspected sections 3–4 on existence, recession and constancy, section 9 on separation versus degeneracy, sections 10.1–10.2 on complete separation, 10.4 on stable likelihood/gradient computation, and 13.1–13.2 on quasi-complete separation. Derived the two- and four-observation examples directly; stated both-class and positive-slope-penalty restrictions for the finite-unique teaching fit. No claim to have reviewed every section of the long note.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.