Skip to main content
LearnMLAcademy
Intermediate10 min read

ROC-AUC

Evaluate binary classifiers across all decision thresholds with ROC curves, with Python code, architecture diagrams, worked examples, and interview quiz.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

ROC-AUC in Machine Learning

A classifier often produces a score for each example: for instance, a fraud probability of 0.82 or a decision score from an SVM. A threshold then turns that score into a final class such as Fraud / Not Fraud.

ROC-AUC in Simple Words

Step 1
Model gives scores
Step 2
Change threshold
Step 3
Track TPR and FPR
Step 4
Summarize with AUC

Why accuracy alone can be misleading

Suppose 990 of 1,000 transactions are normal and only 10 are fraud. A model that predicts “normal” every time gets 99% accuracy but detects none of the fraud cases. ROC-AUC is one useful way to study ranking performance across many thresholds instead of judging the model at only one threshold.


What Is the ROC Curve?

ROC stands for Receiver Operating Characteristic. For binary classification, the ROC curve plots the True Positive Rate (TPR) against the False Positive Rate (FPR) as the decision threshold changes.

Important: use continuous prediction scores

ROC analysis works best with continuous scores such as predict_proba(... )[:, 1] or a model's decision_function(). Hard class predictions like only 0 and 1 contain very little threshold information and usually produce only a small number of operating points.

A tiny score example

SampleActual ClassModel Score
APositive0.95
BPositive0.85
CNegative0.70
DPositive0.60
ENegative0.40
FNegative0.20

Why changing the threshold matters

Threshold = 0.85

Predicted positive: A, B

TP = 2, FP = 0, FN = 1, TN = 3

TPR = 2/3 = 0.667

FPR = 0/3 = 0.000

Threshold = 0.55

Predicted positive: A, B, C, D

TP = 3, FP = 1, FN = 0, TN = 2

TPR = 3/3 = 1.000

FPR = 1/3 = 0.333

Lowering the threshold caught the remaining positive example, but it also created a false alarm. The ROC curve records this trade-off over many thresholds.


Understanding the ROC Axes

X-Axis: False Positive Rate

FPR = FP / (FP + TN)

If 10 of 100 actual negatives are incorrectly flagged positive, FPR = 10/100 = 0.10.

Y-Axis: True Positive Rate

TPR = TP / (TP + FN)

TPR is also Recall or Sensitivity. If 90 of 100 actual positives are detected, TPR = 90/100 = 0.90.

One simple ROC picture

Ideal: FPR 0, TPR 1Random-ranking diagonalExample ROC curveFalse Positive Rate (FPR)True Positive Rate (TPR)011

Curves that reach toward the top-left generally indicate stronger ranking performance: high TPR can be achieved while keeping FPR relatively low. The diagonal represents random ranking in the usual binary ROC interpretation.


What Is AUC?

AUC means Area Under the ROC Curve. It compresses the ROC curve into one number that summarizes how well the model's scores rank positive examples above negative examples across thresholds.

Useful reference points

AUC = 1.0Perfect ranking on the evaluated data
AUC = 0.5Random-ranking baseline
AUC < 0.5Ranking is worse than that baseline; investigate labels/scores/model

Do not memorize universal labels

Rules such as “0.8 is always good” or “0.9 is always excellent” are not universal. Whether an AUC is useful depends on the task, data quality, costs of errors, baseline models, and deployment requirements.

Ranking interpretation

An AUC of 0.92 can be interpreted as the model having about a 92% chance of assigning a higher score to a randomly selected positive example than to a randomly selected negative example, under the usual ranking interpretation.


How ROC Points Are Created

Start with the score table from earlier. At each threshold, convert scores into positive/negative predictions, count TP/FP/FN/TN, and calculate TPR and FPR.

At threshold 0.85

TP = 2, FP = 0, FN = 1, TN = 3

TPR = 2 / (2 + 1) = 0.667

FPR = 0 / (0 + 3) = 0.000

ROC point = (0.000, 0.667)

Repeating this process across score thresholds creates the sequence of ROC points. AUC summarizes the resulting curve.


Comparing Models with ROC-AUC

ROC-AUC is useful when you care about how well models rank positives above negatives across many possible thresholds. It can reveal differences that a single fixed-threshold accuracy score hides.

Model A

AUC = 0.91

Model B

AUC = 0.86

But ask one more question

Which model is better in the FPR/TPR region your application actually uses?

AUC is not the entire decision

Two ROC curves can cross. A model with a larger overall AUC may still be worse in a narrow operating region that matters to your application. Always inspect the curve and connect evaluation to real false-positive and false-negative costs.


ROC-AUC Does Not Choose Your Final Threshold

ROC-AUC evaluates ranking across thresholds. Deployment still needs a particular decision threshold, and that threshold should reflect the real problem.

Cost of False Positives

Cost of False Negatives

Operational Capacity

For example, if investigators can review only a limited number of alerts each day, a threshold that produces an impractical number of false alarms may be unusable even when the overall ROC-AUC is strong.


Python Implementation

This example uses a leakage-safe Pipeline, an explicit stratified train/test split, continuous positive-class probabilities, and Scikit-learn's ROC utilities.

ROC Curve & AUC Score

Python
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_curve, roc_auc_score, RocCurveDisplay

# 1. Load educational binary-classification data
X, y = load_breast_cancer(return_X_y=True)

# 2. Keep a final test set
X_train, X_test, y_train, y_test = train_test_split(
    X, y,
    test_size=0.30,
    random_state=42,
    stratify=y
)

# 3. Scale using training data inside the Pipeline, then fit
model = make_pipeline(
    StandardScaler(),
    LogisticRegression(max_iter=2000)
)
model.fit(X_train, y_train)

# 4. Use continuous scores for the positive class
#    (decision_function scores can also be used by many estimators)
y_score = model.predict_proba(X_test)[:, 1]

# 5. Compute ROC points and ROC-AUC
fpr, tpr, thresholds = roc_curve(y_test, y_score)
auc_score = roc_auc_score(y_test, y_score)

print(f"AUC Score: {auc_score:.3f}")
print(f"ROC points: {len(fpr)}")

# 6. Plot from the same predictions
RocCurveDisplay.from_predictions(y_test, y_score)
plt.plot([0, 1], [0, 1], "--", label="Random ranking")
plt.legend()
plt.show()

Expected output for this fixed split:

AUC Score: 0.998
ROC points: 6

Why only 6 plotted ROC points?

Scikit-learn's roc_curve uses drop_intermediate=True by default, so thresholds whose ROC points are collinear with neighboring points can be omitted. This reduces plotting points without changing the ROC-AUC or the visual shape of the curve.

Educational dataset note

A high score on this built-in dataset is only a demonstration of the metric. It does not imply that a model is ready for medical or other high-stakes deployment.


ROC Curve vs Precision-Recall Curve

ROC and Precision-Recall curves answer related but different questions. When the positive class is very rare, a Precision-Recall curve can often be especially informative because precision directly reflects how many predicted positives are actually positive.

CurveAxesUseful focus
ROCTPR vs FPRRanking trade-off across positives and negatives
Precision-RecallPrecision vs RecallPositive-class retrieval quality, often informative for rare positives

Do not choose only from a slogan

“Balanced data = ROC” and “imbalanced data = PR” are useful beginner shortcuts but not universal rules. Look at the decision problem, class prevalence, operating region, and costs of mistakes.


What About Multiclass Problems?

The basic ROC curve is easiest to understand for binary classification. ROC-AUC can also be extended to multiclass and multilabel problems using strategies such as one-vs-rest or one-vs-one and then combining class-level scores with averaging choices.

For a first lesson, master the binary case first. The key idea remains the same: evaluate ranking scores rather than relying only on one hard threshold.


Common Mistakes

Using only hard 0/1 predictions and expecting a meaningful multi-threshold ROC curve.
Treating AUC = 0.9 as universally “excellent” without considering the application.
Assuming a higher overall AUC means a model is better at every possible operating threshold.
Choosing a deployment threshold from ROC-AUC alone without considering FP/FN costs.
Ignoring Precision-Recall analysis when rare positive cases are especially important.
Calculating ROC-AUC on training data and reporting it as evidence of unseen-data performance.

Quick Recap

What does the ROC curve plot?

True Positive Rate against False Positive Rate across changing score thresholds.

Does ROC-AUC tell us the best production threshold?

No. It summarizes ranking across thresholds; the final threshold depends on the application's trade-offs and constraints.

Should ROC be computed from hard predictions?

Use continuous model scores whenever possible. Hard labels discard most threshold-ranking information.

Most Important Insight

ROC-AUC is mainly about ranking quality across thresholds. Use continuous scores, inspect the actual curve, and choose the final decision threshold using the real cost of mistakes—not AUC alone.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "ROC-AUC"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Summary / Key Takeaways

  • ROC plots true-positive rate against false-positive rate across thresholds.
  • ROC-AUC measures ranking, not one deployed threshold.
  • AUC does not measure probability calibration.
  • Precision-recall can be more informative for rare positives.
  • Choose thresholds from false-positive and false-negative costs.
  • Inspect uncertainty and subgroup curves, not only aggregate AUC.

Knowledge Check

Progress: 0/4

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 4
What happens as you move the classification threshold from 1.0 to 0.0, and how does this create the ROC curve?
Question 2 of 4
Model A AUC=0.91, Model B AUC=0.89. What additional analysis is needed before concluding A is better?
Question 3 of 4
A credit scoring model achieves AUC=0.94 on a dataset with 2% default rate. What should you additionally check?
Question 4 of 4
What does AUC=0.5 mean and how do you verify this is not a bug?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1What happens as you move the classification threshold from 1.0 to 0.0, and how does this create the ROC curve?▼

Correct Answer: At threshold=1.0: nobody predicted positive → TPR=0, FPR=0. As threshold decreases: more examples predicted positive. True positives are captured (TPR increases — up y-axis). Some negatives are also incorrectly captured (FPR increases — right along x-axis). A perfect model captures all positives before any negatives. A random model captures both at equal rates (diagonal line). AUC summarises the model's ability to rank positives above negatives across all thresholds

Understanding the ROC curve as a threshold sweep is crucial. The curve encodes the model's ranking ability. AUC=0.9 means: if you pick a random positive and random negative, the model ranks the positive higher 90% of the time.

2Model A AUC=0.91, Model B AUC=0.89. What additional analysis is needed before concluding A is better?▼

Correct Answer: Bootstrap confidence intervals on both AUC estimates. With 500 test examples, the 95% CI for AUC is approximately ±0.04. If CIs overlap substantially, the difference is not statistically significant. Also consider: whether AUC is the right metric for this application, computational cost, and performance at the specific threshold you will use in production

The difference of 0.02 in AUC is meaningful only if it exceeds estimation uncertainty. With small test sets, this difference is not statistically significant and might reverse on a different test sample.

3A credit scoring model achieves AUC=0.94 on a dataset with 2% default rate. What should you additionally check?▼

Correct Answer: Also check: (1) PR-AUC, more informative for the 2% positive class. (2) Model calibration — does p=0.15 actually mean 15% of applicants with that score default? Poor calibration hurts loan pricing. (3) Performance at the specific operating threshold used in production. (4) Performance across demographic groups — high overall AUC can mask disparate sub-group performance

AUC is a ranking metric, not a calibration metric. For credit decisions, you need calibrated probabilities to make sound financial decisions. AUC=0.94 with poor calibration means you can rank applicants but cannot accurately price the risk.

4What does AUC=0.5 mean and how do you verify this is not a bug?▼

Correct Answer: AUC=0.5 means predictions are no better than random at ranking positives above negatives. Verification: (1) Check for label inversion — if AUC=0.5 with normal labels gives AUC=0.95 with inverted labels, your labels are reversed. (2) Check if predictions have zero variance (model always predicts the same value). (3) Verify feature-label correspondence was maintained during preprocessing

AUC=0.5 is the most suspicious result. The most common cause: accidentally inverted labels (0 and 1 swapped during encoding). Second: all predictions are identical (zero variance). Third: features and labels got misaligned during data processing.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next