TExcelTAD
Home › Classical ML Algorithms: Supervised & Unsupervised › Multiclass Logistic Regression: Softmax

Multiclass Logistic Regression: Softmax

A handwritten digit is one of ten classes, a wine one of three cultivars, a support ticket one of a dozen categories. Logistic regression answers yes or no; softmax regression (multinomial logistic regression) extends it to KK classes with one linear score per class and probabilities that sum to 1. It is what LogisticRegression does by default in scikit-learn 1.7 when there are more than two classes, and it is the last layer of nearly every neural-network classifier.

The model

One weight vector per class, one score per class, and the softmax turns scores into probabilities:

zk=wk⊤x+bk,p(y=k∣x)=softmax⁡(z)k=ezk∑j=1Kezjz_k = \mathbf{w}_k^\top \mathbf{x} + b_k, \qquad p(y = k \mid \mathbf{x}) = \operatorname{softmax}(\mathbf{z})_k = \frac{e^{z_k}}{\sum_{j=1}^{K} e^{z_j}}

The prediction is the class with the largest score. Adding the same number to every score leaves the probabilities unchanged, which gives two practical consequences: you can subtract max⁡kzk\max_k z_k before exponentiating so nothing overflows (A Stable Softmax), and the weights are only determined up to a shared shift (with the L2 penalty, the solution has ∑kwk=0\sum_k \mathbf{w}_k = \mathbf{0}). With K=2K = 2 the softmax reduces to the sigmoid of the score difference z1−z0z_1 - z_0.

Loss and gradient

With one-hot labels Y\mathbf{Y} (Yik=1Y_{ik} = 1 when example ii is in class kk) and predicted probabilities PP, the loss is the cross-entropy, and its gradient is again "error times input":

ℓ(W)=−∑i=1n∑k=1KYiklog⁡Pik,∇Wℓ=X⊤(P−Y)\ell(W) = -\sum_{i=1}^{n} \sum_{k=1}^{K} Y_{ik} \log P_{ik}, \qquad \nabla_W \ell = X^\top (P - Y)

This tidy gradient is derived in Softmax and Cross-Entropy Gradient; Entropy, Cross-Entropy and KL Divergence explains the loss. scikit-learn minimises 12∥W∥F2+C ℓ(W)\frac{1}{2} \lVert W \rVert_F^2 + C \, \ell(W), the same penalty as the binary case.

From scratch

Gradient descent on scikit-learn's objective, for the three wine cultivars (13 standardised features):

python · try it yourself
import numpy as np
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

X, y = load_wine(return_X_y=True)                    # 3 classes
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
sc = StandardScaler().fit(X_tr)
X_tr, X_te = sc.transform(X_tr), sc.transform(X_te)

def softmax(Z):
    Z = Z - Z.max(axis=1, keepdims=True)              # subtract the row max: no overflow, same result
    E = np.exp(Z)
    return E / E.sum(axis=1, keepdims=True)

def fit_softmax(X, y, C=1.0, lr=0.01, steps=3000):
    """Gradient descent on 1/2 ||W||^2 + C * sum cross-entropy (scikit-learn's multinomial objective)."""
    n, d = X.shape
    K = y.max() + 1
    Y = np.eye(K)[y]                                  # one-hot labels, n x K
    W, b = np.zeros((d, K)), np.zeros(K)
    for step in range(steps):
        P = softmax(X @ W + b)
        W -= lr * (W + C * X.T @ (P - Y))             # gradient: W + C X^T (P - Y)
        b -= lr * C * (P - Y).sum(axis=0)
    return W, b

W, b = fit_softmax(X_tr, y_tr)
sk = LogisticRegression(C=1.0, tol=1e-8, max_iter=10000).fit(X_tr, y_tr)  # multinomial (softmax) for 3+ classes
P_ours, P_sk = softmax(X_te @ W + b), sk.predict_proba(X_te)
print("probabilities match sklearn:", np.allclose(P_ours, P_sk, atol=1e-3))
print("first test wine:", P_ours[0].round(3), " true class", y_te[0])
print("weights sum to zero over classes:", np.allclose(W.sum(axis=1), 0, atol=1e-6))
print("test accuracy:", round(np.mean(P_ours.argmax(axis=1) == y_te), 3))
probabilities match sklearn: True
first test wine: [0.999 0.    0.001]  true class 0
weights sum to zero over classes: True
test accuracy: 1.0

The from-scratch probabilities match scikit-learn's to three decimals on every test wine. Because every update to WW has rows summing to zero (each row of P−YP - Y sums to 1−1=01 - 1 = 0) and WW starts at zero, the weights keep ∑kwk=0\sum_k \mathbf{w}_k = \mathbf{0} throughout, exactly the property of the penalised solution. All 54 test wines are classified correctly: wine is an easy data set.

Softmax versus one-vs-rest

The other way to get KK classes from a binary method is one-vs-rest (OvR): train KK separate classifiers, "class kk or not", and predict the most confident. It works with any binary model (SVMs use it, or one-vs-one), but the KK models are trained independently and their scores are not calibrated against each other. Softmax trains one joint model. On the 1797 handwritten digits (8 by 8 pixels, 10 classes), with 5-fold cross-validation:

python · try it yourself
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import cross_val_score, StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.multiclass import OneVsRestClassifier
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import cross_val_predict

X, y = load_digits(return_X_y=True)                  # 1797 images of 8x8 pixels, digits 0-9
cv = StratifiedKFold(5, shuffle=True, random_state=0)
softmax = make_pipeline(StandardScaler(), LogisticRegression(C=0.1, max_iter=2000))
ovr = make_pipeline(StandardScaler(), OneVsRestClassifier(LogisticRegression(C=0.1, max_iter=2000)))
print("softmax (multinomial) CV accuracy:", cross_val_score(softmax, X, y, cv=cv).mean().round(3))
print("one-vs-rest (10 binary) CV accuracy:", cross_val_score(ovr, X, y, cv=cv).mean().round(3))
pred = cross_val_predict(softmax, X, y, cv=cv)
cm = confusion_matrix(y, pred)
np.fill_diagonal(cm, 0)
i, j = np.unravel_index(cm.argmax(), cm.shape)
print(f"most common confusion: true {i} predicted as {j} ({cm[i, j]} times)")
softmax (multinomial) CV accuracy: 0.967
one-vs-rest (10 binary) CV accuracy: 0.958
most common confusion: true 8 predicted as 1 (8 times)

A linear model on raw pixels already gets 96.7 % of digits right, softmax slightly ahead of one-vs-rest. cross_val_predict gives every image a prediction from a model that did not see it, so the confusion matrix is honest; the most frequent mistake reads an 8 as a 1.

Hyperparameters, strengths, weaknesses

The hyperparameters are those of logistic regression (C, penalty, class_weight, solver settings). Softmax regression is fast, convex and gives a proper probability distribution over the classes; its boundaries between classes are linear, and with many classes and features the weight matrix has d×Kd \times K entries to estimate. Use it as the baseline for any multiclass problem, and on high-dimensional sparse data (text) where linear models are hard to beat.

Pitfalls

  • Computing exp(Z) without subtracting the max. Scores of a few hundred overflow to inf, and inf/inf is nan.
  • Encoding classes as numbers 0 to K-1 and running a regression. That imposes an order and spacing on the classes; classification needs one score per class.
  • Reading one class's weights alone. Only differences between classes' weights matter.

Practice

  1. Scores z=(2,1,0)\mathbf{z} = (2, 1, 0). Compute the softmax probabilities, then for z+100\mathbf{z} + 100.
Answer

e2,e1,e0=7.389,2.718,1e^2, e^1, e^0 = 7.389, 2.718, 1, sum 11.107, so p=(0.665,0.245,0.090)p = (0.665, 0.245, 0.090). Adding 100 to every score multiplies every numerator and the denominator by e100e^{100}, so the probabilities are identical (and computing them after subtracting the max avoids the overflow).

  1. Why can one-vs-rest predict a class that none of its KK binary models is confident about?
Answer

OvR picks the largest of KK independent scores. If every binary model says "probably not my class" (all probabilities below 0.5), the largest is still chosen, and the scores were never trained to be compared with each other.

Test yourself

What does softmax guarantee about its outputs?

  1. They are 0 or 1
  2. They are positive and sum to 1
  3. They are sorted
  4. They are independent of each other

What is the gradient of the cross-entropy loss with respect to the weight matrix WW?

  1. X⊤YX^\top Y
  2. X⊤(P−Y)X^\top (P - Y)
  3. P−YP - Y
  4. X(P−Y)X (P - Y)

Why subtract the row maximum from the scores before np.exp?

  1. It changes the probabilities to be more accurate
  2. It prevents overflow without changing the result
  3. It makes the model regularised
  4. It is required for the gradient