Skip to main content

Model Evaluation

Confusion Matrix Visualization

The Hidden Trap

Your model has 99% accuracy. Incredible, right? Wait. The dataset has 99% of one class:
  • 99% emails are not spam
  • Model predicts “not spam” for everything
  • 99% accuracy… but catches zero spam!
Think of it like a weather forecaster in the Sahara who predicts “no rain” every single day. They’d be right 99% of the time — and completely useless the 1% of the time it actually matters. Accuracy is a vanity metric when your classes are imbalanced, and in the real world, they almost always are. This is why proper evaluation matters.
A/B Testing Model Comparison

The Train-Test Split

Rule #1: Never evaluate on training data! Evaluating on training data is like grading a student using the exact questions they practiced on. Of course they’ll ace it — but you have no idea if they actually understand the material. The test set is the “final exam” your model has never seen.
If training accuracy >> test accuracy: Your model is overfitting! It memorized the training data instead of learning patterns.Rules of thumb for the gap:
  • less than 5%: Normal and expected. Ship it.
  • 5-15%: Mild overfitting. Try regularization or simpler model.
  • greater than 15%: Serious overfitting. Reduce model complexity, get more data, or add dropout/regularization.
  • Test higher than train: Something is wrong — possible data leakage or a very lucky split. Investigate.

Cross-Validation: More Reliable Evaluation

What if the test split was “lucky”? Use k-fold cross-validation:
Every sample gets to be in the test set exactly once! The standard deviation of CV scores tells you how stable your model is. A model with 95% +/- 1% is much more trustworthy than one with 95% +/- 8%. High variance across folds often means your dataset is too small or your model is too sensitive to which specific examples it trains on.

Classification Metrics

The Confusion Matrix


Precision, Recall, F1

Precision

Of predicted positives, how many are correct?TPTP+FP\frac{TP}{TP + FP}“Don’t cry wolf”

Recall

Of actual positives, how many did we find?TPTP+FN\frac{TP}{TP + FN}“Find them all”

F1 Score

Harmonic mean of precision and recall2PRP+R\frac{2 \cdot P \cdot R}{P + R}“Balance both”

When to Use What?


Probability Thresholds

By default, we use 0.5 as the threshold. But you can adjust it:
Trade-off — think of it like adjusting the sensitivity on a metal detector at an airport:
  • Lower threshold (more sensitive): Catches more threats but also beeps at belt buckles. More positive predictions, higher recall, lower precision.
  • Higher threshold (less sensitive): Only triggers on real weapons but might miss a hidden knife. Fewer positive predictions, lower recall, higher precision.
The right threshold depends on what’s more expensive: false alarms or missed catches. In cancer screening, you want low threshold (catch everything). In email spam, you want higher threshold (don’t lose real mail).

ROC Curve and AUC

The ROC curve shows performance across all thresholds:
AUC (Area Under Curve) — the probability that a randomly chosen positive example is scored higher than a randomly chosen negative example:
  • 1.0 = Perfect model (always ranks positives above negatives)
  • 0.5 = Random guessing (coin flip)
  • > 0.9 = Excellent (production-ready for many applications)
  • > 0.8 = Good (worth deploying with monitoring)
  • > 0.7 = Fair (better than nothing, but investigate why it’s struggling)
  • < 0.5 = Your labels might be flipped, or the model is actively anti-predicting
Why AUC over accuracy? AUC doesn’t depend on a specific threshold, so it tells you about the model’s overall discriminative ability. Two models could have the same accuracy at threshold=0.5 but very different AUCs — the one with higher AUC has more “room to maneuver” when you adjust the threshold for business needs.

Regression Metrics

For predicting numbers:

RMSE

Average error in same units as target. More sensitive to large errors.

MAE

Average error in same units as target. More robust to outliers.

R2 Score

% of variance explained (0 to 1). 1 = perfect fit, 0 = baseline.

MAPE

Average % error. Easy to interpret.

Handling Imbalanced Data

When one class dominates (99% vs 1%):

1. Use Appropriate Metrics

2. Resample the Data

Think of it like a cooking class where 95 students want to learn Italian but only 5 want to learn Thai. If you just teach to the majority, you’ll ignore Thai completely. Resampling either duplicates the Thai students (upsampling) or randomly removes some Italian students (downsampling) to give both groups fair representation.

3. Use Class Weights

Model selection tip for imbalanced data: Start with class_weight='balanced' on Logistic Regression or Random Forest before trying resampling techniques. It’s simpler, doesn’t create synthetic data, and often works just as well. Reserve SMOTE and other resampling for when class weights alone aren’t enough.

Learning Curves: Diagnosing Problems

Diagnosing from learning curves — this is one of the most valuable debugging tools in ML:

Validation Curve: Tuning Hyperparameters


Complete Evaluation Pipeline


🚀 Mini Projects

Project 1: Metric Dashboard Builder

Build a comprehensive model evaluation dashboard

Project 2: Cross-Validation Analyzer

Compare different CV strategies and their stability

Project 3: Threshold Optimization

Find optimal decision thresholds for business needs

Project 4: Model Comparison Report

Create an automated model comparison report

Project 1: Metric Dashboard Builder

Build a comprehensive evaluation dashboard that calculates all metrics and visualizes model performance.

Project 2: Cross-Validation Analyzer

Compare different cross-validation strategies and analyze their stability.

Project 3: Threshold Optimization

Find the optimal classification threshold for different business objectives.

Project 4: Model Comparison Report

Create an automated report comparing multiple models across all metrics.

Key Takeaways

Never Evaluate on Training Data

Always use a held-out test set or cross-validation

Accuracy Is Not Enough

Use precision, recall, F1, AUC depending on the problem

Cross-Validation

More reliable than a single train-test split

Watch for Leakage

Test data must not influence training in any way

🧹 Real-World Complications: Messy Data Evaluation

Real-world data creates evaluation challenges. Here’s how to handle them:

Handling Class Imbalance in Evaluation

Evaluating with Missing Values

Evaluating on Time Series (No Random Split!)

Detecting Evaluation Errors


What’s Next?

Before training, you need to prepare your data. Feature engineering can make or break your model!

Continue to Module 8: Feature Engineering

Learn how to transform raw data into powerful features