AI Wiki中文/EN

Multinomial logistic regression: fitting a joint class distribution

多项逻辑回归

Fit multiclass linear logits with stable cross-entropy, check gradients and parameter shifts, and distinguish joint softmax training from one-vs-rest.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Choose one label from several alternatives

Suppose a laboratory sorts readings into three mutually exclusive signal classes. Each observation has two numeric features and exactly one correct class. Three independent yes/no scores would not automatically describe a single choice: all three could be high at once.

Multinomial logistic regression fits the classes jointly. Each class gets an affine score, and one shared softmax denominator turns those scores into a categorical distribution. “Multinomial” here names the classification model; it is not polynomial regression, and this implementation does not model several simultaneous labels.

The binary logistic regression, softmax and cross-entropy chapters supply the building blocks. This chapter connects them into a fitted multiclass model, including the choices that make its parameters interpretable. Stanford’s CS229 §2.3 derives the joint likelihood and gradient. Notes dated August 23, 2026, pp. 25–27.

Only score differences determine probabilities

For K mutually exclusive classes, let wₖ be a feature-weight vector and bₖ an intercept. With fixed input features x:

zk=wk⊤x+bk,pk(x)=ezk∑r=0K−1ezr,log⁡pk(x)pl(x)=(wk−wl)⊤x+bk−bl.z_k=w_k^\top x+b_k,\qquad p_k(x)=\frac{e^{z_k}}{\sum_{r=0}^{K-1}e^{z_r}},\qquad\log\frac{p_k(x)}{p_l(x)}=(w_k-w_l)^\top x+b_k-b_l.

Pairwise log odds are affine in the supplied features. An equal-score boundary is a hyperplane when the two slope vectors differ. Softmax makes the probabilities nonlinear in x; it does not create curved decision boundaries in an unchanged feature space.

Adding the same vector v to every class’s weights and the same scalar c to every intercept leaves all probabilities unchanged. Consequently, an unrestricted unpenalized parameterization is not identifiable:

wk′=wk+v,bk′=bk+c⟹pk′(x)=pk(x).w_k'=w_k+v,\quad b_k'=b_k+c\quad\Longrightarrow\quad p_k'(x)=p_k(x).

One convention fixes a reference class’s score to zero and uses K−1 vectors. Another, used below, keeps K symmetric rows and requires the sum over classes of each weight coordinate and of the intercepts to be zero. Subtracting class means enforces that convention. It removes common-score shifts, not every ambiguity caused by redundant input features. The scikit-learn documentation discusses the K versus K−1 choice and why regularization makes the parameterization matter. Version 1.7, multinomial case.

For n examples with class IDs yᵢ, this program minimizes average cross-entropy plus a symmetric slope penalty:

J(W,b)=−1n∑i=1nlog⁡pyi(xi)+λ2∑k=0K−1∥wk∥22,λ≥0.J(W,b)=-\frac1n\sum_{i=1}^n\log p_{y_i}(x_i)+\frac\lambda2\sum_{k=0}^{K-1}\|w_k\|_2^2,\qquad\lambda\ge0.

Intercepts are not penalized. This is the stated average-loss convention; a summed loss needs a correspondingly rescaled penalty. It is not safe to copy a package’s parameter named C or alpha without checking that package’s objective.

The data term is invariant to common-score shifts. With a positive slope penalty, centering the class weight rows also chooses the lowest-penalty representative among those shifts. Fixing a reference row to zero and penalizing only the remaining rows generally defines a different regularizer.

Differentiating gives one coupled residual for every class:

∂J∂wk=1n∑i(pk(xi)−1[yi=k])xi+λwk,∂J∂bk=1n∑i(pk(xi)−1[yi=k]).\frac{\partial J}{\partial w_k}=\frac1n\sum_i(p_k(x_i)-\mathbf1[y_i=k])x_i+\lambda w_k,\qquad\frac{\partial J}{\partial b_k}=\frac1n\sum_i(p_k(x_i)-\mathbf1[y_i=k]).

The probability covariance matrix diag(p)−ppᵀ is positive semidefinite, so cross-entropy is convex in these linear parameters; the quadratic penalty preserves convexity. That does not make a fixed number of gradient steps an exact solution. Without regularization, separable data can drive weight magnitudes upward while the loss approaches an unattained infimum.

One shared likelihood is different from one-vs-rest

One-vs-rest trains K separate binary losses. Its sigmoid scores need not sum to one. Even normalizing them afterward does not turn that training objective into the joint categorical likelihood. For scores (2,0,−1), softmax gives approximately (0.8438,0.1142,0.0420); the separate sigmoid scores sum to about 1.6497. Renormalizing those sigmoid scores gives a different vector. This is a numerical comparison of transformations, not an accuracy contest between trained systems. The official solver discussion identifies the separate binary approach. scikit-learn 1.7, solver distinctions.

Compute loss from logits, then update all classes

For m = maxₖ zₖ, the loss for one observed class y can be computed as:

−log⁡py=(m−zy)+log⁡∑kezk−m.-\log p_y=(m-z_y)+\log\sum_k e^{z_k-m}.

Every exponential argument is nonpositive. The code calculates this expression directly, rather than taking the logarithm of a probability that may already have underflowed to zero. The example has logits (1000,999,−1000): the displayed probability of class 2 rounds to zero, but its loss remains about 2000.313262.

The complete Python 3.10+ program uses full-batch gradient descent, zero initialization and class-mean centering after each step. It returns the final objective, gradient norm and actual step count. It has no stopping-tolerance or line-search implementation. A poor learning rate can increase the objective or produce a numerical-range error.

Training inputs are nonempty rectangular lists/tuples of finite real numbers. Labels must be integers from 0 through K−1, with K at least 2; Booleans are rejected. This teaching interface requires every declared class to occur in training. Zero features are allowed for an intercept-only model. Zero optimization steps return the initial uniform predictor, not a fitted optimum. Prediction accepts an unmodified returned model; ties in maximum logits choose the smallest class ID. Empty prediction input returns an empty tuple.

The code uses input coordinates as supplied. It does not learn a scaler and does not require a manually added constant feature: intercepts are stored separately. If scaling is needed, fit it on training data and apply the same transformation at prediction. Scaling changes both gradient-descent geometry and the meaning of a coefficient penalty; “the same lambda” in two feature coordinate systems need not imply the same model.

from math import exp, fsum, hypot, isfinite, log


def seq(value):
    if type(value) not in (list, tuple):
        raise ValueError('expected list or tuple')
    return value


def real(value):
    if type(value) not in (int, float):
        raise ValueError('expected finite real number, not Boolean')
    try:
        value = float(value)
    except OverflowError as error:
        raise ValueError('number outside floating-point range') from error
    if not isfinite(value):
        raise ValueError('number must be finite')
    return value


def matrix(rows, width=None):
    rows = tuple(tuple(real(x) for x in seq(row)) for row in seq(rows))
    if rows and width is None:
        width = len(rows[0])
    if any(len(row) != width for row in rows):
        raise ValueError('inconsistent feature width')
    return rows


def probabilities_loss(scores, label=None):
    # Internal primitive: nonempty finite logits; optional valid target label.
    if not all(isfinite(s) for s in scores):
        raise ValueError('nonfinite logits; rescale data or reduce step size')
    high = max(scores)
    shifted = [s - high for s in scores]
    exponentials = [exp(s) for s in shifted]
    total = fsum(exponentials)
    loss = None if label is None else log(total) - shifted[label]
    if loss is not None and not isfinite(loss):
        raise ValueError('loss outside floating-point range')
    return tuple(e / total for e in exponentials), loss


def loss_gradient(X, y, W, bias, penalty):
    # Internal helper; shapes, labels and scalars have already been validated.
    n, K, d = len(X), len(W), len(W[0])
    gW = [[0.0] * d for _ in range(K)]
    gb = [0.0] * K
    losses = []
    for row, label in zip(X, y):
        scores = [fsum(w * x for w, x in zip(W[k], row)) + bias[k] for k in range(K)]
        probability, loss = probabilities_loss(scores, label)
        losses.append(loss)
        for k in range(K):
            error = (probability[k] - (k == label)) / n
            gb[k] += error
            for j in range(d):
                gW[k][j] += error * row[j]
    for k in range(K):
        for j in range(d):
            gW[k][j] += penalty * W[k][j]
    value = fsum(losses) / n + penalty * fsum(w * w for row in W for w in row) / 2
    if not isfinite(value):
        raise ValueError('objective outside floating-point range')
    return value, gW, gb


def fit(rows, labels, classes, steps=400, rate=0.2, penalty=0.05):
    X, y = matrix(rows), tuple(seq(labels))
    if not X or len(X) != len(y):
        raise ValueError('nonempty equally sized training inputs required')
    if type(classes) is not int or classes < 2:
        raise ValueError('classes must be an integer at least 2')
    if any(type(t) is not int or not 0 <= t < classes for t in y):
        raise ValueError('labels must be integer class IDs')
    if set(y) != set(range(classes)):
        raise ValueError('this teaching fit requires every class to occur')
    if type(steps) is not int or steps < 0:
        raise ValueError('steps must be a nonnegative integer')
    rate, penalty = real(rate), real(penalty)
    if rate <= 0 or penalty < 0:
        raise ValueError('positive rate and nonnegative penalty required')
    K, d = classes, len(X[0])
    W, bias = [[0.0] * d for _ in range(K)], [0.0] * K
    for _ in range(steps):
        _, gW, gb = loss_gradient(X, y, W, bias, penalty)
        for k in range(K):
            bias[k] -= rate * gb[k]
            for j in range(d):
                W[k][j] -= rate * gW[k][j]
        # Choose a symmetric representative of the common-logit shift freedom.
        mean = fsum(bias) / K
        bias = [b - mean for b in bias]
        for j in range(d):
            mean = fsum(W[k][j] for k in range(K)) / K
            for k in range(K):
                W[k][j] -= mean
    value, gW, gb = loss_gradient(X, y, W, bias, penalty)
    gradient_norm = hypot(*gb, *(v for row in gW for v in row))
    if not isfinite(gradient_norm):
        raise ValueError('gradient outside floating-point range')
    return {'W': tuple(tuple(row) for row in W), 'bias': tuple(bias),
            'loss': value, 'gradient_norm': gradient_norm, 'steps': steps}


def predict(model, rows):
    # model is an unmodified result of fit; raw input coordinates are preserved.
    W, bias = model['W'], model['bias']
    X = matrix(rows, len(W[0]))
    result = []
    for row in X:
        scores = [fsum(w * x for w, x in zip(weight, row)) + b for weight, b in zip(W, bias)]
        probability, _ = probabilities_loss(scores)
        label = max(range(len(W)), key=lambda k: scores[k])
        result.append((label, probability))
    return tuple(result)


if __name__ == '__main__':
    X = ((-1,-1), (-.8,-1.2), (1,-1), (.8,-1.2), (0,1), (.2,.8))
    y = (0,0,1,1,2,2)
    model = fit(X, y, 3)
    print('training labels:', tuple(k for k, p in predict(model, X)))
    print('objective / gradient norm:', round(model['loss'], 6), round(model['gradient_norm'], 6))
    print('at origin:', tuple(round(p, 6) for p in predict(model, ((0,0),))[0][1]))
    p, loss = probabilities_loss((1000,999,-1000), 2)
    print('extreme logits:', tuple(round(x, 6) for x in p), round(loss, 6))
    print('zero-step tie:', predict(fit(X, y, 3, steps=0), ((0,0),))[0][0])

Actual output:

training labels: (0, 0, 1, 1, 2, 2)
objective / gradient norm: 0.304826 9.1e-05
at origin: (0.244674, 0.221407, 0.53392)
extreme logits: (0.731059, 0.268941, 0.0) 2000.313262
zero-step tie: 0

The six points are an authored demonstration with two dimensionless features, not a benchmark. Correct training labels do not demonstrate generalization or calibration. The nonzero reported gradient norm makes the finite optimization state visible. The origin prediction is a probability vector, not evidence that class 2 is certain.

For n observations, d input features, K classes and t update steps, the retained-data implementation has costs:

Tfit=O((t+1)nK(d+1)),Sfit=O(n(d+1)+K(d+1)).T_{\mathrm{fit}}=O((t+1)nK(d+1)),\qquad S_{\mathrm{fit}}=O(n(d+1)+K(d+1)).

The final objective/gradient evaluation accounts for t+1. The d+1 terms include intercept-only input, and n≥1, K≥2 cover constant work. Predicting m rows costs O(1+mK(d+1)) arithmetic operations and retains O(1+m(d+K+1)) extra input/output storage, apart from the model. These bounds treat floating arithmetic and class IDs as unit cost; unusually large integers have conversion costs. Public input validation and internal helper contracts are distinguished in the comments.

A probability vector is not a calibration guarantee

The classes must express one exclusive outcome. Multilabel tasks need another observation model. Class IDs have no numeric distance: confusing class 0 with class 2 is not inherently twice as costly as confusing it with class 1. If mistakes have different costs, the decision rule must express them instead of blindly choosing the maximum probability.

Useful evaluation includes held-out cross-entropy and class-specific errors, not only training accuracy. Class imbalance and changes in class frequency can affect the fitted intercepts and later probabilities. Good calibration must be measured; normalization alone does not establish it.

The common-shift constraint is a coordinate convention. It does not reveal a unique physical contribution for each raw coefficient, fix feature collinearity or validate causal explanations. Ridge regularization controls slope magnitude in the chosen units, and the intercepts remain free. The code deliberately rejects missing training classes rather than letting an unsupported intercept drift toward negative infinity.

A production fit needs appropriate scaling, convergence criteria and numerical safeguards beyond this compact teaching optimizer. Nonfinite inputs are rejected; extreme finite values or excessive step sizes may still exceed arithmetic range. No training-data result here claims that the same settings suit arbitrary data.

Check the objective before comparing coefficients

  1. Add 7 to every class intercept. What happens to probabilities and to this program’s penalty? What if the same nonzero vector is added to every class weight row?

    Answer: Probabilities do not change in either case. The intercept shift also leaves this penalty unchanged because intercepts are excluded. A common weight shift generally changes the penalty; starting from centered rows, it adds lambda times K times the squared shift norm, divided by two.

  2. A three-class zero-logit model predicts each class with probability one-third. Three independent zero-logit binary models each predict one-half. Is normalizing the binary outputs enough to make their fitting procedures identical?

    Answer: No. At that special point the normalized numbers agree, but the losses and their gradients remain different. For general logits even the transformed probability vectors differ, as the (2,0,−1) example demonstrates.

  3. The true-class probability underflows to zero for logits (1000,999,−1000). Is the cross-entropy necessarily infinite? Has 400 gradient steps necessarily reached an optimum?

    Answer: The real-valued loss is finite: 2000 + log(1+exp(−1)+exp(−2000)), approximately 2000.313262. Directly taking log of the rounded zero would lose that information. A fixed step count is not a convergence certificate; inspect the objective, gradient and solver behavior.

  4. For two classes, centered slopes are w₀ = −v/2 and w₁ = v/2. Express the slope penalty using v. Can its lambda be copied unchanged into a binary objective with penalty lambda times ||v||²/2?

    Answer: The log-odds slope is v, but the two-row penalty is lambda times ||v||²/4. Copying lambda into the stated single-vector penalty doubles its strength. Intercepts still enter through their difference and are not penalized here.

Use the likelihood and the parameter convention together

The Stanford source is the author-maintained CS229 notes by Tengyu Ma and Andrew Ng, dated August 23, 2026. Section 2.3, pp. 25–27, derives multiclass probabilities, negative log-likelihood and the probability-minus-indicator gradient. Only those relevant pages and the version header were used; no claim is made about the rest of the 278-page file.

The second source is scikit-learn’s fixed 1.7 documentation path, displayed as 1.7.2. Its multinomial section distinguishes K-row and reference-class parameterizations; its solver section distinguishes joint multinomial optimization from one-vs-rest. The program here implements its explicitly written objective, not a copy of a package solver or its C convention.

Tests independently differentiate a 70-digit Decimal objective at a small parameter array, check the binary reduction and common-shift invariance, and verify an intercept-only optimum against class frequencies. Class relabeling preserves predictions under the symmetric fit. These checks are small and targeted; the data, code and exercises are original, and no library or course implementation is copied.

Make a prediction, then check

Add the same constant to every class intercept in this model. What changes?

Choose one answer

Learning objectives

  • Derive the joint multiclass likelihood and explain why normalizing independent binary scores does not change their training objective.
  • Identify common-score shifts and compare a centered K-row penalty with a reference-class penalty.
  • Compute stable logit cross-entropy, check gradients and assess a finite-step fit without claiming convergence or calibration.

Prerequisites & connections

Explore related knowledge →

References

  1. CS229 Lecture Notes — section 2.3, Multi-class classification
    Tengyu Ma and Andrew Ng · 2026
  2. scikit-learn 1.7 — Multinomial logistic regression and solver distinctions
    scikit-learn developers

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.

  • Both locales contain six stable anchors, six identical display formulas, identical full Python and actual five-line output, and four answered exercises. Reread under the pinned Humanizer guidance. Distinguishes mutually exclusive outcomes from multilabel, joint likelihood from one-vs-rest, common shifts from feature collinearity, and normalized probabilities from calibrated predictions.
  • Eight tests passed. A separate 70-digit Decimal objective checks the objective and 18 central-difference gradient coordinates at two penalties. Also checked the binary sigmoid reduction, extreme logits with finite loss despite probability underflow, common shifts and their penalty increment, class relabeling, and an intercept-only fit against class frequencies.
  • Verified zero-step ties, empty prediction, input immutability, centered parameters and 17 invalid training/hyperparameter/prediction cases. The six-point demonstration gives objective 0.304826 and gradient norm about 0.000091 after 400 steps; no generalization, convergence or calibration conclusion follows. Tests load both code and expected output from article fences through one article_text path function.
  • Strict MDX/KaTeX evaluation and actual React HTML passed with six displays, six headings and four answers per locale; the complete fitting-cost annotation was inspected. Costs include intercept-only data, final gradient evaluation, retained training data and constant empty-prediction storage. The program is original Python 3.10+ standard library, with no automatic scaler or production optimizer claim. AI author checks only; review remains written pending independent cross-review.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.

Source locations checked:

  • CS229 Lecture Notes — section 2.3, Multi-class classification · Opened the official PDF through web and read the cover date/authors. Section 2.3 printed pages 25–27 corresponds to PDF indices 25–27: extracted lines 1364–1394 define exclusive classes and K weight groups; 1395–1481 give normalized logits; 1482–1516 give likelihood/loss; 1517–1592 derive the residual and parameter gradient. Checked the actual 278-page file, not all its content. No local PDF hash, independent visual screenshot audit or Stanford implementation execution is claimed.
  • scikit-learn 1.7 — Multinomial logistic regression and solver distinctions · Opened the official versioned HTML through web. Read section 1.1.11.2, lines 535–560, for K versus K−1, nonuniqueness, symmetry and regularization; lines 515–534 for package objective context; and solver lines 562–586, particularly liblinear one-vs-rest and solver-specific intercept handling. Did not adopt a comparative calibration claim or infer an exact C-to-lambda conversion. No library source was copied or executed.
  • CS229 Lecture Notes — section 2.3, Multi-class classification · Actually read official 278-page PDF header: Tengyu Ma and Andrew Ng, August 23, 2026. Read section 2.3 printed pages 25–27, web lines 1364–1592: exclusive classes, joint softmax likelihood and probability-minus-indicator gradient. Text extraction only; no full-file visual review or immutable-version claim.
  • scikit-learn 1.7 — Multinomial logistic regression and solver distinctions · Actually read official HTML displaying 1.7.2, section 1.1.11.2 lines 535–560 and solver discussion 562–586; checked K versus K−1 parameters, symmetric regularization and one-vs-rest distinction. Read objective context 515–534; no package execution or C mapping inferred.

Related topics

No matches. Try a synonym or acronym.

0 results shown

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