Sub topic 7
One-vs-rest and one-vs-one strategies
This chapter assumes you can train a binary classifier such as logistic regression. It also assumes you know what a decision score is and can read a confusion matrix. Here you will see two ways to turn binary classifiers into a multiclass model: one-vs-rest (OvR) and one-vs-one (OvO). Both reduce one K-class problem to several binary problems and combine the answers.
Why decompose at all
Some learners are natively binary. Support vector machines and gradient-boosted margin models are examples. Others handle many classes directly, like softmax regression or random forests. When the base learner is binary only, you need a rule for combining several binary models into one prediction.
Decomposition can also help when a native multiclass model exists. It lets you tune each binary problem separately and reuse a well-understood binary pipeline. The cost is extra models and a combination rule that can fail in specific ways.
One-vs-rest
OvR trains one binary classifier per class. For class k, every sample of class k is relabeled 1 and every other sample is relabeled 0. With K classes you get K models, and each one sees the whole training set.
At prediction time every model scores the sample. The predicted class is the one with the highest score:
- Train K models, where model
kanswers "is it class k, or anything else?". - Score the new sample with all K models.
- Return the class whose model gave the largest score.
The next example builds this by hand and compares it with scikit-learn's wrapper.
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.multiclass import OneVsRestClassifier
X, y = load_digits(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, stratify=y, random_state=0
)
classes = np.unique(y_train)
# Manual OvR: relabel the target for each class, then take the argmax of the scores.
scores = np.column_stack([
LogisticRegression(max_iter=2000)
.fit(X_train, (y_train == k).astype(int))
.decision_function(X_test)
for k in classes
])
manual_pred = classes[scores.argmax(axis=1)]
ovr = OneVsRestClassifier(LogisticRegression(max_iter=2000)).fit(X_train, y_train)
print("models:", len(ovr.estimators_))
print("matches wrapper:", (manual_pred == ovr.predict(X_test)).all())
print("manual accuracy:", round((manual_pred == y_test).mean(), 3))The digits dataset has 10 classes, so this trains 10 models. The comparison should print True.
Strengths and weaknesses of OvR
- Few models. K models stay manageable even with hundreds of classes.
- Readable. Each model has a plain meaning: "this class against everything else".
- Lopsided binary problems. With K classes of equal size, each binary problem has a 1-to-(K-1) class ratio. A model can reach high accuracy by always answering "rest".
- Scores that are not comparable. Each model is trained and scaled on its own problem. The argmax compares numbers that were never calibrated against each other, so a model with a wider score range can win unfairly.
- Ambiguous regions. Several models can claim a sample, or none can. Taking the argmax always yields an answer, but the answer may rest on weak evidence.
One-vs-one
OvO trains one binary classifier for every pair of classes. For K classes that is K(K-1)/2 models. Each model sees only the samples that belong to its two classes and ignores the rest.
At prediction time each pairwise model votes for one of its two classes. The class with the most votes wins. If classes tie, scikit-learn breaks the tie using the summed confidences of the pairwise models.
from sklearn.multiclass import OneVsOneClassifier
ovo = OneVsOneClassifier(LogisticRegression(max_iter=2000)).fit(X_train, y_train)
print("OvR models:", len(ovr.estimators_)) # K = 10
print("OvO models:", len(ovo.estimators_)) # K(K-1)/2 = 45
print("OvR accuracy:", round(ovr.score(X_test, y_test), 3))
print("OvO accuracy:", round(ovo.score(X_test, y_test), 3))
print("OvO score shape:", ovo.decision_function(X_test[:2]).shape)The score shape is (2, 10). The values combine vote counts with a small confidence term that breaks ties. They are not probabilities.
Strengths and weaknesses of OvO
- Balanced, easier subproblems. Each pair involves only two classes, so the problem is often closer to balanced and easier to separate.
- Cheaper for slow learners. Each model trains on about 2N/K samples. If training cost grows faster than linearly in N, as with kernel SVMs, many small fits cost less than a few large ones.
- Many models. The model count grows with the square of K. At 100 classes you have 4,950 models, and each prediction must query all of them.
- Irrelevant voters. The A-vs-B model never saw class C. When the true class is C, its vote is meaningless, yet it still counts.
- No probabilities.
OneVsOneClassifierhas nopredict_proba.OneVsRestClassifierdoes, and for single-label targets it normalizes the K outputs so they sum to 1.
Cost comparison
OvR trains K models on N samples each, so the total number of rows processed is about K·N. OvO trains K(K-1)/2 models on about 2N/K rows each, which totals about (K-1)·N. The row counts are nearly equal. The difference appears when the learner's cost is superlinear in the row count, and OvO wins there.
| Property | One-vs-rest | One-vs-one |
|---|---|---|
| Models for K classes | K | K(K-1)/2 |
| Rows per model | All N | About 2N/K |
| Combination rule | Argmax of scores | Majority vote |
| Class imbalance per model | Severe (1 vs K-1) | Mild |
| `predict_proba` in scikit-learn | Yes, if the base model has it | No |
| Prediction cost | K model calls | K(K-1)/2 model calls |
Choosing between them
Start with the native multiclass model if your learner has one. Reach for a wrapper when the base learner is binary only, or when you have a specific reason to prefer a decomposition.
- Use OvR when K is large, when you need probability-like outputs, or when you want to inspect one model per class.
- Use OvO when the base learner scales badly with the number of rows, as kernel SVMs do, and K is small enough for the pair count to stay manageable.
- Check per-class results in a confusion matrix, not only overall accuracy. A decomposition can hide a weak class behind a good average.
Common errors
- Comparing raw scores from uncalibrated models. In OvR, a model trained on a rare class may produce systematically lower scores. Consider calibration or class weights.
- Reading OvO scores as probabilities. They are vote counts plus a tie-breaking term.
- Wrapping an estimator that is already multiclass and expecting the same results. The wrapped model and the native model solve different optimization problems.
- Forgetting that the number of OvO models grows with the square of K. Check
len(model.estimators_)before launching a long fit.
Exercise
A dataset has 20 balanced classes and 50,000 training rows, so each class has 2,500 rows. How many binary models does OvR train, and how many rows does each see? Answer the same for OvO. Which method gives the more balanced binary problems?
Show answer
OvR trains 20 models, and each sees all 50,000 rows, with 2,500 positives and 47,500 negatives. OvO trains 20 × 19 / 2 = 190 models, and each sees 2 × 2,500 = 5,000 rows, split evenly between the two classes. OvO gives the more balanced binary problems. Its total of 190 × 5,000 = 950,000 rows is close to OvR's 20 × 50,000 = 1,000,000.
Exercise
You use OneVsOneClassifier and need a probability for each class for downstream ranking. What are two ways to get class scores or probabilities?
Show answer
Either switch to OneVsRestClassifier, which provides predictproba when the base model does, or keep OvO and use decisionfunction, treating its output only as a ranking score. A third option is to switch to a native multiclass model such as softmax regression, then calibrate its probabilities if needed.