Evaluating & Shipping Models · Lesson 5 of 6
Model Evaluation Metrics: Confusion Matrix, Precision, Recall, F1 and Cross-Validation
Accuracy alone can make a useless model look excellent. Learn the confusion matrix, precision, recall, F1, ROC-AUC, regression metrics and cross-validation — and how to pick the metric that matches the real cost of mistakes.
A model that screens chest X-rays reports 95% accuracy. Impressive? If only 5% of patients actually have the disease, a model that says "healthy" for everyone also scores 95% — while missing every sick patient. Choosing the right metric is not a technical detail; it decides whether a model helps or harms.
The confusion matrix
For a yes/no classifier, every prediction lands in one of four boxes. Take a model that flags fraudulent transactions:
| Predicted: fraud | Predicted: genuine | |
|---|---|---|
| Actually fraud | True Positive (TP) — caught it | False Negative (FN) — missed fraud |
| Actually genuine | False Positive (FP) — blocked a real customer | True Negative (TN) — correctly let through |
Every classification metric is built from these four numbers.
Precision and recall
- Precision = TP / (TP + FP) — of everything we flagged, how much was really fraud? Low precision means many annoyed genuine customers.
- Recall = TP / (TP + FN) — of all real fraud, how much did we catch? Low recall means fraud slips through.
They pull against each other. Lower the threshold and you catch more fraud (recall up) but block more genuine customers (precision down).
| Situation | Costlier mistake | Prioritise |
|---|---|---|
| Cancer screening | Missing a sick patient (FN) | Recall |
| Spam filter | Hiding an important email (FP) | Precision |
| Fraud detection | Both cost money | Balance — F1 or a cost-based threshold |
F1 score is the harmonic mean of precision and recall — high only when both are reasonably high.
Probabilities: ROC-AUC and PR-AUC
Most classifiers output a probability. Instead of judging one threshold, you can measure ranking quality across all thresholds:
- ROC-AUC — the chance that a random positive example gets a higher score than a random negative one. 0.5 is guessing, 1.0 is perfect.
- PR-AUC (average precision) — more informative when positives are rare, like fraud.
Regression metrics recap
- MAE — average absolute error, in real units ("₹38,000 off on average").
- RMSE — penalises large misses; use when big errors are especially bad.
- R² — share of variance explained; useful for comparing models on the same data.
- MAPE — average percentage error; easy to explain, but breaks when actual values are near zero.
Cross-validation: a fairer estimate
One train/test split can be lucky or unlucky. K-fold cross-validation splits the training data into k parts (often 5), trains on k−1 and validates on the remaining one, rotating until every part has been the validation set once. You get k scores — their average is more reliable, and their spread shows how stable the model is.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, cross_val_score, StratifiedKFold
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import confusion_matrix, classification_report, roc_auc_score
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
model = RandomForestClassifier(n_estimators=300, random_state=42)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(model, X_train, y_train, cv=cv, scoring="f1")
print("CV F1: %.3f ± %.3f" % (scores.mean(), scores.std()))
model.fit(X_train, y_train) # final check on the untouched test set
pred = model.predict(X_test)
proba = model.predict_proba(X_test)[:, 1]
print(confusion_matrix(y_test, pred))
print(classification_report(y_test, pred, digits=3))
print("ROC-AUC:", round(roc_auc_score(y_test, proba), 3))
The clean process: split off a test set → compare and tune models with cross-validation on the training set → retrain the chosen model on all training data → report the test score once. That final number is the one you can honestly quote.
Choosing the threshold
The default 0.5 threshold is rarely the best business choice. If missing fraud costs ₹10,000 and blocking a genuine payment costs ₹200 in support time and goodwill, pick the threshold that minimises total cost on validation data. This is how ML connects to real decisions.
Do not stop at the metric. Also check errors by group (city, age band, device type). A model with a good overall score can still fail badly for one group of users — a fairness and quality problem worth catching before launch.
Try it yourself: Using proba from the code, compute precision and recall at thresholds 0.3, 0.5 and 0.7 (pred = proba >= t). Write one sentence for a doctor explaining which threshold you would choose for a screening test and why.
Common interview questions
Try answering each one aloud before you open it.
1Explain precision and recall with an example.
In fraud detection, precision is the share of flagged transactions that are truly fraud, and recall is the share of all fraud that was flagged. High precision means few false alarms; high recall means little fraud is missed.
2Why is accuracy misleading for imbalanced data?
When one class dominates, predicting the majority class for every example gives high accuracy while completely failing on the minority class, which is usually the important one.
3What is k-fold cross-validation?
The training data is split into k folds; the model is trained k times, each time validated on a different fold and trained on the rest. Averaging the k scores gives a more reliable and stable estimate than a single split.
Practise this
Build something with it
FAQs
What is a good F1 score?
It depends on the problem and the baseline. Compare against a simple baseline and against the business requirement rather than a universal number.
Should I report cross-validation or test-set results?
Use cross-validation to choose and tune models, and report the final test-set result as your estimate of real-world performance — ideally alongside the CV mean and spread.
References & further reading
Finished this lesson?
Mark it complete. Create a free account to save it on every device.