Machine Learning

Multinomial Logistic Regression

Softmax regression turns one score per class into a normalized probability distribution and learns by moving probability mass toward the observed class.

status: publishedimportance: criticaldifficulty 3/5math: undergraduateread: 18mlive demo

Concept Structure

Multinomial Logistic Regression

01Intuition

Start with the picture, metaphor, or geometric mechanism.

02Math

Make the objects explicit and connect them with notation.

03Code

Mirror the equations with runnable implementation details.

04Interactive Demo

Manipulate the mechanism and watch the idea respond.

2prerequisites
1next concepts
3related links

Learning map

Multinomial Logistic Regression
BeforeLogistic RegressionNow4/4 sections readyTryManipulate one control and predict the visible change.NextScaled Dot-Product Attention & Transformer Layers

Object flow

4/4 sections readyAsk about thisResearch room
ConceptMultinomial Logistic RegressionMachine Learning
2 sources attachedLocal snapshot ready
concept:machine-learning/multinomial-logistic-regression

Conceptual Bridge

What should feel connected as you move through this page.

Carry inLogistic Regression

Bring the mental model from Logistic Regression; this page will reuse it instead of restarting from zero.

Work hereMultinomial Logistic Regression

Softmax regression turns one score per class into a normalized probability distribution and learns by moving probability mass toward the observed class.

Carry outScaled Dot-Product Attention & Transformer Layers

The next edge should feel earned: use the demo prediction here before following Scaled Dot-Product Attention & Transformer Layers.

Test the linkManipulate one control and predict the visible change.Then continue to Scaled Dot-Product Attention & Transformer Layers
01

01

Intuition

Build the mental picture first so the rest of the page has something to attach to.

Section prompt

You are here because a language model, image classifier, and attention mechanism all need the same basic move: turn a list of scores into a distribution. Binary logistic regression has one logit. Softmax regression has one logit per class.

Before this, know logistic regression and cross-entropy. By the end, you should be able to explain why softmax probabilities sum to one, why adding the same constant to every logit changes nothing, and why the logit gradient is qk1[k=y]q_k-\mathbf 1[k=y].

Imagine three labels: cat, dog, and bird. The model gives each label a score. A score by itself is not a probability because scores can be negative, large, or unnormalized. Softmax exponentiates the scores and normalizes them:

qk=exp(zk)jexp(zj).q_k=\frac{\exp(z_k)}{\sum_j \exp(z_j)}.

The highest score gets the largest probability, but every class competes through the denominator. Raising one logit steals probability mass from the others.

Softmax also has a useful invariance. If you add the same number cc to every logit, every exponential is multiplied by exp(c)\exp(c), and that factor cancels:

softmax(z+c1)=softmax(z).\operatorname{softmax}(z+c\mathbf 1)=\operatorname{softmax}(z).

That is why stable implementations subtract the maximum logit before exponentiating. It changes the numbers used internally, not the distribution.

02

02

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

Section prompt

For one input xRdx\in\mathbb R^d and KK classes, collect class weights in WRK×dW\in\mathbb R^{K\times d} and biases in bRKb\in\mathbb R^K. The logit vector is

z=Wx+bRK.z=Wx+b\in\mathbb R^K.

The predicted class distribution is

qk=Pθ(Y=kx)=exp(zk)j=1Kexp(zj).q_k=P_\theta(Y=k\mid x)=\frac{\exp(z_k)}{\sum_{j=1}^K \exp(z_j)}.

If the observed class is y{1,,K}y\in\{1,\dots,K\}, the likelihood is qyq_y. The negative log-likelihood is

(z,y)=logqy.\ell(z,y)=-\log q_y.

Substituting the softmax gives the log-sum-exp form:

(z,y)=zy+logj=1Kexp(zj).\ell(z,y)=-z_y+\log\sum_{j=1}^K \exp(z_j).

Now differentiate with respect to one logit zkz_k:

zk=exp(zk)jexp(zj)1[k=y]=qk1[k=y].\frac{\partial \ell}{\partial z_k} = \frac{\exp(z_k)}{\sum_j \exp(z_j)}-\mathbf 1[k=y] = q_k-\mathbf 1[k=y].

That is the multi-class version of the logistic-regression signal qyq-y. The correct class has a negative gradient unless it already has probability near 11, so gradient descent raises its logit. Incorrect classes have positive gradients, so gradient descent lowers their logits.

For a batch with design matrix XRn×dX\in\mathbb R^{n\times d}, one-hot labels YRn×KY\in\mathbb R^{n\times K}, probabilities QRn×KQ\in\mathbb R^{n\times K}, and weights WRd×KW\in\mathbb R^{d\times K}, one common convention writes logits as

Z=XW+1bT.Z=XW+\mathbf 1b^{\mathsf T}.

The average-loss gradients are

WL=1nXT(QY),\nabla_W L=\frac1n X^{\mathsf T}(Q-Y),

and

bL=1ni=1n(QiYi).\nabla_b L=\frac1n\sum_{i=1}^n (Q_i-Y_i).

The notation differs by whether examples are rows or columns, but the invariant is stable: softmax plus cross-entropy creates a probability-error vector over classes.

03

03

Code

Keep the implementation aligned with the notation so the algorithm is legible.

Section prompt
import numpy as np

# Three-class softmax regression on tiny 2D points.
# Shapes: X is (n, 3) with bias column, W is (3, K).
X_raw = np.array([[-2, 0], [-1, 1], [0, -1], [1, 1], [2, 0], [1, -2]], float)
y = np.array([0, 0, 1, 1, 2, 2])
K = 3
X = np.column_stack([np.ones(len(X_raw)), X_raw])
Y = np.eye(K)[y]
W = np.zeros((X.shape[1], K))

def softmax(z):
    z = z - z.max(axis=1, keepdims=True)
    exp_z = np.exp(z)
    return exp_z / exp_z.sum(axis=1, keepdims=True)

for step in range(120):
    logits = X @ W
    Q = softmax(logits)
    grad = X.T @ (Q - Y) / len(X)
    W -= 0.7 * grad

Q = softmax(X @ W)
loss = -np.mean(np.log(Q[np.arange(len(y)), y] + 1e-12))
print("class probabilities:")
print(np.round(Q, 3))
print("loss:", round(loss, 4))
print("first example logit gradient:", np.round(Q[0] - Y[0], 3))
print("row sums:", np.round(Q.sum(axis=1), 6))

The code mirrors the math: softmax normalizes logits row by row, Q - Y is the probability-error matrix, and X.T @ (Q - Y) / n is the weight gradient.

04

04

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

Section prompt

Set three logits and choose the true class. Before revealing the gradient, predict the shape of the update: does one wrong class nearly match the true-class upward push, is the wrong probability mass split across wrong classes, or are all updates already small?

The reveal shows the invariant that is easy to miss: for one example, the true-class upward update has magnitude 1qy1-q_y, while all wrong-class downward updates sum to the same amount. A single wrong class can nearly tie the true-class push, but it cannot be larger unless the demo has changed the object being measured. The shared-shift slider adds the same value to every logit. Watch the raw scores move while the probabilities and gradients stay fixed. That small invariant is the bridge from classical softmax regression to stable neural-network implementations.

Live Concept Demo

Explore Multinomial Logistic Regression

The stage is code-native and interactive. Use it to test the explanation against the mechanism.

difficulty 3/5undergraduatecode-aligned
Demo Prediction Checkpoint

Manipulate one control and predict the visible change.

Commit to what Multinomial Logistic Regression should make visible before reading the result.

After The First Pass

Turn the concept into an inspected object.

Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.

Mechanism Storyboard

See the idea move before the page explains it

Softmax regression turns one score per class into a normalized probability distribution and learns by moving probability mass toward the observed class.

Prediction open01 / Intuition
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change Multinomial Logistic Regression should make visible.

Visual Inquiry

Make the image answer a mathematical question

Softmax regression turns one score per class into a normalized probability distribution and learns by moving probability mass toward the observed class.

4/4 stages readyLive demo connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make Multinomial Logistic Regression easier to reason about before the page gives the answer.

Source Grounding

Canonical references for the mechanism on this page.

course-notes · 2023CS229 Lecture Notes: Softmax RegressionStanford CS229

Curriculum source for softmax regression and multi-class likelihood.

Open source
bookDive into Deep Learning: Softmax RegressionZhang, Lipton, Li, and Smola

Curriculum source for logits, softmax probabilities, and implementation-oriented multi-class classification.

Open source

Claim Review

Softmax regression turns one score per class into a normalized probability distribution and learns by moving probability mass toward the observed class.

Status1 substantive review recorded

Claims without a substantive review badge still need exact source-support review.

Sources2 references

cs229-softmax-regression, d2l-softmax-regression

Witnesses4 local objects

Use equation, code, and demo objects to check whether the source support is operational.

Substantively reviewedFor one softmax-classification example, the gradient of negative log-likelihood with respect to each logit is predicted probability minus the one-hot label.Claim metadata: source checked

CS229 gives softmax logits, NLL/cross-entropy, and derivative phi_i - 1{y=i}; D2L independently derives softmax-cross-entropy derivative softmax(o)_j - y_j and the rowwise vectorized model.

Sources: CS229 Lecture Notes: Softmax Regression, Dive into Deep Learning: Softmax RegressionThis supports single-label softmax classification mechanics, not calibrated probabilities, multi-label classification, attention semantics, or any claim that one wrong class can exceed the total true-class push.A bounded review summary is present; still check caveats and exact source scope.

Checked CS229 section 2.3 and D2L section 4.1: both support softmax probabilities, one-hot labels, cross-entropy/NLL, and the logit derivative as predicted probability minus the label indicator. Prior GPT Pro blocker about the wrong-class update was resolved by teaching true-class push equals total wrong-class pull.

Reviewer: codex+gpt-pro-prior; reviewed 2026-06-28

Practice Loop

Try the idea before it explains itself

Softmax regression turns one score per class into a normalized probability distribution and learns by moving probability mass toward the observed class.

Readiness0/3 checks ready
Predict

Before touching the demo, predict one visible change that should happen in Multinomial Logistic Regression.

Hint 1

Reveal when your model needs a nudge.

Hint 2

Reveal when your model needs a nudge.

Hint 3

Reveal when your model needs a nudge.

Object research drawerClose
ConceptMultinomial Logistic RegressionMachine Learning

Research Room

Attach the question to an exact object

Pick the concept, equation, source, code witness, claim, misconception, or demo state before asking for help. The handoff stays grounded to that object.
Next local actionNo local draft saved yet

Open the draft below to save one note and next action in this browser.

conceptMachine Learning

Multinomial Logistic Regression

Anchored question

What is the smallest example that makes Multinomial Logistic Regression click without losing the math?

Local action draftNo local draft saved yetExpand only when ready to capture one local next action
Local action draft

This draft stays locally in this browser for concept:machine-learning/multinomial-logistic-regression.

No local draft saved.
Evidence to inspect
  • Source ids to inspect: cs229-softmax-regression, d2l-softmax-regression
  • Definition, prerequisite, and contrast concept links
  • The equation or code witness that makes the concept operational
  • One demo state that shows the invariant instead of a slogan
What would resolve this
  • The learner can state the mechanism in their own words
  • The learner can name the prerequisite that would repair confusion
  • The learner can predict how the mechanism changes under one perturbation
Grounded AI handoff

I am working in Continuous Function's research reading room. Object: concept - Multinomial Logistic Regression Object key: concept:machine-learning/multinomial-logistic-regression Context: Machine Learning Anchor id: concept/concept-notebook/machine-learning/multinomial-logistic-regression Open question: What is the smallest example that makes Multinomial Logistic Regression click without losing the math? Evidence to inspect: - Source ids to inspect: cs229-softmax-regression, d2l-softmax-regression - Definition, prerequisite, and contrast concept links - The equation or code witness that makes the concept operational - One demo state that shows the invariant instead of a slogan What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action.

Open source object
concept/concept-notebook/machine-learning/multinomial-logistic-regression concept:machine-learning/multinomial-logistic-regression