Sub topic 14
Extending SVMs to more than two classes
This chapter assumes you know the binary soft-margin SVM, the role of C, and the kernel trick. It also assumes you can fit SVC in scikit-learn and run cross-validation. It covers how a method built for two classes handles K classes, what scikit-learn does by default, and where the common mistakes are.
Why the binary SVM needs an extension
A binary SVM learns one function, f(x) = w·x + b, and predicts by its sign. The sign gives two outcomes, so it cannot directly name one of K classes.
The standard fix is to train several binary SVMs and combine their outputs. Two decompositions are common: one-vs-rest and one-vs-one. A third approach, a single joint optimization over all classes, exists but is rarely used.
One-vs-rest (OvR)
OvR trains K classifiers. Classifier k treats class k as positive and all other classes as negative. At prediction time, you compute all K scores f_k(x) and choose the class with the highest score.
- Each classifier sees the full training set, so each trains on N samples.
- The negative class is a mix of many classes, so the positive class is often the minority. Imbalance is a real concern.
- The scores come from separately trained models. Their scales are not guaranteed to be comparable, so the argmax can be unreliable.
- Some points get no "positive" vote from any classifier. Without the argmax step, the decision regions would have gaps.
One-vs-one (OvO)
OvO trains one classifier for every pair of classes, K(K-1)/2 in total. Each classifier sees only the samples from its two classes. At prediction time, every classifier votes for one of its two classes, and the class with the most votes wins.
- Each classifier trains on about 2N/K samples. The pairs are small and usually balanced.
- The number of classifiers grows quadratically with K.
- Ties are possible. Libraries break them in a fixed way, such as picking the lowest class index.
- Voting uses only the sign of each pairwise output. The margin size is discarded.
Comparing the two
| Property | One-vs-rest | One-vs-one |
|---|---|---|
| Classifiers for K classes | K | K(K-1)/2 |
| Samples per classifier | N | about 2N/K |
| Class balance per classifier | Often skewed | Usually balanced |
| Combination rule | Highest score | Majority vote |
| K = 10 | 10 models | 45 models |
OvO sounds more expensive because it has more models. With kernel SVMs it is often cheaper. Training cost grows faster than linearly in the number of samples, so many small problems can cost less than a few large ones. That is why OvO is the usual choice for kernel SVMs.
What scikit-learn does
SVC is built on libsvm, which always trains one-vs-one internally. This surprises people because of the parameter decision_function_shape. It only changes the shape of the scores that decision_function returns. It does not change training.
from sklearn.datasets import load_digits
from sklearn.svm import SVC
X, y = load_digits(return_X_y=True)
for shape in ("ovo", "ovr"):
clf = SVC(kernel="rbf", decision_function_shape=shape).fit(X, y)
print(shape, clf.decision_function(X[:1]).shape)With 10 digit classes, this prints (1, 45) for ovo and (1, 10) for ovr. The ovr option aggregates the pairwise results into one score per class. Those aggregated scores are not the output of true one-vs-rest models.
LinearSVC differs. It is built on liblinear and uses one-vs-rest by default. Its multi_class="crammer_singer" option solves one joint problem over all classes. That option is rarely better in practice and is slower.
Forcing a strategy with wrappers
To get a specific strategy, wrap a binary estimator. OneVsRestClassifier and OneVsOneClassifier both accept any binary classifier, and they work with pipelines.
from sklearn.datasets import load_digits
from sklearn.model_selection import cross_val_score
from sklearn.multiclass import OneVsOneClassifier, OneVsRestClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = load_digits(return_X_y=True)
base = make_pipeline(StandardScaler(), SVC(kernel="rbf", C=1.0))
models = {
"SVC built-in (one-vs-one)": base,
"explicit one-vs-rest": OneVsRestClassifier(base),
"explicit one-vs-one": OneVsOneClassifier(base),
}
for name, model in models.items():
scores = cross_val_score(model, X, y, cv=5)
print(f"{name}: {scores.mean():.3f}")Expect the built-in model and the explicit one-vs-one wrapper to score almost the same. They use the same decomposition. The one-vs-rest result usually differs a little. The gap tends to be small when the classes are well separated and larger when many classes overlap.
Tuning in the multiclass setting
Several details change when K is greater than 2.
- One C and gamma for all subproblems. A single value is shared by every pairwise or one-vs-rest classifier. Some pairs may need a different value. If one pair of classes is much harder than the rest, a global setting is a compromise.
- Scale inside the pipeline. The scaler should be fitted on training folds only. Place it in the pipeline, as in the code above, and let the wrapper clone the whole pipeline.
- Use a suitable metric. Accuracy hides weak classes. Report macro-averaged F1 or a per-class report when classes are imbalanced.
- Class weights.
class_weight="balanced"rescales C per class. It helps in one-vs-rest settings where the positive class is small.
Probabilities and scores
The binary SVM outputs a margin, not a probability. For multiclass, SVC(probability=True) fits Platt scaling on each pairwise problem using an internal cross-validation. It then combines the pairwise probabilities into class probabilities. This costs extra training time. The result can also disagree with predict, because the probabilities and the votes are computed separately. The next chapters on decision scores treat this in more detail.
Failure modes
- Many classes. With K = 1000, OvO needs about 500,000 models. Use one-vs-rest, a linear model, or a different method.
- Ties in voting. With few classes and similar votes, the tie-break rule decides the label. This is deterministic but not meaningful.
- Incomparable OvR scores. If one classifier has large-magnitude scores, it dominates the argmax. Calibrate the scores or compare against OvO.
- Rare classes. A class with very few samples produces weak pairwise classifiers. Pooling or resampling may help.
Exercise
A dataset has 6 classes and 12,000 samples, evenly split. You train an SVC with an RBF kernel. How many binary classifiers does it fit internally, and about how many samples does each see? Does setting decision_function_shape="ovr" change either answer?
Show answer
One-vs-one gives 6 x 5 / 2 = 15 classifiers. Each sees two classes of 2,000 samples, so about 4,000 samples. Setting decision_function_shape="ovr" changes neither answer. It only changes the shape of the output of decision_function, from (n, 15) to (n, 6). Training stays one-vs-one.
Exercise
You want a true one-vs-rest SVM with an RBF kernel and scaling, evaluated with 5-fold cross-validation. How do you build it so the scaler is fitted only on training folds?
Show answer
Put the scaler and SVC in a pipeline, wrap the pipeline in OneVsRestClassifier, and pass the wrapper to cross_val_score(model, X, y, cv=5). Each fold then clones and fits the full pipeline on its training part only.