TEC-DATA85-08 · Lesson 5 · 12 clock hours · theory
Model Evaluation: Metrics, Cross-Validation, and ROC-AUC
Objective. Students will select appropriate evaluation metrics for classification and regression problems, implement k-fold cross-validation, and construct and interpret ROC curves.
⚠ Pending professional review
This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.
VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.
Why Evaluation Metrics Matter
Building a model is only half the job. Before you trust any model with a real business decision, you need to measure how well it performs—and you need to pick the right yardstick. A metric that suits one problem can be deeply misleading in another. This lesson covers the main metrics for classification and regression, explains cross-validation, and walks through ROC-AUC curves so you can interpret and communicate model performance with confidence.
Classification Metrics
Accuracy is the fraction of predictions the model gets right. It is easy to understand, but it breaks down with imbalanced classes. If only 2% of credit-card transactions are fraudulent, a model that predicts "not fraud" every single time scores 98% accuracy while catching zero fraud cases. That makes accuracy useless here.
Precision answers: of everything the model labeled positive, how many actually were positive? High precision matters when false positives are costly—for example, flagging a legitimate customer as a fraudster and blocking their card.
Recall (Sensitivity) answers: of all the real positives, how many did the model catch? High recall matters when false negatives are costly—for example, missing a cancerous tumor in a screening test.
F1 Score is the harmonic mean of precision and recall. It balances both concerns and is a good single-number summary when classes are imbalanced and both types of error matter.
ROC-AUC (Receiver Operating Characteristic – Area Under the Curve) measures a classifier's ability to distinguish between classes across all possible decision thresholds. The ROC curve plots the True Positive Rate (recall) on the y-axis against the False Positive Rate on the x-axis. A perfect classifier has an AUC of 1.0; random guessing produces an AUC of 0.5. AUC is threshold-independent, making it excellent for comparing models when the operating threshold has not yet been fixed. For severely imbalanced data, Precision-Recall AUC is often preferred over ROC-AUC because ROC can look optimistically high even when positive-class performance is poor.
Regression Metrics
RMSE (Root Mean Squared Error) penalizes large errors heavily because errors are squared before averaging. Use RMSE when large prediction errors are especially harmful—for example, forecasting electricity demand where a big miss could cause an outage.
MAE (Mean Absolute Error) treats all errors equally regardless of size. It is more interpretable and more robust to outliers than RMSE. Use MAE when you want a straightforward average error in the original units of the target variable.
For ordinal targets (categories with a meaningful order but unequal spacing, like a satisfaction rating of 1–5), standard regression metrics may not apply cleanly. Consider ordinal-specific approaches or treat the problem as classification with an ordinal loss if your framework supports it.
The Danger of Evaluating on Training Data
If you measure model performance on the same data used to train it, you get an overly optimistic picture. The model has already "seen" those examples and may have memorized patterns that do not generalize. The solution is cross-validation.
K-Fold Cross-Validation
In k-fold cross-validation the dataset is split into k equal-sized folds. The model trains on k−1 folds and is evaluated on the remaining fold. This process repeats k times, each fold serving as the validation set exactly once. You then average the k scores to get a reliable performance estimate and report the standard deviation to understand variability.
Stratified k-fold preserves the proportion of each class in every fold. Always use stratified k-fold for classification tasks—especially with imbalanced classes—so that rare positive examples appear in every fold rather than clustering in just a few.
In scikit-learn, `cross_val_score` combined with `StratifiedKFold` handles this automatically. A typical call looks like:
```python
from sklearn.model_selection import StratifiedKFold, cross_val_score
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(model, X, y, cv=cv, scoring='roc_auc')
print(f"AUC: {scores.mean():.3f} ± {scores.std():.3f}")
```
Constructing and Reading an ROC Curve
The ROC curve is generated by varying the classification threshold from 0 to 1 and plotting (FPR, TPR) at each threshold. In scikit-learn, `RocCurveDisplay.from_estimator` does this in one call. Key things to look for:
- The diagonal line represents a random classifier (AUC = 0.5). Any useful model should be well above it.
- The operating point is the specific threshold your team selects based on business needs. Mark it clearly on the curve and document the business rationale (e.g., "We accept a 15% FPR to catch at least 85% of fraudulent transactions").
- AUC comparison lets you rank multiple models without fixing a threshold first.
Selecting the Right Metric: A Decision Guide
| Scenario | Recommended Metric |
|---|---|
| Balanced classes, simple reporting | Accuracy |
| Imbalanced classes | F1, Precision-Recall AUC |
| High false-negative cost (e.g., disease screening) | Recall |
| High false-positive cost (e.g., spam filter) | Precision |
| Comparing classifiers before fixing a threshold | ROC-AUC |
| Continuous target, penalize large errors | RMSE |
| Continuous target, robust to outliers | MAE |
Accuracy and Data Integrity
Metrics are only trustworthy when your data pipeline is clean. Data leakage—where information from the test set accidentally enters training—will inflate scores and produce models that fail in production. Always fit preprocessing steps (scalers, encoders) inside the cross-validation loop, never on the full dataset before splitting. scikit-learn `Pipeline` objects make this straightforward and help prevent this class of error.
Key terms10
PrecisionThe proportion of positive predictions that are actually correct; minimizes false positives.
Recall (Sensitivity)The proportion of actual positives that the model correctly identifies; minimizes false negatives.
F1 ScoreThe harmonic mean of precision and recall; useful when both false positives and false negatives carry significant cost.
ROC-AUCArea under the Receiver Operating Characteristic curve; measures a classifier's ability to rank positives above negatives across all thresholds, with 1.0 being perfect and 0.5 being random.
RMSE (Root Mean Squared Error)Square root of the average squared prediction errors for a regression model; penalizes large errors more than small ones.
MAE (Mean Absolute Error)Average of the absolute differences between predicted and actual values; more robust to outliers than RMSE.
K-Fold Cross-ValidationA resampling procedure that splits data into k folds, trains and evaluates the model k times, and averages the results to estimate generalization performance.
Stratified K-FoldA variant of k-fold cross-validation that ensures each fold contains roughly the same proportion of each class label as the full dataset.
Operating PointThe specific classification threshold chosen based on business requirements, representing a deliberate trade-off between true positive rate and false positive rate on the ROC curve.
Data LeakageThe accidental inclusion of information from outside the training set during model development, causing inflated evaluation scores that do not reflect real-world performance.
Worked examples4
1. A model predicts fraud on 200 test transactions. It predicts 'fraud' for 40 transactions. Of those 40, 30 are actually fraudulent. There are 50 total fraudulent transactions in the test set. Calculate precision, recall, and F1 score.
- Identify the counts: True Positives (TP) = 30 (predicted fraud, actually fraud). False Positives (FP) = 40 − 30 = 10 (predicted fraud, actually not fraud). False Negatives (FN) = 50 − 30 = 20 (actual fraud the model missed).
- Calculate Precision = TP / (TP + FP) = 30 / (30 + 10) = 30 / 40 = 0.75.
- Calculate Recall = TP / (TP + FN) = 30 / (30 + 20) = 30 / 50 = 0.60.
- Calculate F1 = 2 × (Precision × Recall) / (Precision + Recall) = 2 × (0.75 × 0.60) / (0.75 + 0.60) = 2 × 0.45 / 1.35 = 0.90 / 1.35 ≈ 0.667.
Answer: Precision = 0.75, Recall = 0.60, F1 ≈ 0.667. The relatively low recall means the model is missing 40% of actual fraud cases, which is a serious concern in a fraud-detection context where false negatives are costly.
2. A 5-fold cross-validation run returns AUC scores of 0.82, 0.79, 0.85, 0.81, and 0.83. Compute the mean and standard deviation to report model performance.
- List the five scores: 0.82, 0.79, 0.85, 0.81, 0.83.
- Calculate the mean: (0.82 + 0.79 + 0.85 + 0.81 + 0.83) / 5 = 4.10 / 5 = 0.82.
- Calculate the variance: find each squared deviation from the mean. (0.82−0.82)²=0.0000, (0.79−0.82)²=0.0009, (0.85−0.82)²=0.0009, (0.81−0.82)²=0.0001, (0.83−0.82)²=0.0001. Sum = 0.0020. Variance = 0.0020 / 5 = 0.00040.
- Standard deviation = √0.00040 ≈ 0.020.
Answer: Report the model as AUC = 0.820 ± 0.020. The low standard deviation indicates the model's performance is consistent across folds.
3. A regression model predicts house prices (in thousands of dollars). Actual values and predictions for five houses are: Actual [200, 250, 300, 180, 220], Predicted [210, 240, 310, 170, 230]. Calculate MAE and RMSE.
- Calculate absolute errors for each house: |200−210|=10, |250−240|=10, |300−310|=10, |180−170|=10, |220−230|=10.
- MAE = (10 + 10 + 10 + 10 + 10) / 5 = 50 / 5 = 10. The average prediction error is $10,000.
- Calculate squared errors: 10²=100, 10²=100, 10²=100, 10²=100, 10²=100. Mean Squared Error (MSE) = (100+100+100+100+100) / 5 = 500 / 5 = 100.
- RMSE = √100 = 10. In this example all errors are equal, so MAE and RMSE are identical at 10 ($10,000).
Answer: MAE = 10 ($10,000) and RMSE = 10 ($10,000). When all errors are equal in magnitude, the two metrics agree. RMSE would diverge and be larger than MAE if even one error were much bigger than the others.
4. A dataset has 950 'not fraud' and 50 'fraud' records (1,000 total). A naive model predicts 'not fraud' for every record. What is its accuracy? Why is accuracy misleading here, and which metric should be used instead?
- Count correct predictions: the model labels all 1,000 records as 'not fraud'. It is correct for all 950 'not fraud' records and wrong for all 50 'fraud' records. Correct = 950.
- Accuracy = 950 / 1000 = 0.95, or 95%.
- Evaluate recall for the fraud class: TP = 0 (no fraud was detected), FN = 50. Recall = 0 / (0 + 50) = 0.00. The model catches zero fraudulent transactions despite its high accuracy.
- Conclude: accuracy is misleading because the class imbalance (95:5 ratio) allows a useless model to score very high. F1 score or Precision-Recall AUC should be used instead, as they account for the model's performance on the minority (fraud) class.
Answer: Accuracy = 95%, which looks excellent but is entirely misleading. Recall for fraud = 0% and F1 for fraud = 0. The correct choice is F1 score or Precision-Recall AUC for this imbalanced fraud-detection problem.
The math in this lesson2
Learners express precision, recall and F1 as ratios and percents.
7.RP.3S-CP.4
In class: Lecture and guided problem set: students work through four scenario cards (imbalanced classes, high false-negative cost, continuous target, ordinal target) and justify which metric to use in each case, citing precision, recall, F1, ROC-AUC, RMSE, or MAE. · Coding lab: use cross_val_score and StratifiedKFold on the Titanic logistic regression from Lesson 3; plot the ROC curve using RocCurveDisplay, compute AUC, and annotate the plot with the operating point selected and the business rationale. · Group debate (10 minutes): two teams argue whether accuracy or ROC-AUC is more useful for a fraud-detection model; instructor summarizes consensus and students update their concept maps.
Materials: Jupyter Lab, scikit-learn metrics module documentation, scenario cards (instructor-prepared), Géron ch. 3
Check: Individual scenario card quiz (4 questions, open-note): student must correctly match metric to scenario with written justification for all 4; plus cross-validation notebook cell must produce a mean ± std score without errors.
Practice check8
Answer each question, then check it. Nothing is recorded; this is your own practice.
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.