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 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:
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 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 ). With the softmax reduces to the sigmoid of the score difference .
Loss and gradient
With one-hot labels ( when example is in class ) and predicted probabilities , the loss is the cross-entropy, and its gradient is again "error times input":
This tidy gradient is derived in Softmax and Cross-Entropy Gradient; Entropy, Cross-Entropy and KL Divergence explains the loss. scikit-learn minimises , the same penalty as the binary case.
From scratch
Gradient descent on scikit-learn's objective, for the three wine cultivars (13 standardised features):
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 has rows summing to zero (each row of sums to ) and starts at zero, the weights keep 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 classes from a binary method is one-vs-rest (OvR): train separate classifiers, "class or not", and predict the most confident. It works with any binary model (SVMs use it, or one-vs-one), but the 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:
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 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 toinf, andinf/infisnan. - 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
- Scores . Compute the softmax probabilities, then for .
Answer
, sum 11.107, so . Adding 100 to every score multiplies every numerator and the denominator by , so the probabilities are identical (and computing them after subtracting the max avoids the overflow).
- Why can one-vs-rest predict a class that none of its binary models is confident about?
Answer
OvR picks the largest of 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?
- They are 0 or 1
- They are positive and sum to 1
- They are sorted
- They are independent of each other
What is the gradient of the cross-entropy loss with respect to the weight matrix ?
Why subtract the row maximum from the scores before np.exp?
- It changes the probabilities to be more accurate
- It prevents overflow without changing the result
- It makes the model regularised
- It is required for the gradient