This example describes the use of the Receiver Operating Characteristic (ROC)
metric to evaluate the quality of multiclass classifiers.
ROC curves typically feature true positive rate (TPR) on the Y axis, and false
positive rate (FPR) on the X axis. This means that the top left corner of the
plot is the “ideal” point - a FPR of zero, and a TPR of one. This is not very
realistic, but it does mean that a larger area under the curve (AUC) is usually
better. The “steepness” of ROC curves is also important, since it is ideal to
maximize the TPR while minimizing the FPR.
ROC curves are typically used in binary classification, where the TPR and FPR
can be defined unambiguously. In the case of multiclass classification, a notion
of TPR or FPR is obtained only after binarizing the output. This can be done in
2 different ways:
the One-vs-Rest scheme compares each class against all the others (assumed as
one);
the One-vs-One scheme compares every unique pairwise combination of classes.
In this example we explore both schemes and demo the concepts of micro and macro
averaging as different ways of summarizing the information of the multiclass ROC
curves.
Receiver Operating Characteristic (ROC) with cross validation
# Authors: The scikit-learn developers# SPDX-License-Identifier: BSD-3-Clause
Load and prepare data
We import the Iris plants dataset which contains 3 classes, each one
corresponding to a type of iris plant. One class is linearly separable from
the other 2; the latter are not linearly separable from each other.
Here we binarize the output and add noisy features to make the problem harder.
The One-vs-the-Rest (OvR) multiclass strategy, also known as one-vs-all,
consists in computing a ROC curve per each of the n_classes. In each step, a
given class is regarded as the positive class and the remaining classes are
regarded as the negative class as a bulk.
In this section we use a LabelBinarizer to
binarize the target by one-hot-encoding in a OvR fashion. This means that the
target of shape (n_samples,) is mapped to a target of shape (n_samples,
n_classes).
We can as well easily check the encoding of a specific class:
label_binarizer.transform(["virginica"])
array([[0, 0, 1]])
ROC curve showing a specific class
In the following plot we show the resulting ROC curve when regarding the iris
flowers as either “virginica” (class_id=2) or “non-virginica” (the rest).
Micro-averaging aggregates the contributions from all the classes (using
numpy.ravel) to compute the average metrics as follows:
TPR=∑c(TPc+FNc)∑cTPc ;
ROC curve using the OvR macro-average
Obtaining the macro-average requires computing the metric independently for
each class and then taking the average over them, hence treating all classes
equally a priori. We first aggregate the true/false positive rates per class:
The One-vs-One (OvO) multiclass strategy consists in fitting one classifier
per class pair. Since it requires to train n_classes * (n_classes - 1) / 2
classifiers, this method is usually slower than One-vs-Rest due to its
O(n_classes ^2) complexity.
In this section, we demonstrate the macro-averaged AUC using the OvO scheme
for the 3 possible combinations in the Iris plants dataset: “setosa” vs
“versicolor”, “versicolor” vs “virginica” and “virginica” vs “setosa”. Notice
that micro-averaging is not defined for the OvO scheme.
ROC curve using the OvO macro-average
In the OvO scheme, the first step is to identify all possible unique
combinations of pairs. The computation of scores is done by treating one of
the elements in a given pair as the positive class and the other element as
the negative class, then re-computing the score by inversing the roles and
taking the mean of both scores.
One can also assert that the macro-average we computed “by hand” is equivalent
to the implemented average="macro" option of the
roc_auc_score function.
importmatplotlib.pyplotaspltfromsklearn.metricsimportRocCurveDisplaydisplay=RocCurveDisplay.from_predictions(y_onehot_test[:,class_id],y_score[:,class_id],name=f"{class_of_interest} vs the rest",curve_kwargs=dict(color="darkorange"),plot_chance_level=True,despine=True,)_=display.ax_.set(xlabel="False Positive Rate",ylabel="True Positive Rate",title="One-vs-Rest ROC curves:\nVirginica vs (Setosa & Versicolor)",)
In a multi-class classification setup with highly imbalanced classes,
micro-averaging is preferable over macro-averaging. In such cases, one can
alternatively use a weighted macro-averaging, not demonstrated here.
This is equivalent to computing the ROC curve with
roc_curve and then the area under the curve with
auc for the raveled true and predicted classes.
fromsklearn.metricsimportauc,roc_curve# store the fpr, tpr, and roc_auc for all averaging strategiesfpr,tpr,roc_auc=dict(),dict(),dict()# Compute micro-average ROC curve and ROC areafpr["micro"],tpr["micro"],_=roc_curve(y_onehot_test.ravel(),y_score.ravel())roc_auc["micro"]=auc(fpr["micro"],tpr["micro"])print(f"Micro-averaged One-vs-Rest ROC AUC score:\n{roc_auc['micro']:.2f}")
Micro-averaged One-vs-Rest ROC AUC score:
0.77
FPR=C1∑cFPc+TNcFPc .
where C is the total number of classes.
foriinrange(n_classes):fpr[i],tpr[i],_=roc_curve(y_onehot_test[:,i],y_score[:,i])roc_auc[i]=auc(fpr[i],tpr[i])fpr_grid=np.linspace(0.0,1.0,1000)# Interpolate all ROC curves at these pointsmean_tpr=np.zeros_like(fpr_grid)foriinrange(n_classes):mean_tpr+=np.interp(fpr_grid,fpr[i],tpr[i])# linear interpolation# Average it and compute AUCmean_tpr/=n_classesfpr["macro"]=fpr_gridtpr["macro"]=mean_tprroc_auc["macro"]=auc(fpr["macro"],tpr["macro"])print(f"Macro-averaged One-vs-Rest ROC AUC score:\n{roc_auc['macro']:.2f}")
We confirm that the classes “versicolor” and “virginica” are not well
identified by a linear classifier. Notice that the “virginica”-vs-the-rest
ROC-AUC score (0.77) is between the OvO ROC-AUC scores for “versicolor” vs
“virginica” (0.64) and “setosa” vs “virginica” (0.90). Indeed, the OvO
strategy gives additional information on the confusion between a pair of
classes, at the expense of computational cost when the number of classes
is large.
The OvO strategy is recommended if the user is mainly interested in correctly
identifying a particular class or subset of classes, whereas evaluating the
global performance of a classifier can still be summarized via a given
averaging strategy.
When dealing with imbalanced datasets, choosing the appropriate metric based on
the business context or problem you are addressing is crucial.
It is also essential to select an appropriate averaging method (micro vs. macro)
depending on the desired outcome:
Micro-averaging aggregates metrics across all instances, treating each
individual instance equally, regardless of its class. This approach is useful
when evaluating overall performance, but note that it can be dominated by
the majority class in imbalanced datasets.
Macro-averaging calculates metrics for each class independently and then
averages them, giving equal weight to each class. This is particularly useful
when you want under-represented classes to be considered as important as highly
populated classes.
Total running time of the script: (0 minutes 0.782 seconds)