Skip to content

roc_plot.py example gives different macro-averaged AUC than roc_auc_score #13546

Closed

Description

@eyaler

sklearn 0.20.1
code to reproduce (plot_roc.py + comparisons to roc_auc_score):

"""
=======================================
Receiver Operating Characteristic (ROC)
=======================================

Example of Receiver Operating Characteristic (ROC) metric to evaluate
classifier output quality.

ROC curves typically feature true positive rate on the Y axis, and false
positive rate on the X axis. This means that the top left corner of the plot is
the "ideal" point - a false positive rate of zero, and a true positive rate 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 true positive rate while minimizing the false positive rate.

Multiclass settings
-------------------

ROC curves are typically used in binary classification to study the output of
a classifier. In order to extend ROC curve and ROC area to multi-class
or multi-label classification, it is necessary to binarize the output. One ROC
curve can be drawn per label, but one can also draw a ROC curve by considering
each element of the label indicator matrix as a binary prediction
(micro-averaging).

Another evaluation measure for multi-class classification is
macro-averaging, which gives equal weight to the classification of each
label.

.. note::

    See also :func:`sklearn.metrics.roc_auc_score`,
             :ref:`sphx_glr_auto_examples_model_selection_plot_roc_crossval.py`.

"""
print(__doc__)

import numpy as np
import matplotlib.pyplot as plt
from itertools import cycle

from sklearn import svm, datasets
from sklearn.metrics import roc_curve, auc, roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import label_binarize
from sklearn.multiclass import OneVsRestClassifier
from scipy import interp

# Import some data to play with
iris = datasets.load_iris()
X = iris.data
y = iris.target

# Binarize the output
y = label_binarize(y, classes=[0, 1, 2])
n_classes = y.shape[1]

# Add noisy features to make the problem harder
random_state = np.random.RandomState(0)
n_samples, n_features = X.shape
X = np.c_[X, random_state.randn(n_samples, 200 * n_features)]

# shuffle and split training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5,
                                                    random_state=0)

# Learn to predict each class against the other
classifier = OneVsRestClassifier(svm.SVC(kernel='linear', probability=True,
                                 random_state=random_state))
y_score = classifier.fit(X_train, y_train).decision_function(X_test)

# Compute ROC curve and ROC area for each class
fpr = dict()
tpr = dict()
roc_auc = dict()
auc_score = roc_auc_score(y_test, y_score, average=None)

for i in range(n_classes):
    fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i])
    roc_auc[i] = auc(fpr[i], tpr[i])
    assert np.isclose(roc_auc[i], auc_score[i])

# Compute micro-average ROC curve and ROC area
fpr["micro"], tpr["micro"], _ = roc_curve(y_test.ravel(), y_score.ravel())
roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])
assert np.isclose(roc_auc['micro'], roc_auc_score(y_test, y_score, average='micro'))



##############################################################################
# Plot of a ROC curve for a specific class
plt.figure()
lw = 2
plt.plot(fpr[2], tpr[2], color='darkorange',
         lw=lw, label='ROC curve (area = %0.2f)' % roc_auc[2])
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic example')
plt.legend(loc="lower right")
plt.show()


##############################################################################
# Plot ROC curves for the multiclass problem

# Compute macro-average ROC curve and ROC area

# First aggregate all false positive rates
all_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_classes)]))

# Then interpolate all ROC curves at this points
mean_tpr = np.zeros_like(all_fpr)
for i in range(n_classes):
    mean_tpr += interp(all_fpr, fpr[i], tpr[i])

# Finally average it and compute AUC
mean_tpr /= n_classes

fpr["macro"] = all_fpr
tpr["macro"] = mean_tpr
roc_auc["macro"] = auc(fpr["macro"], tpr["macro"])
assert np.isclose(roc_auc['macro'], roc_auc_score(y_test, y_score, average='macro'))

# Plot all ROC curves
plt.figure()
plt.plot(fpr["micro"], tpr["micro"],
         label='micro-average ROC curve (area = {0:0.2f})'
               ''.format(roc_auc["micro"]),
         color='deeppink', linestyle=':', linewidth=4)

plt.plot(fpr["macro"], tpr["macro"],
         label='macro-average ROC curve (area = {0:0.2f})'
               ''.format(roc_auc["macro"]),
         color='navy', linestyle=':', linewidth=4)

colors = cycle(['aqua', 'darkorange', 'cornflowerblue'])
for i, color in zip(range(n_classes), colors):
    plt.plot(fpr[i], tpr[i], color=color, lw=lw,
             label='ROC curve of class {0} (area = {1:0.2f})'
             ''.format(i, roc_auc[i]))

plt.plot([0, 1], [0, 1], 'k--', lw=lw)
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Some extension of Receiver operating characteristic to multi-class')
plt.legend(loc="lower right")
plt.show()

Activity

  1. eyaler commented on Mar 30, 2019

    @eyaler
    Author

    the reason is the computation is different.
    roc_plot is computing average curves and than the auc of those curves.
    roc_auc_score is computing the average of the AUCs

  2. jnothman commented on Mar 31, 2019

    @jnothman
    Member
  3. hsjeong14 commented on Oct 26, 2021

    @hsjeong14

    when i try k-fold cross validation, each cv roc result different. roc_plot vs roc_auc_score

  4. added
    Needs Investigation
    and removed
    Needs Triage
    on Mar 10, 2022
  5. ArturoAmorQ commented on May 25, 2022

    @ArturoAmorQ
    Member

    when i try k-fold cross validation, each cv roc result different. roc_plot vs roc_auc_score

    Thanks for contributing to the discussion @hsjeong14, could you please craft a minimal reproducer to help us investigate the issue?

  6. ArturoAmorQ commented on Jul 20, 2022

    @ArturoAmorQ
    Member

    Minimal reproducer:

    from sklearn.linear_model import LogisticRegression
    from sklearn.metrics import roc_auc_score, RocCurveDisplay
    from sklearn.datasets import load_iris
    from sklearn.preprocessing import label_binarize
    
    X, y = load_iris(return_X_y=True)
    clf = LogisticRegression(solver="liblinear").fit(X, y)
    print(roc_auc_score(y, clf.predict_proba(X), multi_class='ovr'))
    
    
    y = label_binarize(y, classes=[0, 1, 2])
    y_pred = clf.decision_function(X)
    
    _ = RocCurveDisplay.from_predictions(y.ravel(), y_pred.ravel())

    Results:
    0.9913...
    output

  7. thomasjpfan commented on Jul 20, 2022

    @thomasjpfan
    Member

    In example from #13546 (comment), the RocCurveDisplay is computing roc_auc_score(y.ravel(), y_pred.ravel()). Another way to directly reproduce the value from roc_auc_score is to use micro-averaging:

    from sklearn.linear_model import LogisticRegression
    from sklearn.metrics import roc_auc_score, RocCurveDisplay
    from sklearn.datasets import load_iris
    from sklearn.preprocessing import label_binarize
    
    X, y = load_iris(return_X_y=True)
    clf = LogisticRegression(solver="liblinear").fit(X, y)
    
    # Treats the multi-class problem like a multi-label problem
    y_multi_label = label_binarize(y, classes=[0, 1, 2])
    roc_auc_score(y_multi_label, clf.decision_function(X), average="micro")
    # 0.97

    In the end, it's different averaging strategies. The example is treating the problem like a multi-label one and using micro-averaging. Using multi_class="ovr" is macro-averaging over the different classes from ovr.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions