Many problems have more than two answers. A wine can come from one of three grapes, and a support ticket can be about billing, a technical fault, an account or security. This is multiclass classification. This lesson shows how scikit-learn handles it and how to read the results when classes are unequal in size.
In this lesson you will learn
- Training and reading a multiclass model and its confusion matrix
- What one-vs-rest and one-vs-one mean
- The difference between micro, macro and weighted averages
- Why macro F1 exposes rare classes that accuracy hides
You should know logistic regression and precision, recall and F1.
A Three-Class Model
Most scikit-learn classifiers accept more than two classes with no extra code. The wine dataset has 178 wines, 13 chemical measurements and three grape types.
from sklearn.datasets import load_wine
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_wine(return_X_y=True) # 178 wines, 3 grape types
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, stratify=y, random_state=1)
model = make_pipeline(StandardScaler(), LogisticRegression(C=0.05))
model.fit(X_tr, y_tr)
pred = model.predict(X_te)
print("Classes:", model.classes_)
print(confusion_matrix(y_te, pred))
print(classification_report(y_te, pred, digits=3))
print("Probabilities for first 3 test wines:")
print(model.predict_proba(X_te[:3]).round(3))
Output
Classes: [0 1 2]
[[18 0 0]
[ 1 20 0]
[ 0 0 15]]
precision recall f1-score support
0 0.947 1.000 0.973 18
1 1.000 0.952 0.976 21
2 1.000 1.000 1.000 15
accuracy 0.981 54
macro avg 0.982 0.984 0.983 54
weighted avg 0.982 0.981 0.982 54
Probabilities for first 3 test wines:
[[0.044 0.214 0.742]
[0.056 0.159 0.785]
[0.066 0.032 0.901]]
- The confusion matrix is now 3×3. Rows are the true class and columns are the predicted class. The diagonal holds correct answers. One wine of class 1 was predicted as class 0.
classification_reportgives precision, recall and F1 for each class. Each class is treated as “positive” in turn, with all other classes as “negative”.predict_probareturns one probability per class, and each row adds up to 1. The prediction is the class with the highest probability.stratify=ykeeps the share of each class the same in the training and test sets.
One-vs-Rest and One-vs-One
Some algorithms, such as support vector machines, are built for exactly two classes. There are two standard ways to extend them:
| Strategy | How it works | Models for k classes |
|---|---|---|
| One-vs-Rest (OvR) | One model per class: “this class or anything else?” The most confident model wins. | k |
| One-vs-One (OvO) | One model per pair of classes. Each model votes, and the class with most votes wins. | k × (k − 1) / 2 |
LogisticRegression, trees, forests and k-NN handle many classes natively. SVC uses one-vs-one inside. You can choose a strategy yourself with the wrappers in sklearn.multiclass.
Averaging Scores Across Classes
The next example has four ticket types with very different sizes: 60% billing, 25% technical, 10% account and 5% security.
from sklearn.datasets import make_classification
from sklearn.metrics import f1_score
from sklearn.model_selection import train_test_split
from sklearn.multiclass import OneVsOneClassifier, OneVsRestClassifier
from sklearn.svm import LinearSVC
# Support tickets: 60% billing, 25% technical, 10% account, 5% security
X, y = make_classification(n_samples=2000, n_features=10, n_informative=6,
n_classes=4, weights=[0.60, 0.25, 0.10, 0.05],
class_sep=1.5, random_state=4)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, stratify=y, random_state=0)
for name, wrapper in [("One-vs-Rest", OneVsRestClassifier),
("One-vs-One", OneVsOneClassifier)]:
clf = wrapper(LinearSVC()).fit(X_tr, y_tr)
pred = clf.predict(X_te)
print(f"{name}: {len(clf.estimators_)} binary models")
print(" F1 per class:", f1_score(y_te, pred, average=None).round(3))
for avg in ["micro", "macro", "weighted"]:
print(f" {avg:8} F1: {f1_score(y_te, pred, average=avg):.3f}")
Output
One-vs-Rest: 4 binary models
F1 per class: [0.867 0.675 0.068 0.207]
micro F1: 0.752
macro F1: 0.454
weighted F1: 0.704
One-vs-One: 6 binary models
F1 per class: [0.888 0.686 0.488 0.474]
micro F1: 0.790
macro F1: 0.634
weighted F1: 0.776
With 4 classes, one-vs-rest trains 4 models and one-vs-one trains 4 × 3 / 2 = 6. Now look at the three averages:
- Micro pools every prediction before scoring. When each row has exactly one label, micro F1 equals accuracy. It is dominated by the big billing class.
- Macro is the plain mean of the per-class F1 scores. Every class counts equally, so the weak account and security classes drag it down.
- Weighted averages per-class F1 by the number of rows in each class. It sits between the other two.
For one-vs-rest, accuracy (micro F1) is 0.752, which sounds reasonable. But the per-class scores show the model almost never gets account tickets right (F1 0.068). Macro F1 of 0.454 makes that failure visible. On this data, one-vs-one does better on the rare classes. One likely reason is that each pairwise model only has to separate two classes, so a rare class is not swamped by all the others at once.
If every class matters to you, and rare ones like security usually do, report macro F1 alongside accuracy.
Common Mistakes
- Reporting only accuracy on unequal classes. Look at per-class scores and macro F1.
- Calling
f1_scorewithoutaverageon multiclass labels. It raises an error, because the binary default does not apply. - Splitting without
stratify=y, so a rare class may be almost missing from the test set. - Wrapping a model that is already multiclass in
OneVsRestClassifierwithout a reason. It adds training time and can change the probabilities.
Practice Exercises
Exercise 1. A problem has 10 classes. How many binary models do one-vs-rest and one-vs-one train?
Show answer
One-vs-rest trains 10. One-vs-one trains 10 × 9 / 2 = 45.
Exercise 2. Print the recall for each class of the wine model only, as a list.
Show answer
from sklearn.metrics import recall_score
print(recall_score(y_te, pred, average=None).round(3))
# [1. 0.952 1. ]
Frequently Asked Questions
What is the difference between multiclass and multilabel?
In multiclass problems each row has exactly one class. In multilabel problems a row can have several labels at once, such as a news story tagged both “sport” and “business”. scikit-learn handles multilabel with a 0/1 matrix as the target.
Can I use ROC AUC for more than two classes?
Yes. roc_auc_score(y, proba, multi_class="ovr") computes one AUC per class against the rest and averages them. You must pass the full probability matrix, not the predicted labels.
How do I deal with a very rare class?
Use stratified splits, look at macro F1, and try class_weight="balanced". The imbalanced data lesson covers more options.
Summary
- Most scikit-learn classifiers support many classes directly.
- The confusion matrix becomes k × k; read the rows as true classes.
- One-vs-rest trains k models; one-vs-one trains k(k − 1)/2.
- Micro F1 follows the big classes; macro F1 treats every class equally.
Next: Gradient Descent in Python.
