AUC ROC Curve in Machine Learning
Last Updated :
06 Aug, 2024
One important aspect of Machine Learning is model evaluation. You need to have some mechanism to evaluate your model. This is where these performance metrics come into the picture they give us a sense of how good a model is. If you are familiar with some of the basics of Machine Learning then you must have come across some of these metrics, like accuracy, precision, recall, auc-roc, etc., which are generally used for classification tasks. In this article, we will explore in depth one such metric, which is the AUC-ROC curve.
What is the AUC-ROC curve?
The AUC-ROC curve, or Area Under the Receiver Operating Characteristic curve, is a graphical representation of the performance of a binary classification model at various classification thresholds. It is commonly used in machine learning to assess the ability of a model to distinguish between two classes, typically the positive class (e.g., presence of a disease) and the negative class (e.g., absence of a disease).
Let’s first understand the meaning of the two terms ROC and AUC.
Receiver Operating Characteristics (ROC) Curve
ROC stands for Receiver Operating Characteristics, and the ROC curve is the graphical representation of the effectiveness of the binary classification model. It plots the true positive rate (TPR) vs the false positive rate (FPR) at different classification thresholds.
Area Under Curve (AUC) Curve:
AUC stands for the Area Under the Curve, and the AUC curve represents the area under the ROC curve. It measures the overall performance of the binary classification model. As both TPR and FPR range between 0 to 1, So, the area will always lie between 0 and 1, and A greater value of AUC denotes better model performance. Our main goal is to maximize this area in order to have the highest TPR and lowest FPR at the given threshold. The AUC measures the probability that the model will assign a randomly chosen positive instance a higher predicted probability compared to a randomly chosen negative instance.
It represents the probability with which our model can distinguish between the two classes present in our target.

ROC-AUC Classification Evaluation Metric
Key terms used in AUC and ROC Curve
1. TPR and FPR
This is the most common definition that you would have encountered when you would Google AUC-ROC. Basically, the ROC curve is a graph that shows the performance of a classification model at all possible thresholds( threshold is a particular value beyond which you say a point belongs to a particular class). The curve is plotted between two parameters
- TPR – True Positive Rate
- FPR – False Positive Rate
Before understanding, TPR and FPR let us quickly look at the confusion matrix.

Confusion Matrix for a Classification Task
- True Positive: Actual Positive and Predicted as Positive
- True Negative: Actual Negative and Predicted as Negative
- False Positive(Type I Error): Actual Negative but predicted as Positive
- False Negative(Type II Error): Actual Positive but predicted as Negative
In simple terms, you can call False Positive a false alarm and False Negative a miss. Now let us look at what TPR and FPR are.
2. Sensitivity / True Positive Rate / Recall
Basically, TPR/Recall/Sensitivity is the ratio of positive examples that are correctly identified. It represents the ability of the model to correctly identify positive instances and is calculated as follows:
[Tex]TPR = \frac{TP}{TP+FN}
[/Tex]
Sensitivity/Recall/TPR measures the proportion of actual positive instances that are correctly identified by the model as positive.
3. False Positive Rate
FPR is the ratio of negative examples that are incorrectly classified.
[Tex]FPR = \frac{FP}{TN+FP}
[/Tex]
4. Specificity
Specificity measures the proportion of actual negative instances that are correctly identified by the model as negative. It represents the ability of the model to correctly identify negative instances
[Tex]\begin{aligned} \text{Specificity} &= \frac{TN}{TN+FP} \\&=1-\text{FPR} \end{aligned}
[/Tex]
And as said earlier ROC is nothing but the plot between TPR and FPR across all possible thresholds and AUC is the entire area beneath this ROC curve.

Sensitivity versus False Positive Rate plot
Relationship between Sensitivity, Specificity, FPR, and Threshold.
Sensitivity and Specificity:
- Inverse Relationship: sensitivity and specificity have an inverse relationship. When one increases, the other tends to decrease. This reflects the inherent trade-off between true positive and true negative rates.
- Tuning via Threshold: By adjusting the threshold value, we can control the balance between sensitivity and specificity. Lower thresholds lead to higher sensitivity (more true positives) at the expense of specificity (more false positives). Conversely, raising the threshold boosts specificity (fewer false positives) but sacrifices sensitivity (more false negatives).
Threshold and False Positive Rate (FPR):
- FPR and Specificity Connection: False Positive Rate (FPR) is simply the complement of specificity (FPR = 1 – specificity). This signifies the direct relationship between them: higher specificity translates to lower FPR, and vice versa.
- FPR Changes with TPR: Similarly, as you observed, the True Positive Rate (TPR) and FPR are also linked. An increase in TPR (more true positives) generally leads to a rise in FPR (more false positives). Conversely, a drop in TPR (fewer true positives) results in a decline in FPR (fewer false positives)
How does AUC-ROC work?
We looked at the geometric interpretation, but I guess it is still not enough in developing the intuition behind what 0.75 AUC actually means, now let us look at AUC-ROC from a probabilistic point of view. Let us first talk about what AUC does and later we will build our understanding on top of this
AUC measures how well a model is able to distinguish between classes.
An AUC of 0.75 would actually mean that let’s say we take two data points belonging to separate classes then there is a 75% chance the model would be able to segregate them or rank order them correctly i.e positive point has a higher prediction probability than the negative class. (assuming a higher prediction probability means the point would ideally belong to the positive class). Here is a small example to make things more clear.
Index
| Class
| Probability
|
|---|
P1
| 1
| 0.95
|
|---|
P2
| 1
| 0.90
|
|---|
P3
| 0
| 0.85
|
|---|
P4
| 0
| 0.81
|
|---|
P5
| 1
| 0.78
|
|---|
P6
| 0
| 0.70
|
|---|
Here we have 6 points where P1, P2, and P5 belong to class 1 and P3, P4, and P6 belong to class 0 and we’re corresponding predicted probabilities in the Probability column, as we said if we take two points belonging to separate classes then what is the probability that model rank orders them correctly.
We will take all possible pairs such that one point belongs to class 1 and the other belongs to class 0, we will have a total of 9 such pairs below are all of these 9 possible pairs.
Pair
| isCorrect
|
|---|
(P1,P3)
| Yes
|
|---|
(P1,P4)
| Yes
|
|---|
(P1,P6)
| Yes
|
|---|
(P2,P3)
| Yes
|
|---|
(P2,P4)
| Yes
|
|---|
(P2,P6)
| Yes
|
|---|
(P3,P5)
| No
|
|---|
(P4,P5)
| No
|
|---|
(P5,P6)
| Yes
|
|---|
Here column is Correct tells if the mentioned pair is correctly rank-ordered based on the predicted probability i.e class 1 point has a higher probability than class 0 point, in 7 out of these 9 possible pairs class 1 is ranked higher than class 0, or we can say that there is a 77% chance that if you pick a pair of points belonging to separate classes the model would be able to distinguish them correctly. Now, I think you might have a bit of intuition behind this AUC number, just to clear up any further doubts let’s validate it using Scikit learns AUC-ROC implementation.
Python
import numpy as np
from sklearn .metrics import roc_auc_score
y_true = [1, 1, 0, 0, 1, 0]
y_pred = [0.95, 0.90, 0.85, 0.81, 0.78, 0.70]
auc = np.round(roc_auc_score(y_true, y_pred), 3)
print("Auc for our sample data is {}".format(auc))
Output:
AUC for our sample data is 0.778
When should we use the AUC-ROC evaluation metric?
There are some areas where using ROC-AUC might not be ideal. In cases where the dataset is highly imbalanced, the ROC curve can give an overly optimistic assessment of the model’s performance. This optimism bias arises because the ROC curve’s false positive rate (FPR) can become very small when the number of actual negatives is large.
Looking at the FPR formula,
[Tex]\begin{aligned} FPR &= \frac{FP}{TN+FP} \end{aligned}
[/Tex]
we observe ,
- The Negative class is in the majority, the denominator of FPR is dominated by True Negatives, because of which FPR becomes less sensitive to changes in predictions related to the minority class (positive class).
- ROC curves may be appropriate when the cost of False Positives and False Negatives is balanced and the dataset is not heavily imbalanced.
In those case, Precision-Recall Curves can be used which provide an alternative evaluation metric that is more suitable for imbalanced datasets, focusing on the performance of the classifier with respect to the positive (minority) class.
- A high AUC (close to 1) indicates excellent discriminative power. This means the model is effective in distinguishing between the two classes, and its predictions are reliable.
- A low AUC (close to 0) suggests poor performance. In this case, the model struggles to differentiate between the positive and negative classes, and its predictions may not be trustworthy.
- AUC around 0.5 implies that the model is essentially making random guesses. It shows no ability to separate the classes, indicating that the model is not learning any meaningful patterns from the data.
Understanding the AUC-ROC Curve
In an ROC curve, the x-axis typically represents the False Positive Rate (FPR), and the y-axis represents the True Positive Rate (TPR), also known as Sensitivity or Recall. So, a higher x-axis value (towards the right) on the ROC curve does indicate a higher False Positive Rate, and a higher y-axis value (towards the top) indicates a higher True Positive Rate.The ROC curve is a graphical representation of the trade-off between true positive rate and false positive rate at various thresholds. It shows the performance of a classification model at different classification thresholds. The AUC (Area Under the Curve) is a summary measure of the ROC curve performance.The choice of the threshold depends on the specific requirements of the problem you’re trying to solve and the trade-off between false positives and false negatives that is acceptable in your context.
- If you want to prioritize reducing false positives (minimizing the chances of labeling something as positive when it’s not), you might choose a threshold that results in a lower false positive rate.
- If you want to prioritize increasing true positives (capturing as many actual positives as possible), you might choose a threshold that results in a higher true positive rate.
Let’s consider an example to illustrate how ROC curves are generated for different thresholds and how a particular threshold corresponds to a confusion matrix. Suppose we have a binary classification problem with a model predicting whether an email is spam (positive) or not spam (negative).
Let us consider the hypothetical data,
True Labels: [1, 0, 1, 0, 1, 1, 0, 0, 1, 0]
Predicted Probabilities: [0.8, 0.3, 0.6, 0.2, 0.7, 0.9, 0.4, 0.1, 0.75, 0.55]
Case 1: Threshold = 0.5
True Labels
| Predicted Probabilities
| Predicted Labels (if Threshold = 0.5)
|
|---|
|
1
|
0.8
|
1
|
|
0
|
0.3
|
0
|
|
1
|
0.6
|
1
|
|
0
|
0.2
|
0
|
|
1
|
0.7
|
1
|
|
1
|
0.9
|
1
|
|
0
|
0.4
|
0
|
|
0
|
0.1
|
0
|
|
1
|
0.75
|
1
|
|
0
|
0.55
|
1
|
Confusion matrix based on above predictions
| Prediction = 0
| Prediction = 1
|
|---|
Actual = 0
| TP=4
| FN=1
|
|---|
Actual = 1
| FP=0
| TN=5
|
|---|
Accordingly,
- True Positive Rate (TPR):
Proportion of actual positives correctly identified by the classifier is
[Tex]\begin{aligned}
TPR &= \frac{TP}{TP + FN}
\\&= \frac{4}{4+ 1}
\\&= 0.8
\end{aligned}[/Tex] - False Positive Rate (FPR):
Proportion of actual negatives incorrectly classified as positives
[Tex]\begin{aligned}
FPR &= \frac{FP}{FP + TN}
\\&= \frac{0}{0 + 5}
\\&= 0
\end{aligned}[/Tex]
So, at the threshold of 0.5:
- True Positive Rate (Sensitivity): 0.8
- False Positive Rate: 0
The interpretation is that the model, at this threshold, correctly identifies 80% of actual positives (TPR) but incorrectly classifies 0% of actual negatives as positives (FPR).
Accordingly for different thresholds we will get ,
Case 2: Threshold = 0.7
True Labels
| Predicted Probabilities
| Predicted Labels (if Threshold = 0.7)
|
|---|
|
1
|
0.8
|
1
|
|
0
|
0.3
|
0
|
|
1
|
0.6
|
0
|
|
0
|
0.2
|
0
|
|
1
|
0.7
|
0
|
|
1
|
0.9
|
1
|
|
0
|
0.4
|
0
|
|
0
|
0.1
|
0
|
|
1
|
0.75
|
1
|
|
0
|
0.55
|
0
|
Confusion matrix based on above predictions
| Prediction = 0
| Prediction = 1
|
|---|
Actual = 0
| TP=5
| FN=0
|
|---|
Actual = 1
| FP=2
| TN=3
|
|---|
Accordingly,
- True Positive Rate (TPR):
Proportion of actual positives correctly identified by the classifier is
[Tex]\begin{aligned}
TPR &= \frac{TP}{TP + FN}
\\&= \frac{5}{5+ 0}
\\&= 1.0
\end{aligned}[/Tex] - False Positive Rate (FPR):
Proportion of actual negatives incorrectly classified as positives
[Tex]\begin{aligned}
FPR &= \frac{FP}{FP + TN}
\\&= \frac{1}{1+ 4}
\\&= 0.2
\end{aligned}[/Tex]
Case 3: Threshold = 0.4
True Labels
| Predicted Probabilities
| Predicted Labels (if Threshold = 0.4)
|
|---|
|
1
|
0.8
|
1
|
|
0
|
0.3
|
0
|
|
1
|
0.6
|
1
|
|
0
|
0.2
|
0
|
|
1
|
0.7
|
1
|
|
1
|
0.9
|
1
|
|
0
|
0.4
|
0
|
|
0
|
0.1
|
0
|
|
1
|
0.75
|
1
|
|
0
|
0.55
|
1
|
Confusion matrix based on above predictions
| Prediction = 0
| Prediction = 1
|
|---|
Actual = 0
| TP=4
| FN=1
|
|---|
Actual = 1
| FP=0
| TN=5
|
|---|
Accordingly,
- True Positive Rate (TPR):
Proportion of actual positives correctly identified by the classifier is
[Tex]\begin{aligned}
TPR &= \frac{TP}{TP + FN}
\\&= \frac{4}{4+ 1}
\\&= 0.8
\end{aligned}[/Tex] - False Positive Rate (FPR):
Proportion of actual negatives incorrectly classified as positives
[Tex]\begin{aligned}
FPR &= \frac{FP}{FP + TN}
\\&= \frac{0}{0 + 5}
\\&= 0
\end{aligned}[/Tex]
Case 4: Threshold = 0.2
True Labels
| Predicted Probabilities
| Predicted Labels (if Threshold = 0.2)
|
|---|
|
1
|
0.8
|
1
|
|
0
|
0.3
|
1
|
|
1
|
0.6
|
1
|
|
0
|
0.2
|
0
|
|
1
|
0.7
|
1
|
|
1
|
0.9
|
1
|
|
0
|
0.4
|
1
|
|
0
|
0.1
|
0
|
|
1
|
0.75
|
1
|
|
0
|
0.55
|
1
|
Confusion matrix based on above predictions
| Prediction = 0
| Prediction = 1
|
|---|
Actual = 0
| TP=2
| FN=3
|
|---|
Actual = 1
| FP=0
| TN=5
|
|---|
Accordingly,
- True Positive Rate (TPR):
Proportion of actual positives correctly identified by the classifier is
[Tex]\begin{aligned}
TPR &= \frac{TP}{TP + FN}
\\&= \frac{2}{2+ 3}
\\&= 0.4
\end{aligned}[/Tex] - False Positive Rate (FPR):
Proportion of actual negatives incorrectly classified as positives
[Tex]\begin{aligned}
FPR &= \frac{FP}{FP + TN}
\\&= \frac{0}{0 + 5}
\\&= 0
\end{aligned}[/Tex]
Case 5: Threshold = 0.85
True Labels
| Predicted Probabilities
| Predicted Labels (if Threshold = 0.85)
|
|---|
|
1
|
0.8
|
0
|
|
0
|
0.3
|
0
|
|
1
|
0.6
|
0
|
|
0
|
0.2
|
0
|
|
1
|
0.7
|
0
|
|
1
|
0.9
|
1
|
|
0
|
0.4
|
0
|
|
0
|
0.1
|
0
|
|
1
|
0.75
|
0
|
|
0
|
0.55
|
0
|
Confusion matrix based on above predictions
| Prediction = 0
| Prediction = 1
|
|---|
Actual = 0
| TP=5
| FN=0
|
|---|
Actual = 1
| FP=4
| TN=1
|
|---|
Accordingly,
- True Positive Rate (TPR):
Proportion of actual positives correctly identified by the classifier is
[Tex]\begin{aligned}
TPR &= \frac{TP}{TP + FN}
\\&= \frac{5}{5+ 0}
\\&= 1.0
\end{aligned}[/Tex] - False Positive Rate (FPR):
Proportion of actual negatives incorrectly classified as positives
[Tex]\begin{aligned}
FPR &= \frac{FP}{FP + TN}
\\&= \frac{4}{4 + 1}
\\&= 0.8
\end{aligned}[/Tex]
Based on the above result, we will plot the ROC curve
Python
true_positive_rate = [0.4, 0.8, 0.8, 1.0, 1]
false_positive_rate = [0, 0, 0, 0.2, 0.8]
plt.plot(false_positive_rate, true_positive_rate, 'o-', label='ROC')
plt.plot([0, 1], [0, 1], '--', color='grey', label='Worst case')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Curve')
plt.legend()
plt.show()
Output:

From the graph it is implied that:
- The gray dashed line represents the “Worst case” scenario, where the model’s predictions i.e TPR are FPR are same. This diagonal line is considered the worst-case scenario, indicating an equal likelihood of false positives and false negatives.
- As points deviate from the random guess line towards the upper-left corner, the model’s performance improves.
- The Area Under the Curve (AUC) is a quantitative measure of the model’s discriminative ability. A higher AUC value, closer to 1.0, indicates superior performance. The best possible AUC value is 1.0, corresponding to a model that achieves 100% sensitivity and 100% specificity.
In all, the Receiver Operating Characteristic (ROC) curve serves as a graphical representation of the trade-off between a binary classification model’s True Positive Rate (sensitivity) and False Positive Rate at various decision thresholds. As the curve gracefully ascends towards the upper-left corner, it signifies the model’s commendable ability to discriminate between positive and negative instances across a range of confidence thresholds. This upward trajectory indicates an improved performance, with higher sensitivity achieved while minimizing false positives. The annotated thresholds, denoted as A, B, C, D, and E, offer valuable insights into the model’s dynamic behavior at different confidence levels.
Implementation using two different models
Installing Libraries
Python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_curve, auc
In order to train the Random Forest and Logistic Regression models and to present their ROC curves with AUC scores, the algorithm creates artificial binary classification data.
Generating data and splitting data
Python
# Generate synthetic data for demonstration
X, y = make_classification(
n_samples=1000, n_features=20, n_classes=2, random_state=42)
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42)
Using an 80-20 split ratio, the algorithm creates artificial binary classification data with 20 features, divides it into training and testing sets, and assigns a random seed to ensure reproducibility.
Training the different models
Python
# Train two different models
logistic_model = LogisticRegression(random_state=42)
logistic_model.fit(X_train, y_train)
random_forest_model = RandomForestClassifier(n_estimators=100, random_state=42)
random_forest_model.fit(X_train, y_train)
Using a fixed random seed to ensure repeatability, the method initializes and trains a logistic regression model on the training set. In a similar manner, it uses the training data and the same random seed to initialize and train a Random Forest model with 100 trees.
Predictions
Python
# Generate predictions
y_pred_logistic = logistic_model.predict_proba(X_test)[:, 1]
y_pred_rf = random_forest_model.predict_proba(X_test)[:, 1]
Using the test data and a trained Logistic Regression model, the code predicts the positive class’s probability. In a similar manner, using the test data, it uses the trained Random Forest model to produce projected probabilities for the positive class.
Creating a dataframe
Python
# Create a DataFrame
test_df = pd.DataFrame(
{'True': y_test, 'Logistic': y_pred_logistic, 'RandomForest': y_pred_rf})
Using the test data, the code creates a DataFrame called test_df with columns labeled “True,” “Logistic,” and “RandomForest,” adding true labels and predicted probabilities from the Random Forest and Logistic Regression models.
Plot the ROC Curve for the models
Python
# Plot ROC curve for each model
plt.figure(figsize=(7, 5))
for model in ['Logistic', 'RandomForest']:
fpr, tpr, _ = roc_curve(test_df['True'], test_df[model])
roc_auc = auc(fpr, tpr)
plt.plot(fpr, tpr, label=f'{model} (AUC = {roc_auc:.2f})')
# Plot random guess line
plt.plot([0, 1], [0, 1], 'r--', label='Random Guess')
# Set labels and title
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Curves for Two Models')
plt.legend()
plt.show()
Output:

The code generates a plot with 8 by 6 inch figures. It computes the AUC and ROC curve for each model (Random Forest and Logistic Regression), then plots the ROC curve. The ROC curve for random guessing is also represented by a red dashed line, and labels, a title, and a legend are set for visualization.
How to use ROC-AUC for a multi-class model?
For a multi-class setting, we can simply use one vs all methodology and you will have one ROC curve for each class. Let’s say you have four classes A, B, C, and D then there would be ROC curves and corresponding AUC values for all the four classes, i.e. once A would be one class and B, C, and D combined would be the others class, similarly, B is one class and A, C, and D combined as others class, etc.
The general steps for using AUC-ROC in the context of a multiclass classification model are:
One-vs-All Methodology:
- For each class in your multiclass problem, treat it as the positive class while combining all other classes into the negative class.
- Train the binary classifier for each class against the rest of the classes.
Calculate AUC-ROC for Each Class:
- Here we plot the ROC curve for the given class against the rest.
- Plot the ROC curves for each class on the same graph. Each curve represents the discrimination performance of the model for a specific class.
- Examine the AUC scores for each class. A higher AUC score indicates better discrimination for that particular class.
Implementation of AUC-ROC in Multiclass Classification
Importing Libraries
Python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import label_binarize
from sklearn.multiclass import OneVsRestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_curve, auc
from itertools import cycle
The program creates artificial multiclass data, divides it into training and testing sets, and then uses the One-vs-Restclassifier technique to train classifiers for both Random Forest and Logistic Regression. Lastly, it plots the two models’ multiclass ROC curves to demonstrate how well they discriminate between various classes.
Generating Data and splitting
Python
# Generate synthetic multiclass data
X, y = make_classification(
n_samples=1000, n_features=20, n_classes=3, n_informative=10, random_state=42)
# Binarize the labels
y_bin = label_binarize(y, classes=np.unique(y))
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(
X, y_bin, test_size=0.2, random_state=42)
Three classes and twenty features make up the synthetic multiclass data produced by the code. After label binarization, the data is divided into training and testing sets in an 80-20 ratio.
Training Models
Python
# Train two different multiclass models
logistic_model = OneVsRestClassifier(LogisticRegression(random_state=42))
logistic_model.fit(X_train, y_train)
rf_model = OneVsRestClassifier(
RandomForestClassifier(n_estimators=100, random_state=42))
rf_model.fit(X_train, y_train)
The program trains two multiclass models: a Random Forest model with 100 estimators and a Logistic Regression model with the One-vs-Rest approach. With the training set of data, both models are fitted.
Plotting the AUC-ROC Curve
Python
# Compute ROC curve and ROC area for each class
fpr = dict()
tpr = dict()
roc_auc = dict()
models = [logistic_model, rf_model]
plt.figure(figsize=(6, 5))
colors = cycle(['aqua', 'darkorange'])
for model, color in zip(models, colors):
for i in range(model.classes_.shape[0]):
fpr[i], tpr[i], _ = roc_curve(
y_test[:, i], model.predict_proba(X_test)[:, i])
roc_auc[i] = auc(fpr[i], tpr[i])
plt.plot(fpr[i], tpr[i], color=color, lw=2,
label=f'{model.__class__.__name__} - Class {i} (AUC = {roc_auc[i]:.2f})')
# Plot random guess line
plt.plot([0, 1], [0, 1], 'k--', lw=2, label='Random Guess')
# Set labels and title
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Multiclass ROC Curve with Logistic Regression and Random Forest')
plt.legend(loc="lower right")
plt.show()
Output:

The Random Forest and Logistic Regression models’ ROC curves and AUC scores are calculated by the code for each class. The multiclass ROC curves are then plotted, showing the discrimination performance of each class and featuring a line that represents random guessing. The resulting plot offers a graphic evaluation of the models’ classification performance.
Conclusion
In machine learning, the performance of binary classification models is assessed using a crucial metric called the Area Under the Receiver Operating Characteristic (AUC-ROC). Across various decision thresholds, it shows how sensitivity and specificity are traded off. Greater discrimination between positive and negative instances is typically exhibited by a model with a higher AUC score. Whereas 0.5 denotes chance, 1 represents flawless performance. Model optimization and selection are aided by the useful information that the AUC-ROC curve offers about a model’s capacity to discriminate between classes. When working with unbalanced datasets or applications where false positives and false negatives have different costs, it is particularly useful as a comprehensive measure.
FAQs for AUC ROC Curve in Machine Learning
1. What is the AUC-ROC curve?
For various classification thresholds, the trade-off between true positive rate (sensitivity) and false positive rate (specificity) is graphically represented by the AUC-ROC curve.
2. What does a perfect AUC-ROC curve look like?
An area of 1 on an ideal AUC-ROC curve would mean that the model achieves optimal sensitivity and specificity at all thresholds.
3. What does an AUC value of 0.5 signify?
AUC of 0.5 indicates that the model’s performance is comparable to that of random chance. It suggests a lack of discriminating ability.
4. Can AUC-ROC be used for multiclass classification?
AUC-ROC is frequently applied to issues involving binary classification. Variations such as the macro-average or micro-average AUC can be taken into consideration for multiclass classification.
5. How is the AUC-ROC curve useful in model evaluation?
The ability of a model to discriminate between classes is comprehensively summarized by the AUC-ROC curve. When working with unbalanced datasets, it is especially helpful.
Similar Reads
Machine Learning Algorithms
Machine learning algorithms are essentially sets of instructions that allow computers to learn from data, make predictions, and improve their performance over time without being explicitly programmed. Machine learning algorithms are broadly categorized into three types: Supervised Learning: Algorith
9 min read
Top 15 Machine Learning Algorithms Every Data Scientist Should Know in 2025
Machine Learning (ML) Algorithms are the backbone of everything from Netflix recommendations to fraud detection in financial institutions. These algorithms form the core of intelligent systems, empowering organizations to analyze patterns, predict outcomes, and automate decision-making processes. Wi
15 min read
Linear Model Regression
Ordinary Least Squares (OLS) using statsmodels
In this article, we will use Python's statsmodels module to implement Ordinary Least Squares ( OLS ) method of linear regression. Introduction : A linear regression model establishes the relation between a dependent variable( y ) and at least one independent variable( x ) as : [Tex] \hat{y}=b_1x+b_0
4 min read
Linear Regression (Python Implementation)
Linear regression is a statistical method that is used to predict a continuous dependent variable i.e target variable based on one or more independent variables. This technique assumes a linear relationship between the dependent and independent variables which means the dependent variable changes pr
14 min read
ML | Multiple Linear Regression using Python
Linear Regression: It is the basic and commonly used type for predictive analysis. It is a statistical approach to modeling the relationship between a dependent variable and a given set of independent variables. These are of two types: Simple linear RegressionMultiple Linear Regression Let's Discuss
6 min read
Polynomial Regression ( From Scratch using Python )
Prerequisites Linear RegressionGradient DescentIntroductionLinear Regression finds the correlation between the dependent variable ( or target variable ) and independent variables ( or features ). In short, it is a linear model to fit the data linearly. But it fails to fit and catch the pattern in no
5 min read
Implementation of Bayesian Regression
Linear regression is a popular regression approach in machine learning. Linear regression is based on the assumption that the underlying data is normally distributed and that all relevant predictor variables have a linear relationship with the outcome. But In the real world, this is not always poss
13 min read
How to Perform Quantile Regression in Python
In this article, we are going to see how to perform quantile regression in Python. Linear regression is defined as the statistical method that constructs a relationship between a dependent variable and an independent variable as per the given set of variables. While performing linear regression we a
4 min read
Isotonic Regression in Scikit Learn
Isotonic regression is a regression technique in which the predictor variable is monotonically related to the target variable. This means that as the value of the predictor variable increases, the value of the target variable either increases or decreases in a consistent, non-oscillating manner. Mat
6 min read
Stepwise Regression in Python
Stepwise regression is a method of fitting a regression model by iteratively adding or removing variables. It is used to build a model that is accurate and parsimonious, meaning that it has the smallest number of variables that can explain the data. There are two main types of stepwise regression: F
6 min read
Least Angle Regression (LARS)
Regression is a supervised machine learning task that can predict continuous values (real numbers), as compared to classification, that can predict categorical or discrete values. Before we begin, if you are a beginner, I highly recommend this article. Least Angle Regression (LARS) is an algorithm u
3 min read
Linear Model Classification
K-Nearest Neighbors (KNN)
ML | Stochastic Gradient Descent (SGD)
Gradient Descent is an iterative optimization process that searches for an objective function's optimum value (Minimum/Maximum). It is one of the most used methods for changing a model's parameters in order to reduce a cost function in machine learning projects. The primary goal of gradient descen
10 min read
Ensemble Learning
Ensemble Methods in Python
Ensemble means a group of elements viewed as a whole rather than individually. An Ensemble method creates multiple models and combines them to solve it. Ensemble methods help to improve the robustness/generalizability of the model. In this article, we will discuss some methods with their implementat
11 min read
Random Forest Regression in Python
Random Forest Regression is a versatile machine-learning technique for predicting numerical values. It combines the predictions of multiple decision trees to reduce overfitting and improve accuracy. Python's machine-learning libraries make it easy to implement and optimize this approach. Ensemble Le
11 min read
ML | Extra Tree Classifier for Feature Selection
Prerequisites: Decision Tree Classifier Extremely Randomized Trees Classifier(Extra Trees Classifier) is a type of ensemble learning technique which aggregates the results of multiple de-correlated decision trees collected in a "forest" to output it's classification result. In concept, it is very si
6 min read
Implementing the AdaBoost Algorithm From Scratch
In this article, we will learn about the AdaBoost classifier and its practical implementation over a dataset.AdaBoost algorithm falls under ensemble boosting techniques, as we will discuss it combines multiple models to produce more accurate results and this is done in two phases: Multiple weak lear
6 min read
XGBoost
XGBoost is short form for Extreme Gradient Boosting, has become one of the most powerful and widely used machine learning algorithms known for its speed, scalability, and high performance. In this article we will learn about the XG Boost algorithm. Understanding XG Boost Algorithm XGBoost is an impl
5 min read
CatBoost in Machine Learning
We often encounter datasets that contain categorical features and to fit these datasets into the Boosting model we apply various encoding techniques to the dataset such as One-Hot Encoding or Label Encoding. But applying One-Hot encoding creates a sparse matrix which may sometimes lead to the overfi
9 min read
LightGBM (Light Gradient Boosting Machine)
LightGBM is an ensemble learning framework, specifically a gradient boosting method, which constructs a strong learner by sequentially adding weak learners in a gradient descent manner. It optimizes memory usage and training time with techniques like Gradient-based One-Side Sampling (GOSS). Table of
10 min read
Stacking in Machine Learning
Stacking is a way to ensemble multiple classifications or regression model. There are many ways to ensemble models, the widely known models are Bagging or Boosting. Bagging allows multiple similar models with high variance are averaged to decrease variance. Boosting builds multiple incremental model
2 min read
Generative Model
ML | Naive Bayes Scratch Implementation using Python
A key concept in probability theory, the Bayes theorem, provides the foundation for the probabilistic classifier known as Naive Bayes. It is a simple yet powerful algorithm that has risen in popularity because of its understanding, simplicity, and ease of implementation. Naive Bayes Algorithm is a p
8 min read
Applying Multinomial Naive Bayes to NLP Problems
Multinomial Naive Bayes (MNB) is a popular machine learning algorithm for text classification problems in Natural Language Processing (NLP). It is particularly useful for problems that involve text data with discrete features such as word frequency counts. MNB works on the principle of Bayes theorem
7 min read
Gaussian Process Classification (GPC) on the XOR Dataset in Scikit Learn
Gaussian process classification (GPC) is a probabilistic approach to classification that models the conditional distribution of the class labels given the feature values. In GPC, the data is assumed to be generated by a Gaussian process, which is a stochastic process that is characterized by its mea
4 min read
Gaussian Discriminant Analysis
Gaussian Discriminant Analysis (GDA) is a supervised learning algorithm used for classification tasks in machine learning. It is a variant of the Linear Discriminant Analysis (LDA) algorithm that relaxes the assumption that the covariance matrices of the different classes are equal. GDA works by ass
7 min read
Quadratic Discriminant Analysis
Linear Discriminant Analysis Now, Let's consider a classification problem represented by a Bayes Probability distribution P(Y=k | X=x), LDA does it differently by trying to model the distribution of X given the predictors class (I.e. the value of Y) P(X=x| Y=k): [Tex]P(Y=k | X=x) = \frac{P(X=x | Y=k
4 min read
Basic Understanding of Bayesian Belief Networks
Bayesian Belief Network is a graphical representation of different probabilistic relationships among random variables in a particular set. It is a classifier with no dependency on attributes i.e it is condition independent. Due to its feature of joint probability, the probability in Bayesian Belief
4 min read
Hidden Markov Model in Machine learning
A statistical model called a Hidden Markov Model (HMM) is used to describe systems with changing unobservable states over time. It is predicated on the idea that there is an underlying process with concealed states, each of which has a known result. Probabilities for switching between concealed stat
11 min read
Time Series Forecasting
Components of Time Series Data
Time series data, which consists of observations recorded over time at regular intervals, can be analyzed by breaking it down into four primary components. These components help identify patterns, trends, and irregularities in the data. It's often shown as a line graph to easily see patterns over ti
10 min read
AutoCorrelation
Autocorrelation is a fundamental concept in time series analysis. Autocorrelation is a statistical concept that assesses the degree of correlation between the values of variable at different time points. The article aims to discuss the fundamentals and working of Autocorrelation. Table of Content Wh
10 min read
How to Check if Time Series Data is Stationary with Python?
Time series data are generally characterized by their temporal nature. This temporal nature adds a trend or seasonality to the data that makes it compatible for time series analysis and forecasting. Time-series data is said to be stationary if it doesn't change with time or if they don't have a temp
8 min read
How to Perform an Augmented Dickey-Fuller Test in R
Augmented Dickey-Fuller Test: It is a common test in statistics and is used to check whether a given time series is at rest. A given time series can be called stationary or at rest if it doesn't have any trend and depicts a constant variance over time and follows autocorrelation structure over a per
3 min read
How to calculate MOVING AVERAGE in a Pandas DataFrame?
Calculating the moving average in a Pandas DataFrame is used for smoothing time series data and identifying trends. The moving average, also known as the rolling mean, helps reduce noise and highlight significant patterns by averaging data points over a specific window. In Pandas, this can be achiev
7 min read
Exponential Smoothing in R Programming
The Exponential Smoothing is a technique for smoothing data of time series using an exponential window function. It is a rule of the thumb method. Unlike simple moving average, over time the exponential functions assign exponentially decreasing weights. Here the greater weights are placed on the rec
15+ min read
Python | ARIMA Model for Time Series Forecasting
A Time Series is defined as a series of data points indexed in time order. The time order can be daily, monthly, or even yearly. Given below is an example of a Time Series that illustrates the number of passengers of an airline per month from the year 1949 to 1960. Time Series Forecasting Time Serie
5 min read
Supervised Dimensionality Reduction Technique
Metrics for Classification & Regression Algorithms
Python | Mean Squared Error
The Mean Squared Error (MSE) or Mean Squared Deviation (MSD) of an estimator measures the average of error squares i.e. the average squared difference between the estimated values and true value. It is a risk function, corresponding to the expected value of the squared error loss. It is always non –
2 min read
Root-Mean-Square Error in R Programming
In this article, we will cover the theory behind RMSE, explain its significance, and provide detailed steps on how to compute RMSE in R programming using different approaches using R Programming Language. What is RMSE?Root mean squared error (RMSE) is the square root of the mean of the square of all
4 min read
How to Calculate Mean Absolute Error in Python?
When building machine learning models, our aim is to make predictions as accurately as possible. However, not all models are perfect some predictions will surely deviate from the actual values. To evaluate how well a model performs, we rely on error metrics. One widely used metric for measuring pred
4 min read
R-squared in Regression Analysis in Machine Learning
The most important thing we do after making any model is evaluating the model. We have different evaluation matrices for evaluating the model. However, the choice of evaluation matrix to use for evaluating the model depends upon the type of problem we are solving whether it's a regression, classific
4 min read
ML | Adjusted R-Square in Regression Analysis
Prerequisite: Linear Regression, R-square in Regression Why Adjusted-R Square Test: R-square test is used to determine the goodness of fit in regression analysis. Goodness of fit implies how better regression model is fitted to the data points. More is the value of r-square near to 1, better is the
3 min read
Understanding the Confusion Matrix in Machine Learning
Machine learning models are increasingly used in various applications to classify data into different categories. However, evaluating the performance of these models is crucial to ensure their accuracy and reliability. One essential tool in this evaluation process is the confusion matrix. In this ar
9 min read
Techniques To Evaluate Accuracy of Classifier in Data Mining
Pre-requisites: Data Mining Data Mining can be referred to as knowledge mining from data, knowledge extraction, data/pattern analysis, data archaeology, and data dredging. In this article, we will see techniques to evaluate the accuracy of classifiers. HoldOutIn the holdout method, the largest datas
3 min read
Precision Handling in Python
Python in its definition allows handling the precision of floating-point numbers in several ways using different functions. Most of them are defined under the "math" module. In this article, we will use high-precision calculations in Python with Decimal in Python. Example Input: x = 2.4Output: Integ
6 min read
Precision-Recall Curve | ML
There are numerous ways to evaluate the performance of a classifier. In this article, we introduce the Precision-Recall Curve and further examine the difference between two popular performance reporting methods: Precision-Recall (PR) Curve and Receiver Operating Characteristic (ROC) Curve. ROC Curve
10 min read
Calculate Sensitivity, Specificity and Predictive Values in CARET
R programming is used for predictive data analysis we all know that. In R the "CARET" package is used to train and evaluate machine learning models. The 'caret' package (short for Classification and Regression Training) is a comprehensive and powerful tool that provides a unified interface and a wid
9 min read
How to Calculate F1 Score in R?
In this article, we will be looking at the approach to calculate F1 Score using the various packages and their various functionalities in the R language. F1 Score The F-score or F-measure is a measure of a test's accuracy. It is calculated from the precision and recall of the test, where the precisi
5 min read
AUC ROC Curve in Machine Learning
One important aspect of Machine Learning is model evaluation. You need to have some mechanism to evaluate your model. This is where these performance metrics come into the picture they give us a sense of how good a model is. If you are familiar with some of the basics of Machine Learning then you mu
15+ min read
Probability Calibration Curve in Scikit Learn
Probability Calibration is a technique used to convert the output scores from a binary classifier into probabilities to correlate with the actual probabilities of the target class. In this article, we will discuss probability calibration curves and how to plot them using Scikit-learn. Probability Ca
6 min read
Calibration Curves
Generally, for any classification problem, we predict the class value that has the highest probability of being the true class label. However, sometimes, we want to predict the probabilities of a data instance belonging to each class label. For example, say we are building a model to classify fruits
3 min read
Probability Calibration of Classifiers in Scikit Learn
In this article, we will explore the concepts and techniques related to the probability calibration of classifiers in the context of machine learning. Classifiers in machine learning frequently provide probabilities indicating how confident they are in their predictions. However, the probabilities m
4 min read
Cross Validation Technique
Optimization Technique
Gradient Descent in Linear Regression
We know that in any machine learning project our main aim relies on how good our project accuracy is or how much our model prediction differs from the actual data point. Based on the difference between model prediction and actual data points we try to find the parameters of the model which give bett
9 min read
ML | Stochastic Gradient Descent (SGD)
Gradient Descent is an iterative optimization process that searches for an objective function's optimum value (Minimum/Maximum). It is one of the most used methods for changing a model's parameters in order to reduce a cost function in machine learning projects. The primary goal of gradient descen
10 min read
ML | Mini-Batch Gradient Descent with Python
In machine learning, gradient descent is an optimization technique used for computing the model parameters (coefficients and bias) for algorithms like linear regression, logistic regression, neural networks, etc. In this technique, we repeatedly iterate through the training set and update the model
5 min read
ML | Momentum-based Gradient Optimizer introduction
Gradient Descent is an optimization technique used in Machine Learning frameworks to train different models. The training process consists of an objective function (or the error function), which determines the error a Machine Learning model has on a given dataset. While training, the parameters of t
5 min read
Find root of a number using Newton's method
Given an integer N and a tolerance level L, the task is to find the square root of that number using Newton's Method.Examples: Input: N = 16, L = 0.0001 Output: 4 42 = 16Input: N = 327, L = 0.00001 Output: 18.0831 Newton's Method: Let N be any number then the square root of N can be given by the for
7 min read
Hill Climbing in Artificial Intelligence
Hill climbing is a widely used optimization algorithm in Artificial Intelligence (AI) that helps find the best possible solution to a given problem. As part of the local search algorithms family, it is often applied to optimization problems where the goal is to identify the optimal solution from a s
12 min read
What is TABU Search?
Tabu search (TS) is an iterative neighborhood search algorithm, where the neighborhood changes dynamically. Tabu search enhances local search by avoiding points in the search space which are already visited. By avoiding already visited points, loops in search space are avoided and local optima can b
11 min read
Clustering
Clustering in Machine Learning
In real world, not every data we work upon has a target variable. This kind of data cannot be analyzed using supervised learning algorithms. We need the help of unsupervised algorithms. One of the most popular type of analysis under unsupervised learning is Cluster analysis. When the goal is to grou
12 min read
K means Clustering - Introduction
K-Means Clustering is an Unsupervised Machine Learning algorithm which groups the unlabeled dataset into different clusters. The article aims to explore the fundamentals and working of k means clustering along with its implementation. Understanding K-means ClusteringK-means clustering is a technique
6 min read
ML | K-means++ Algorithm
Prerequisite: K-means Clustering – IntroductionDrawback of standard K-means algorithm:One disadvantage of the K-means algorithm is that it is sensitive to the initialization of the centroids or the mean points. So, if a centroid is initialized to be a "far-off" point, it might just end up with no po
5 min read
K-Mode Clustering in Python
K-mode clustering is an unsupervised machine-learning technique used to group a set of data objects into a specified number of clusters, based on their categorical attributes. The algorithm is called "K-Mode" because it uses modes (i.e. the most frequent values) instead of means or medians to repres
8 min read
Fuzzy C-means Clustering in MATLAB
Fuzzy C-means (FCM) is a method of clustering that allows points to be more than one cluster. The (FCM) is a kind of data clustering technique in which the data set is grouped into N numbers of clusters with every data point corresponding to each cluster on the basis. which is to differentiate the d
4 min read
Gaussian Mixture Model
Suppose there are a set of data points that need to be grouped into several parts or clusters based on their similarity. In Machine Learning, this is known as Clustering. There are several methods available for clustering: K Means ClusteringHierarchical ClusteringGaussian Mixture Models In this arti
6 min read
ML | Expectation-Maximization Algorithm
In real-world machine learning applications, it is common to have many relevant features, but only a subset of them may be observable. When dealing with variables that are sometimes observable and sometimes not, it is indeed possible to utilize the instances when that variable is visible or observed
8 min read
Hierarchical Clustering in Machine Learning
In data mining and statistics, hierarchical clustering analysis is a method of clustering analysis that seeks to build a hierarchy of clusters i.e. tree-type structure based on the hierarchy. In machine learning, clustering is the unsupervised learning technique that groups the data based on similar
7 min read
Implementing Agglomerative Clustering using Sklearn
Prerequisites: Agglomerative Clustering Agglomerative Clustering is one of the most common hierarchical clustering techniques. Dataset - Credit Card Dataset. Assumption: The clustering technique assumes that each data point is similar enough to the other data points that the data at the starting can
3 min read
Difference Between Agglomerative clustering and Divisive clustering
Hierarchical clustering is a popular unsupervised machine learning technique used to group similar data points into clusters based on their similarity or dissimilarity. It is called "hierarchical" because it creates a tree-like hierarchy of clusters, where each node represents a cluster that can be
5 min read
Affinity Propagation in ML | To find the number of clusters
Affinity Propagation creates clusters by sending messages between data points until convergence. Unlike clustering algorithms such as k-means or k-medoids, affinity propagation does not require the number of clusters to be determined or estimated before running the algorithm, for this purpose the tw
3 min read
DBSCAN Clustering in ML | Density based clustering
Clustering analysis or simply Clustering is basically an Unsupervised learning method that divides the data points into a number of specific batches or groups, such that the data points in the same groups have similar properties and data points in different groups have different properties in some s
7 min read
ML | OPTICS Clustering Explanation
Prerequisites: DBSCAN Clustering OPTICS Clustering stands for Ordering Points To Identify Cluster Structure. It draws inspiration from the DBSCAN clustering algorithm. It adds two more terms to the concepts of DBSCAN clustering. OPTICS (Ordering Points To Identify the Clustering Structure) is a dens
7 min read
Dimensionality Reduction Technique
Principal Component Analysis(PCA)
As the number of features or dimensions in a dataset increases, the amount of data required to obtain a statistically significant result increases exponentially. This can lead to issues such as overfitting, increased computation time, and reduced accuracy of machine learning models this is known as
14 min read
ML | T-distributed Stochastic Neighbor Embedding (t-SNE) Algorithm
T-distributed Stochastic Neighbor Embedding (t-SNE) is a nonlinear dimensionality reduction technique well-suited for embedding high-dimensional data for visualization in a low-dimensional space of two or three dimensions. What is Dimensionality Reduction? Dimensionality Reduction represents n-dimen
5 min read
Non-Negative Matrix Factorization
Prerequisite : Low Rank Approximation Non-Negative Matrix Factorization: Nonnegative Matrix Factorization is a matrix factorization method where we constrain the matrices to be nonnegative. In order to understand NMF, we should clarify the underlying intuition between matrix factorization. For a mat
3 min read
ML | Independent Component Analysis
Independent Component Analysis is a technique used to separate mixed signals into their independent sources. The application of ICA ranges from audio and image processing to biomedical signal analysis. The article discusses about the fundamentals of ICA. What is Independent Component Analysis? Indep
7 min read
Factor Analysis | Data Analysis
Factor analysis is a statistical method used to analyze the relationships among a set of observed variables by explaining the correlations or covariances between them in terms of a smaller number of unobserved variables called factors. Table of Content What is Factor Analysis?What does Factor mean i
13 min read
Latent Dirichlet Allocation
Topic Modeling: Topic modeling is a way of abstract modeling to discover the abstract 'topics' that occur in the collections of documents. The idea is that we will perform unsupervised classification on different documents, which find some natural groups in topics. We can answer the following questi
8 min read
Swiss Roll Reduction with LLE in Scikit Learn
This article discusses the concept of dimensionality reduction, specifically using the Swiss Roll dataset and the Locally Linear Embedding (LLE) algorithm. The article discusses the process involved in performing Swiss Roll reduction with LLE, including the steps of loading and preprocessing the dat
9 min read
Latent Semantic Analysis
Latent Semantic Analysis is a natural language processing method that uses the statistical approach to identify the association among the words in a document. LSA deals with the following kind of issue: Example: mobile, phone, cell phone, telephone are all similar but if we pose a query like “The
2 min read
Asynchronous Advantage Actor Critic (A3C) algorithm
The Asynchronous Advantage Actor Critic (A3C) algorithm is one of the newest algorithms to be developed under the field of Deep Reinforcement Learning Algorithms. This algorithm was developed by Google's DeepMind which is the Artificial Intelligence division of Google. This algorithm was first menti
3 min read