Multinomial Logistic Regression › Formula

Michael BrenndoerferJune 15, 202519 min read
Machine Learning from ScratchAll chapters
Part 4 of 9Regression Models
Chapter 38Multinomial Logistic Regression › Formula
Reading section 2 of 8 · Formula · 19 minSection 2 of 8 · 19 min

Book contents

Section 2 of 8 · 19 min read

Multinomial Logistic Regression › FormulaOne section · Sections in this chapter2 / 8 ↓
Reading tools Definitions & inline links

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

The mathematical foundation of multinomial logistic regression builds upon the principles of binary logistic regression, but extends them to handle multiple categories. Let's walk through the derivation step by step, starting with the most intuitive form and progressing to the matrix notation.

Basic Probability Model

We begin with the fundamental assumption that we have KK categories (where K≥3K \geq 3) and want to model the probability that observation ii belongs to category kk. Let's denote this probability as P(yi=k∣xi)P(y_i = k | \mathbf{x}_i), where xi\mathbf{x}_i represents the vector of predictor variables for observation ii.

The key insight is that we can model the log-odds of each category relative to a reference category. Without loss of generality, let's choose category KK as our reference category. The log-odds of category kk relative to category KK is:

log⁡(P(yi=k∣xi)P(yi=K∣xi))=βk0+βk1xi1+βk2xi2+⋯+βkpxip\log\left(\frac{P(y_i = k | \mathbf{x}_i)}{P(y_i = K | \mathbf{x}_i)}\right) = \beta_{k0} + \beta_{k1}x_{i1} + \beta_{k2}x_{i2} + \cdots + \beta_{kp}x_{ip}

where:

  • P(yi=k∣xi)P(y_i = k | \mathbf{x}_i) is the probability that observation ii belongs to category kk given its predictor values (the conditional probability we're modeling for the non-reference category)
  • P(yi=K∣xi)P(y_i = K | \mathbf{x}_i) is the probability that observation ii belongs to the reference category KK (the baseline category against which all others are compared)
  • βk0\beta_{k0} is the intercept for category kk (the baseline log-odds when all predictors are zero)
  • βkj\beta_{kj} is the coefficient for predictor jj in category kk (quantifies the effect of predictor jj on the log-odds of category kk relative to the reference category)
  • xijx_{ij} is the value of predictor jj for observation ii (the observed feature value)
  • pp is the total number of predictor variables (the dimensionality of the feature space)
  • KK is the reference category (chosen arbitrarily, typically the last category, with all its coefficients set to zero for identifiability)

From Log-Odds to Probabilities

To convert these log-odds back to probabilities, we need to solve for P(yi=k∣xi)P(y_i = k | \mathbf{x}_i). Let's define the linear predictor for category kk as:

ηik=βk0+βk1xi1+βk2xi2+⋯+βkpxip\eta_{ik} = \beta_{k0} + \beta_{k1}x_{i1} + \beta_{k2}x_{i2} + \cdots + \beta_{kp}x_{ip}

where:

  • ηik\eta_{ik} is the linear predictor for observation ii and category kk (a real-valued quantity that can take any value from −∞-\infty to +∞+\infty, representing the log-odds before normalization)

Then we can write:

log⁡(P(yi=k∣xi)P(yi=K∣xi))=ηik\log\left(\frac{P(y_i = k | \mathbf{x}_i)}{P(y_i = K | \mathbf{x}_i)}\right) = \eta_{ik}

Taking the exponential of both sides:

P(yi=k∣xi)P(yi=K∣xi)=eηik\frac{P(y_i = k | \mathbf{x}_i)}{P(y_i = K | \mathbf{x}_i)} = e^{\eta_{ik}}

This gives us:

P(yi=k∣xi)=P(yi=K∣xi)⋅eηikP(y_i = k | \mathbf{x}_i) = P(y_i = K | \mathbf{x}_i) \cdot e^{\eta_{ik}}

Normalization Constraint

Since all probabilities must sum to one, we have:

∑k=1KP(yi=k∣xi)=1\sum_{k=1}^{K} P(y_i = k | \mathbf{x}_i) = 1

Substituting our expression for P(yi=k∣xi)P(y_i = k | \mathbf{x}_i):

∑k=1KP(yi=K∣xi)⋅eηik=1\sum_{k=1}^{K} P(y_i = K | \mathbf{x}_i) \cdot e^{\eta_{ik}} = 1

Since P(yi=K∣xi)P(y_i = K | \mathbf{x}_i) is common to all terms, we can factor it out:

P(yi=K∣xi)∑k=1Keηik=1P(y_i = K | \mathbf{x}_i) \sum_{k=1}^{K} e^{\eta_{ik}} = 1

This gives us the probability of the reference category:

P(yi=K∣xi)=1∑k=1KeηikP(y_i = K | \mathbf{x}_i) = \frac{1}{\sum_{k=1}^{K} e^{\eta_{ik}}}

Final Probability Formula

Now we can express the probability of any category kk as:

P(yi=k∣xi)=eηik∑j=1KeηijP(y_i = k | \mathbf{x}_i) = \frac{e^{\eta_{ik}}}{\sum_{j=1}^{K} e^{\eta_{ij}}}

This is the softmax function, which ensures that all probabilities sum to one and are non-negative. Notice that when K=2K = 2, this reduces to the standard logistic regression formula.

Out[2]:
Visualization
Line plot showing softmax function maps linear predictors to probabilities.
The softmax function maps linear predictors (η values) into probabilities. As one linear predictor increases, its corresponding probability increases while others decrease proportionally. The mapping ensures all probabilities remain between 0 and 1 and sum to exactly 1.
Heatmap showing probability distribution across three classes.
This heatmap shows how the softmax function distributes probability mass across three classes as their linear predictors vary. When one class has a much larger η value, it captures most of the probability mass.

Matrix Notation

For computational efficiency and clarity, we can express the multinomial logistic regression model in matrix notation.

Let X\mathbf{X} be the n×(p+1)n \times (p+1) design matrix, where nn is the number of observations and pp is the number of predictors (the extra column accounts for the intercept). For each non-reference category kk (where k=1,…,K−1k = 1, \ldots, K-1), let βk\boldsymbol{\beta}_k be a (p+1)×1(p+1) \times 1 vector of coefficients. We stack these coefficient vectors horizontally to form a (p+1)×(K−1)(p+1) \times (K-1) coefficient matrix:

β=[β1,β2,…,βK−1]\boldsymbol{\beta} = [\boldsymbol{\beta}_1, \boldsymbol{\beta}_2, \ldots, \boldsymbol{\beta}_{K-1}]

where:

  • X\mathbf{X} is the n×(p+1)n \times (p+1) design matrix (includes a column of 1s for the intercept term, allowing matrix multiplication to compute all linear predictors)
  • nn is the number of observations in the dataset (the sample size)
  • pp is the number of predictor variables (the number of features, excluding the intercept)
  • βk\boldsymbol{\beta}_k is the (p+1)×1(p+1) \times 1 coefficient vector for category kk (includes the intercept βk0\beta_{k0} as the first element, followed by pp slope coefficients)
  • β\boldsymbol{\beta} is the (p+1)×(K−1)(p+1) \times (K-1) coefficient matrix for all non-reference categories (each column is a coefficient vector βk\boldsymbol{\beta}_k for one non-reference category)
  • KK is the total number of categories (including the reference category)

The linear predictors for all observations and all non-reference categories can be computed as:

η=Xβ\boldsymbol{\eta} = \mathbf{X}\boldsymbol{\beta}

where:

  • η\boldsymbol{\eta} is the n×(K−1)n \times (K-1) matrix of linear predictors (each row corresponds to one observation, each column corresponds to one non-reference category, and element ηik\eta_{ik} is the linear predictor for observation ii and category kk)

To obtain the predicted probabilities for all KK categories, we apply the softmax function row-wise. For each observation ii and category kk:

P(yi=k∣xi)=exp⁡(ηik)∑j=1Kexp⁡(ηij)P(y_i = k \mid \mathbf{x}_i) = \frac{\exp(\eta_{ik})}{\sum_{j=1}^{K} \exp(\eta_{ij})}

where for the reference category KK, we set ηiK=0\eta_{iK} = 0 (since its coefficients are all zero by convention).

In matrix notation, the full n×Kn \times K probability matrix P\mathbf{P}, with elements Pik=P(yi=k∣xi)P_{ik} = P(y_i = k \mid \mathbf{x}_i), is given by:

P=softmax([η,0])\mathbf{P} = \text{softmax}([\boldsymbol{\eta}, \mathbf{0}])

where:

  • P\mathbf{P} is the n×Kn \times K probability matrix (each row contains the predicted probabilities for one observation across all KK categories)
  • PikP_{ik} is the probability that observation ii belongs to category kk (an element of the probability matrix)
  • [η,0][\boldsymbol{\eta}, \mathbf{0}] is the n×Kn \times K matrix formed by horizontally concatenating η\boldsymbol{\eta} (the n×(K−1)n \times (K-1) matrix of linear predictors for non-reference categories) with 0\mathbf{0} (a column of zeros for the reference category)
  • 0\mathbf{0} is the n×1n \times 1 column vector of zeros for the reference category (representing ηiK=0\eta_{iK} = 0 for all observations)
  • softmax(⋅)\text{softmax}(\cdot) is the softmax function applied row-wise (maps linear predictors into probabilities that are non-negative and sum to 1 for each observation)

This formulation ensures that all predicted probabilities are non-negative and sum to one for each observation.

This matrix-based approach is highly efficient for computation, especially when working with large datasets or when fitting the model using optimization algorithms that require gradients with respect to all parameters.

Calculating the Coefficients

The coefficients in multinomial logistic regression are estimated using maximum likelihood estimation (MLE). This process involves finding the parameter values that maximize the likelihood of observing our data given the model.

Likelihood Function

For a dataset with nn observations and KK classes, the likelihood function is:

L(β)=∏i=1n∏k=1KP(yi=k∣xi)I(yi=k)L(\boldsymbol{\beta}) = \prod_{i=1}^{n} \prod_{k=1}^{K} P(y_i = k | \mathbf{x}_i)^{I(y_i = k)}

where:

  • L(β)L(\boldsymbol{\beta}) is the likelihood function (the probability of observing the entire dataset given the model parameters β\boldsymbol{\beta})
  • β\boldsymbol{\beta} represents all coefficient parameters in the model (the collection of all βkj\beta_{kj} values for all non-reference categories and all predictors)
  • nn is the number of observations (the sample size)
  • KK is the number of categories (the total number of possible outcome classes)
  • P(yi=k∣xi)P(y_i = k | \mathbf{x}_i) is the predicted probability that observation ii belongs to category kk (computed using the softmax function)
  • I(yi=k)I(y_i = k) is the indicator function that equals 1 if observation ii truly belongs to class kk, and 0 otherwise (selects the probability of the observed class)

Log-Likelihood Function

Working with the log-likelihood is computationally more convenient:

ℓ(β)=∑i=1n∑k=1KI(yi=k)log⁡P(yi=k∣xi)\ell(\boldsymbol{\beta}) = \sum_{i=1}^{n} \sum_{k=1}^{K} I(y_i = k) \log P(y_i = k | \mathbf{x}_i)

where:

  • ℓ(β)\ell(\boldsymbol{\beta}) is the log-likelihood function (the natural logarithm of the likelihood function, which maps products into sums for computational convenience and numerical stability)

Substituting the softmax probability formula:

ℓ(β)=∑i=1n∑k=1KI(yi=k)[ηik−log⁡(∑j=1Keηij)]\ell(\boldsymbol{\beta}) = \sum_{i=1}^{n} \sum_{k=1}^{K} I(y_i = k) \left[ \eta_{ik} - \log\left(\sum_{j=1}^{K} e^{\eta_{ij}}\right) \right]

Gradient and Hessian

To find the maximum likelihood estimates, we need the gradient (first derivatives) and Hessian (second derivatives) of the log-likelihood function.

Let's break down how to compute the gradient and Hessian of the multinomial logistic regression log-likelihood step by step.

Step 1: Recall the log-likelihood

The log-likelihood for multinomial logistic regression is:

ℓ(β)=∑i=1n∑k=1KI(yi=k)log⁡P(yi=k∣xi)\ell(\boldsymbol{\beta}) = \sum_{i=1}^{n} \sum_{k=1}^{K} I(y_i = k) \log P(y_i = k | \mathbf{x}_i)

where I(yi=k)I(y_i = k) is 1 if observation ii belongs to class kk, and 0 otherwise.

Step 2: Substitute the softmax probability

Recall that

P(yi=k∣xi)=exp⁡(ηik)∑j=1Kexp⁡(ηij)P(y_i = k | \mathbf{x}_i) = \frac{\exp(\eta_{ik})}{\sum_{j=1}^K \exp(\eta_{ij})}

where:

  • ηik=xi⊤βk\eta_{ik} = \mathbf{x}_i^\top \boldsymbol{\beta}_k is the linear predictor for observation ii and category kk (computed as the dot product of the feature vector and coefficient vector)
  • xi⊤\mathbf{x}_i^\top is the transpose of the feature vector for observation ii (a 1×(p+1)1 \times (p+1) row vector including a 1 for the intercept)
  • βk\boldsymbol{\beta}_k is the coefficient vector for category kk (a (p+1)×1(p+1) \times 1 column vector including the intercept and pp slope coefficients)

Step 3: Compute the gradient (first derivative) with respect to βkj\beta_{kj}

We want to find the derivative of the log-likelihood with respect to a particular coefficient βkj\beta_{kj} (the coefficient for predictor jj in class kk):

  • The log-likelihood for a single observation ii is:

    ∑k=1KI(yi=k)log⁡P(yi=k∣xi)\sum_{k=1}^K I(y_i = k) \log P(y_i = k | \mathbf{x}_i)
  • The derivative with respect to βkj\beta_{kj} is:

    ∂∂βkj[I(yi=k)log⁡P(yi=k∣xi)]\frac{\partial}{\partial \beta_{kj}} \left[ I(y_i = k) \log P(y_i = k | \mathbf{x}_i) \right]
  • Since P(yi=k∣xi)P(y_i = k | \mathbf{x}_i) depends on all βkj\beta_{kj}, but only directly on βkj\beta_{kj} through ηik\eta_{ik}, we use the chain rule.

  • The derivative of log⁡P(yi=k∣xi)\log P(y_i = k | \mathbf{x}_i) with respect to βkj\beta_{kj} is:

    ∂∂βkjlog⁡P(yi=k∣xi)=xij[I(yi=k)−P(yi=k∣xi)]\frac{\partial}{\partial \beta_{kj}} \log P(y_i = k | \mathbf{x}_i) = x_{ij} \left[ I(y_i = k) - P(y_i = k | \mathbf{x}_i) \right]

    (This comes from differentiating the log-softmax.)

  • Summing over all observations, we get:

    ∂ℓ∂βkj=∑i=1nxij[I(yi=k)−P(yi=k∣xi)]\frac{\partial \ell}{\partial \beta_{kj}} = \sum_{i=1}^{n} x_{ij} \left[ I(y_i = k) - P(y_i = k | \mathbf{x}_i) \right]

Step 4: Compute the Hessian (second derivative) with respect to βkj\beta_{kj} and βlm\beta_{lm}

  • The Hessian entry for parameters βkj\beta_{kj} and βlm\beta_{lm} is the second derivative: ∂2ℓ∂βkj∂βlm\frac{\partial^2 \ell}{\partial \beta_{kj} \partial \beta_{lm}}
  • Differentiating the gradient again, we get: −∑i=1nxijximP(yi=k∣xi)[I(k=l)−P(yi=l∣xi)]-\sum_{i=1}^{n} x_{ij} x_{im} P(y_i = k | \mathbf{x}_i) \left[ I(k = l) - P(y_i = l | \mathbf{x}_i) \right] where I(k=l)I(k = l) is 1 if k=lk = l, and 0 otherwise.

Results:

  • Gradient (First Derivatives):

    ∂ℓ∂βkj=∑i=1nxij[I(yi=k)−P(yi=k∣xi)]\frac{\partial \ell}{\partial \beta_{kj}} = \sum_{i=1}^{n} x_{ij} \left[ I(y_i = k) - P(y_i = k | \mathbf{x}_i) \right]

    where:

    • ∂ℓ∂βkj\frac{\partial \ell}{\partial \beta_{kj}} is the partial derivative of the log-likelihood with respect to coefficient βkj\beta_{kj} (the gradient component for this parameter)
    • βkj\beta_{kj} is the coefficient for predictor jj in category kk (the parameter we're taking the derivative with respect to)
    • xijx_{ij} is the value of predictor jj for observation ii (the feature value that multiplies this coefficient)
    • I(yi=k)I(y_i = k) is the indicator function (equals 1 if observation ii truly belongs to category kk, and 0 otherwise)
    • P(yi=k∣xi)P(y_i = k | \mathbf{x}_i) is the predicted probability for observation ii in category kk (computed using the current parameter values)
  • Hessian (Second Derivatives):

    ∂2ℓ∂βkj∂βlm=−∑i=1nxijximP(yi=k∣xi)[I(k=l)−P(yi=l∣xi)]\frac{\partial^2 \ell}{\partial \beta_{kj} \partial \beta_{lm}} = -\sum_{i=1}^{n} x_{ij} x_{im} P(y_i = k | \mathbf{x}_i) \left[ I(k = l) - P(y_i = l | \mathbf{x}_i) \right]

    where:

    • ∂2ℓ∂βkj∂βlm\frac{\partial^2 \ell}{\partial \beta_{kj} \partial \beta_{lm}} is the second partial derivative of the log-likelihood (measures the curvature of the log-likelihood surface with respect to parameters βkj\beta_{kj} and βlm\beta_{lm})
    • βlm\beta_{lm} is the coefficient for predictor mm in category ll (the second parameter in the mixed partial derivative)
    • ximx_{im} is the value of predictor mm for observation ii (the feature value that multiplies coefficient βlm\beta_{lm})
    • I(k=l)I(k = l) is the indicator function (equals 1 if categories kk and ll are the same, and 0 otherwise)

Optimization Methods

The coefficients are found by maximizing the log-likelihood function using numerical optimization methods:

  1. Newton-Raphson Method: Uses both gradient and Hessian information for faster convergence
  2. Fisher Scoring: Uses the expected Fisher information matrix instead of the observed Hessian
  3. Gradient Descent: Iteratively updates parameters in the direction of the gradient
  4. Limited-memory BFGS (L-BFGS): A quasi-Newton method that approximates the Hessian

Iterative Reweighted Least Squares (IRLS)

Multinomial logistic regression can also be solved using IRLS, which reformulates the problem as a series of weighted least squares problems. This approach:

  1. Starts with initial coefficient estimates
  2. Computes fitted probabilities using the current coefficients
  3. Creates working responses and weights
  4. Solves a weighted least squares problem
  5. Updates the coefficients
  6. Repeats until convergence

Convergence Criteria

The optimization process continues until one of the following convergence criteria is met:

  • Parameter convergence: ∣β(t+1)−β(t)∣<ϵ|\boldsymbol{\beta}^{(t+1)} - \boldsymbol{\beta}^{(t)}| < \epsilon
  • Log-likelihood convergence: ∣ℓ(t+1)−ℓ(t)∣<ϵ|\ell^{(t+1)} - \ell^{(t)}| < \epsilon
  • Gradient convergence: ∣∇ℓ(t)∣<ϵ|\nabla \ell^{(t)}| < \epsilon

where:

  • β(t)\boldsymbol{\beta}^{(t)} is the vector of coefficient estimates at iteration tt (the current parameter values during optimization)
  • β(t+1)\boldsymbol{\beta}^{(t+1)} is the vector of coefficient estimates at iteration t+1t+1 (the updated parameter values after one optimization step)
  • ℓ(t)\ell^{(t)} is the log-likelihood value at iteration tt (the objective function value at the current parameters)
  • ℓ(t+1)\ell^{(t+1)} is the log-likelihood value at iteration t+1t+1 (the objective function value at the updated parameters)
  • ∇ℓ(t)\nabla \ell^{(t)} is the gradient vector at iteration tt (the vector of partial derivatives of the log-likelihood with respect to all parameters)
  • ϵ\epsilon is the tolerance threshold (a small positive number, typically 10−610^{-6} or 10−810^{-8}, that determines when convergence is achieved)
  • ∣⋅∣|\cdot| denotes the absolute value (for scalars) or norm (for vectors), measuring the magnitude of change

Identifiability and Constraints

The multinomial logistic regression model is said to be overparameterized because, without any constraints, there are more parameters in the model than are needed to describe the relationship between the predictors and the outcome categories. Specifically, for KK outcome categories, the model estimates a separate set of coefficients for each category, but only K−1K-1 of these sets are necessary to uniquely determine the predicted probabilities. This redundancy means that different sets of coefficients can produce the same predicted probabilities, making the model unidentifiable unless we impose a constraint.

To resolve this, the standard approach is to set the coefficients for one of the categories.called the reference category.to zero:

βK=0\boldsymbol{\beta}_K = \mathbf{0}

where:

  • βK\boldsymbol{\beta}_K is the coefficient vector for the reference category KK (a (p+1)×1(p+1) \times 1 vector set to all zeros to ensure model identifiability)
  • 0\mathbf{0} is the zero vector (a (p+1)×1(p+1) \times 1 vector with all elements equal to zero)

By doing this, we remove the redundancy and ensure that the model is identifiable, meaning the optimization problem has a unique solution and the estimated coefficients are interpretable relative to the reference category.

Mathematical Properties

The multinomial logistic regression model has several important mathematical properties. First, the softmax function ensures that all predicted probabilities are between 0 and 1 and sum to 1, which is necessary for a valid probability model. Second, the model is identifiable only up to the choice of reference category - we can add any constant to all coefficients without changing the predicted probabilities, which is why we typically set the coefficients for the reference category to zero.

The model also exhibits the property of proportional odds in the sense that the ratio of probabilities for any two categories depends only on the difference in their linear predictors. This means that if we change a predictor variable, the relative probabilities of all non-reference categories change proportionally, maintaining their relative relationships.

Out[3]:
Visualization
Line plot showing probability changes for each class relative to reference.
This visualization demonstrates how coefficients in multinomial logistic regression are interpreted relative to a reference category. Each colored line shows how the probability of a class changes as a predictor increases. Class 2 (reference) has zero coefficients, while Classes 0 and 1 have their own coefficient sets. The slopes reflect the magnitude and direction of each class's coefficients.
Bar chart showing coefficient magnitudes for different classes.
The coefficient magnitudes shown here represent the effect of the predictor on the log-odds of each class relative to the reference. Positive coefficients increase the probability of that class as the predictor increases, while negative coefficients decrease it. The reference class (Class 2) is the baseline with coefficients fixed at zero.