Sub topic 18
Beyond two classes: one-vs-rest and softmax
This chapter assumes you know binary logistic regression: the sigmoid, log loss, and its gradient Xᵀ(p − y)/n. It also assumes basic NumPy and scikit-learn. Here you will extend the model to K classes in two ways and learn when to prefer each.
Why the binary model needs extending
A binary model produces one probability, P(y = 1 | x). With K classes you need K probabilities that are non-negative and sum to 1. There are two standard routes:
- Train several binary models and combine them (one-vs-rest).
- Change the model and the loss so that all classes are fitted together (softmax, also called multinomial logistic regression).
One-vs-rest
One-vs-rest (OvR, also called one-vs-all) trains K independent binary classifiers. Classifier k treats class k as positive and every other class as negative. At prediction time, each classifier returns a score, and you pick the class with the highest score.
Properties worth knowing:
- Each classifier is an ordinary binary logistic regression, so everything from earlier chapters applies unchanged.
- The K probabilities do not sum to 1, because each model was fitted without knowledge of the others. Libraries typically rescale them to sum to 1, but the result is a heuristic, not a fitted joint distribution.
- Each binary problem is imbalanced. With 10 balanced classes, each classifier sees 10% positives and 90% negatives.
- The models can be trained in parallel, and each one can have its own regularization strength.
Softmax regression
Softmax regression gives each class its own weight vector w_k and bias b_k. The score for class k is z_k = w_k · x + b_k. The softmax function converts the K scores into probabilities:
P(y = k | x) = exp(z_k) / Σ_j exp(z_j)
Every output is positive and the outputs sum to 1. For K = 2, softmax reduces to the sigmoid applied to the difference z_1 − z_0. Binary logistic regression is therefore the two-class special case.
The loss: categorical cross-entropy
Encode each label as a one-hot vector: a row of K entries with a 1 in the true class and 0 elsewhere. Call the one-hot matrix Y (n × K) and the predicted probabilities P (n × K). The loss is the mean negative log probability of the true class:
L = −(1/n) Σ_i Σ_k Y_ik · log P_ik
For K = 2 this is exactly binary log loss.
The gradient
The gradient has the same form you met in the binary case. With W of shape (d × K):
- Gradient for the weights:
Xᵀ(P − Y) / n - Gradient for the biases: the column means of
P − Y
The binary gradient Xᵀ(p − y)/n is the K = 2 version of this result.
NumPy implementation
import numpy as np
from sklearn.datasets import load_iris
def softmax(Z):
Z = Z - Z.max(axis=1, keepdims=True) # stability: avoids overflow in exp
E = np.exp(Z)
return E / E.sum(axis=1, keepdims=True)
def fit_softmax(X, y, k, lr=0.1, steps=2000):
n, d = X.shape
W = np.zeros((d, k))
b = np.zeros(k)
Y = np.eye(k)[y] # one-hot labels
for _ in range(steps):
P = softmax(X @ W + b)
G = P - Y
W -= lr * (X.T @ G) / n
b -= lr * G.mean(axis=0)
return W, b
X, y = load_iris(return_X_y=True)
X = (X - X.mean(axis=0)) / X.std(axis=0) # scale features first
W, b = fit_softmax(X, y, k=3)
P = softmax(X @ W + b)
print("accuracy:", (P.argmax(axis=1) == y).mean())
print("row sums:", P.sum(axis=1)[:3])The accuracy should be well above 0.9 on this training set, and the row sums print as 1.0.
Comparing the two approaches in scikit-learn
LogisticRegression uses the multinomial (softmax) formulation by default with the lbfgs solver. To get OvR, wrap the model in OneVsRestClassifier.
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.multiclass import OneVsRestClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import classification_report, log_loss
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, stratify=y, random_state=0
)
softmax_model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
ovr_model = make_pipeline(
StandardScaler(), OneVsRestClassifier(LogisticRegression(max_iter=1000))
)
for name, m in [("softmax", softmax_model), ("one-vs-rest", ovr_model)]:
m.fit(X_train, y_train)
proba = m.predict_proba(X_test)
print(name, "log loss:", round(log_loss(y_test, proba), 4))
print(classification_report(y_test, softmax_model.predict(X_test)))Both models usually reach similar accuracy on easy data like iris. The log loss often differs more, because softmax optimizes the joint probabilities directly.
Decision criteria
| Question | One-vs-rest | Softmax |
|---|---|---|
| Probabilities sum to 1 by construction | No (rescaled afterward) | Yes |
| Number of models | K | 1 (K weight vectors) |
| Training objective | K separate binary losses | One joint cross-entropy |
| Per-class tuning (C, class weights) | Easy | Shared settings |
| Handles classes that are not mutually exclusive | Yes, if you skip the rescaling | No |
Prefer softmax when classes are mutually exclusive and you care about calibrated probabilities. Prefer OvR when you want independent per-class models, or when the problem is multilabel, where one example can belong to several classes at once. In the multilabel case, use the K independent sigmoid outputs as they are.
Gotchas and failure modes
- Redundant parameters. Adding the same vector to every
w_kleaves the softmax output unchanged. The unregularized solution is therefore not unique, and the weights can drift during training. L2 regularization (scikit-learn's default) removes the ambiguity. Because of this, individual coefficients are only meaningful relative to other classes. - Reading coefficients. In softmax,
exp(w_k,j − w_m,j)is the odds ratio of class k versus class m for a one-unit increase in feature j. In OvR,exp(w_k,j)is the odds ratio of class k versus all others combined, which depends on the class mix. - Linear boundaries only. Softmax produces linear boundaries between each pair of classes. If a class sits in the middle of the feature space, no linear model separates it. Add interaction or polynomial features, or move to a nonlinear model.
- Metrics. Report per-class precision and recall, and use macro averaging (an unweighted mean over classes) when small classes matter. Accuracy hides weak performance on rare classes. Thresholds also become less direct: you choose the argmax, or you apply per-class cutoffs and decide what to do when none, or several, are exceeded.
- Solvers. lbfgs, newton-cg, and saga support multinomial loss. liblinear supports only OvR. Scale features for all of them, as in the binary case.
Exercise
A three-class softmax model produces scores z = (2.0, 1.0, 0.0) for one example. Compute the predicted probabilities, and say what happens to them if you add 10 to every score.
Show answer
The exponentials are e^2 ≈ 7.389, e^1 ≈ 2.718, and e^0 = 1, which sum to about 11.107. The probabilities are about (0.665, 0.245, 0.090). Adding 10 to every score multiplies each exponential, and the sum, by e^10, so the ratios are unchanged and the probabilities stay the same. This shift invariance is why implementations subtract the maximum score for numerical stability. It is also why the weights are not unique without regularization.
Exercise
You have 4 mutually exclusive classes and you train OvR. For one example, the four binary models output 0.7, 0.5, 0.4, and 0.4. Do these values form a valid probability distribution, and which class is predicted?
Show answer
They sum to 2.0, so they are not a valid distribution. They must be rescaled, for example by dividing each by 2.0 to give 0.35, 0.25, 0.20, and 0.20. The prediction is the first class, which has the highest score. Rescaling does not change the argmax.