To compute the micro-average ROC AUC, True Positive Rate (TPR), and False Positive Rate (FPR) for a multiclass classification problem using sklearn, you can follow these steps:
- Train your classifier on your data.
- Use the
predict_proba method to get the probability estimates of the classes for each instance in your test dataset.
- Use the
roc_curve and auc functions from the sklearn.metrics module to compute the ROC curve and AUC.
Here's a step-by-step example:
import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import label_binarize
from sklearn.metrics import roc_curve, auc
from sklearn.ensemble import RandomForestClassifier
# Load a sample multiclass dataset
data = datasets.load_iris()
X, y = data.data, data.target
# Binarize the labels for multiclass
y_bin = label_binarize(y, classes=np.unique(y))
n_classes = y_bin.shape[1]
# Split the dataset
X_train, X_test, y_train, y_test = train_test_split(X, y_bin, test_size=0.5, random_state=0)
# Train a classifier (Random Forest in this case)
classifier = RandomForestClassifier(random_state=0)
classifier.fit(X_train, y_train)
# Get probability estimates
y_score = classifier.predict_proba(X_test)
# Compute micro-average ROC curve and ROC area
# Flatten y_test and y_score to compute micro-average ROC curve
fpr, tpr, _ = roc_curve(y_test.ravel(), y_score.ravel())
roc_auc = auc(fpr, tpr)
print(f'Micro-average ROC AUC: {roc_auc:.2f}')
# Micro-average ROC AUC: e.g., 0.98
# Plot the ROC curve if necessary
import matplotlib.pyplot as plt
plt.figure()
plt.plot(fpr, tpr, label='Micro-average ROC curve (area = {0:0.2f})'.format(roc_auc))
plt.plot([0, 1], [0, 1], 'k--')
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 to multi-class')
plt.legend(loc="lower right")
plt.show()
In this example, roc_curve and auc are used to calculate the micro-average ROC curve and AUC by passing the raveled (flattened) y_test and y_score arrays, which contain the true binary labels and the predicted probabilities for all classes concatenated together, respectively.
Note that the micro-average ROC AUC is computed by considering all the classes together as if it were a binary classification problem. The micro-average is particularly useful when you have an imbalance between classes, as it gives equal weight to the classification of each instance.