Sub topic 12
ROC AUC for more than two classes
This chapter assumes you can build a binary ROC curve and read its AUC, and that you know what predict_proba returns for a scikit-learn classifier. A ROC curve needs one score per example and one positive class. A multiclass model produces one score per class. The usual fix is to turn the problem into several binary ones and combine the results.
Why there is no single multiclass ROC curve
Binary ROC analysis sweeps one threshold over one score. With three classes, the model outputs three probabilities per example. There is no single threshold to sweep, and "true positive rate" needs a definition of which class counts as positive.
Two decompositions are common:
- One-vs-rest (OvR): for each class, treat that class as positive and all other classes as negative. This gives one binary problem per class.
- One-vs-one (OvO): for each pair of classes, keep only the examples from those two classes and treat one of them as positive. This gives one binary problem per pair (and per direction, as described below).
After the decomposition, each sub-problem is an ordinary binary ROC problem. You compute an AUC for each and then average them.
One-vs-rest in scikit-learn
The call is the same roc_auc_score you used for binary problems. You pass the full probability matrix and set multi_class.
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score
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, random_state=0, stratify=y
)
model = LogisticRegression(max_iter=1000).fit(X_train, y_train)
proba = model.predict_proba(X_test)
print(roc_auc_score(y_test, proba, multi_class="ovr"))The result is close to 1.0, because iris classes are easy to separate. Three requirements apply to this call:
y_trueis a 1-D array of class labels, not a one-hot matrix.y_scorehas shape(n_samples, n_classes), and each row must sum to 1 (within a small tolerance). Raw decision-function scores are rejected for multiclass input.- The columns of
y_scoremust follow the sorted order of the labels. A fitted scikit-learn classifier'spredict_probaalready does this, andmodel.classes_shows the order.
Doing it by hand
To see what multi_class="ovr" computes, build the binary problems yourself. label_binarize turns the label vector into one 0/1 column per class.
import numpy as np
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score
from sklearn.preprocessing import label_binarize
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, random_state=0, stratify=y
)
model = LogisticRegression(max_iter=1000).fit(X_train, y_train)
proba = model.predict_proba(X_test)
classes = model.classes_
Y = label_binarize(y_test, classes=classes)
per_class = [roc_auc_score(Y[:, k], proba[:, k]) for k in range(len(classes))]
for c, a in zip(classes, per_class):
print(f"class {c}: AUC = {a:.3f}")
print("macro mean:", np.mean(per_class))
print("sklearn :", roc_auc_score(y_test, proba, multi_class="ovr"))The last two lines print the same number. Each per-class AUC answers a narrow question: how well does the score for class k separate examples of class k from everything else? A per-class AUC is more useful than the average when you need to know which class the model handles badly.
You can also draw one ROC curve per class. Call roc_curve(Y[:, k], proba[:, k]) for each k and plot the curves on one axis. Each curve reads like a binary ROC curve, but its "negative" group mixes all other classes.
Averaging: macro and weighted
The average argument controls how the per-class values combine.
| `average` | What it does | When it fits |
|---|---|---|
| `"macro"` (default) | Unweighted mean of the per-class AUCs. | Every class matters equally, including rare ones. |
| `"weighted"` | Mean weighted by class prevalence in `y_true`. | You care about typical-example performance. |
Macro averaging lets a rare class pull the result down as much as a common one. Weighted averaging hides weak performance on a small class. Report per-class AUCs alongside either average when classes are unbalanced.
scikit-learn also accepts average="micro" for binary or multilabel inputs. It does not accept it for multiclass y_true, so the two options above are the ones you will use here.
One-vs-one
OvO compares classes in pairs, so the other classes never act as a mixed-in negative group.
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score
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, random_state=0, stratify=y
)
model = LogisticRegression(max_iter=1000).fit(X_train, y_train)
proba = model.predict_proba(X_test)
print(roc_auc_score(y_test, proba, multi_class="ovo"))
print(roc_auc_score(y_test, proba, multi_class="ovo", average="weighted"))For a pair of classes (i, j), scikit-learn computes the AUC using class i as positive with score column i, then again using class j as positive with score column j, and averages those two values. It does this for every pair. Three classes give three pairs, and ten classes give 45.
The two decompositions answer different questions and often give similar numbers, but not identical ones.
| Row | One-vs-rest | One-vs-one |
|---|---|---|
| Number of binary problems | `K` | `K(K-1)/2` pairs |
| Negative group | All other classes mixed | One other class |
| Sensitive to class prevalence | Yes. The negative group's mix changes with prevalence. | No. Each pair uses only its own two classes. |
| Typical use | Per-class diagnosis, per-class curves | A summary that does not depend on class mix |
OvR is the usual first choice because it gives one curve per class and the per-class values are easy to explain. OvO has a practical advantage when class proportions may shift between your test set and deployment, since a pairwise AUC does not depend on how many examples of other classes are present. In scikit-learn, average="weighted" with multi_class="ovo" is not invariant to class prevalence, because the weights are prevalence-based.
Common errors
- Passing hard predictions.
roc_auc_score(y_test, model.predict(X_test), multi_class="ovr")fails or gives meaningless results. Usepredict_proba. - A class missing from
y_true. If a test fold lacks one class, there is no positive example for that class and the AUC is undefined. scikit-learn raises an error. Use stratified splits, and for tiny classes use cross-validation folds that keep every class. - Probabilities that do not sum to 1. Some models, or a subset of probability columns, break this. Renormalize the rows, or compute per-class binary AUCs by hand, where row sums do not matter.
- Column order mismatch. If you build the probability matrix yourself, order the columns by sorted class label. When labels are strings, pass
labels=model.classes_toroc_auc_scoreto make the order explicit. - Treating the average as a decision tool. A single AUC says nothing about which threshold to use per class. Choosing operating points still happens per class, using the binary methods from the earlier chapters.
Limits of the multiclass summary
The averaged AUC inherits every limitation of the binary one. It ignores calibration, so a model with well-ranked but badly scaled probabilities scores the same as a calibrated one. It treats all threshold regions as equally important. Per-class OvR AUCs also suffer from the imbalance problem covered in the precision-recall chapter: a rare class has a large mixed negative group, and a high AUC can still mean many false alarms per true detection. For rare classes, compute a per-class precision-recall curve the same way, with Y[:, k] and proba[:, k].
Exercise
A three-class model is evaluated on a test set with 900 examples of class 0, 90 of class 1, and 10 of class 2. Per-class OvR AUCs are 0.98, 0.95, and 0.70. Will the macro average or the weighted average be higher, and why might the macro value still be the more honest summary for a user who cares about class 2?
Show answer
The weighted average is higher. It is about (9000.98 + 900.95 + 10*0.70) / 1000 = 0.9745, because class 0 dominates the weights. The macro average is (0.98 + 0.95 + 0.70) / 3, about 0.877. The macro value is more honest for a user who cares about class 2 because it gives the weak, rare class one third of the weight instead of 1%. In practice you should report the per-class AUCs as well.
Exercise
You call rocaucscore(ytest, model.decisionfunction(Xtest), multiclass="ovr") on a logistic regression with three classes, and scikit-learn raises an error. What is the cause, and what is the fix?
Show answer
For multiclass input, rocaucscore requires yscore to contain probability estimates whose rows sum to 1. decisionfunction returns unnormalized scores. Use model.predictproba(Xtest) instead. Alternatively, binarize the labels with labelbinarize and compute a binary rocauc_score for each column of the decision-function output, which does not require row sums of 1.