The ROC curve helps us see how well a model can tell apart two groups, like sick vs healthy. AUC gives a simple number to show this ability.
ROC curve and AUC in ML Python
from sklearn.metrics import roc_curve, auc fpr, tpr, thresholds = roc_curve(true_labels, predicted_scores) roc_auc = auc(fpr, tpr)
true_labels are the actual class labels (0 or 1).
predicted_scores are the model's predicted probabilities or scores for the positive class.
fpr, tpr, thresholds = roc_curve([0, 0, 1, 1], [0.1, 0.4, 0.35, 0.8]) roc_auc = auc(fpr, tpr)
import matplotlib.pyplot as plt plt.plot(fpr, tpr, label=f'AUC = {roc_auc:.2f}') plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('ROC Curve') plt.legend() plt.show()
This program trains a simple model, calculates the ROC curve and AUC, then prints the false positive rates, true positive rates, and AUC value.
from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import roc_curve, auc import numpy as np # Create a simple binary classification dataset X, y = make_classification(n_samples=100, n_features=5, random_state=42) # Split into train and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) # Train a logistic regression model model = LogisticRegression() model.fit(X_train, y_train) # Get predicted probabilities for the positive class y_scores = model.predict_proba(X_test)[:, 1] # Calculate ROC curve fpr, tpr, thresholds = roc_curve(y_test, y_scores) # Calculate AUC roc_auc = auc(fpr, tpr) print(f"False Positive Rates: {np.round(fpr, 2)}") print(f"True Positive Rates: {np.round(tpr, 2)}") print(f"AUC: {roc_auc:.3f}")
The ROC curve plots the true positive rate against the false positive rate at different thresholds.
AUC ranges from 0 to 1; closer to 1 means better model performance.
ROC and AUC work well even if classes are imbalanced.
ROC curve shows how well a model separates classes at different thresholds.
AUC summarizes the ROC curve into one number to compare models easily.
Use ROC and AUC to evaluate and improve classification models.
Practice
Solution
Step 1: Understand ROC curve components
The ROC curve plots the true positive rate (sensitivity) against the false positive rate (1 - specificity) at various threshold settings.Step 2: Identify what ROC shows
This curve shows how well the model can distinguish between classes by varying the decision threshold.Final Answer:
The trade-off between true positive rate and false positive rate at different thresholds -> Option AQuick Check:
ROC curve = True Positive Rate vs False Positive Rate [OK]
- Confusing ROC with accuracy
- Thinking ROC shows loss values
- Assuming ROC shows only one threshold
Solution
Step 1: Recall correct import syntax
In Python, functions are imported using 'from module import function' syntax.Step 2: Identify correct function name
The correct function name to compute AUC is 'roc_auc_score' from 'sklearn.metrics'.Final Answer:
from sklearn.metrics import roc_auc_score -> Option CQuick Check:
Correct import syntax = from sklearn.metrics import roc_auc_score [OK]
- Using wrong import syntax
- Misspelling function name
- Trying to import module as function
from sklearn.metrics import roc_auc_score true_labels = [0, 0, 1, 1] predicted_scores = [0.1, 0.4, 0.35, 0.8] auc = roc_auc_score(true_labels, predicted_scores) print(round(auc, 2))
Solution
Step 1: Understand roc_auc_score calculation
The AUC measures how well the predicted scores rank positive samples higher than negative ones.Step 2: Calculate AUC for given data
Using the pairs, the AUC is 0.75 as the positive samples are ranked correctly most of the time but not perfectly.Final Answer:
0.75 -> Option AQuick Check:
AUC for given scores = 0.75 [OK]
- Confusing AUC with accuracy
- Rounding incorrectly
- Mixing up true labels and scores
from sklearn.metrics import roc_curve fpr, tpr, thresholds = roc_curve(y_true, y_pred) plt.plot(fpr, tpr) plt.show()
Solution
Step 1: Check input requirements for roc_curve
The roc_curve function requires true labels and predicted scores or probabilities, not class labels.Step 2: Identify the error in inputs
Using predicted class labels instead of probabilities causes incorrect ROC curve calculation.Final Answer:
y_pred should be predicted probabilities, not class labels -> Option BQuick Check:
Use probabilities for roc_curve inputs [OK]
- Passing class labels instead of probabilities
- Forgetting to import matplotlib.pyplot as plt
- Plotting thresholds instead of FPR and TPR
Solution
Step 1: Understand what affects AUC
AUC measures the model's ranking ability and is threshold-independent.Step 2: Choose the best method to improve AUC
Tuning the classification threshold does not improve AUC because AUC is threshold-independent; instead, improving the model's discriminative ability or training is needed.Step 3: Evaluate options
Increasing training epochs (Increase the number of training epochs without changing data or model) can help but may cause overfitting if not managed properly. Reducing dataset size (Reduce the size of the training dataset to avoid overfitting) usually harms performance. Using accuracy (Use accuracy as the main metric instead of AUC) does not improve AUC. Tuning threshold (Tune the classification threshold to balance true positive and false positive rates) affects operating point but not AUC.Final Answer:
Increase the number of training epochs without changing data or model -> Option DQuick Check:
More epochs can improve model performance and AUC [OK]
- Thinking threshold tuning affects AUC
- Reducing data size harms performance
- Switching to accuracy doesn't improve AUC
Ready to prove it?
Pass the test and this pattern moves unknown
