Tensorflow Precision / Recall / F1 score and Confusion matrix
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
Accuracy alone can hide major model failures, especially in imbalanced classification problems. Precision, recall, F1 score, and confusion matrix provide a richer view of model behavior:
- precision answers "when we predict positive, how often are we correct?"
- recall answers "how many actual positives did we capture?"
- F1 balances precision and recall,
- confusion matrix shows full error distribution.
In TensorFlow workflows, these metrics are often computed with a mix of built-in Keras metrics and post-training analysis tools like scikit-learn.
Core Sections
1. Train with precision and recall metrics in Keras
These metrics are threshold-based (default 0.5). If your business threshold differs, set it explicitly.
2. Compute F1 and confusion matrix after prediction
Keras does not always expose F1 as built-in in every setup, so it is commonly computed post-hoc.
For multiclass tasks, set average="macro", "weighted", or "micro" according to evaluation goal.
3. Interpret metrics with business context
Example tradeoff:
- fraud detection may prioritize recall (catch more fraud),
- alerting systems may prioritize precision (fewer false alarms).
Tune threshold based on precision-recall curve:
Confusion matrix helps target error modes directly (false positives vs false negatives).
4. Add visualization for reporting
Visual reports improve communication with non-ML stakeholders and support threshold-decision reviews.
Common Pitfalls
- Relying on accuracy only in imbalanced datasets where minority-class performance matters most.
- Forgetting to set or document classification threshold used for precision/recall/F1.
- Comparing F1 scores across experiments with different averaging methods (
macrovsweighted). - Evaluating on preprocessed labels/probabilities inconsistently between training and reporting.
- Ignoring confusion matrix cell counts and focusing only on one summary metric.
Summary
Precision, recall, F1, and confusion matrix provide complementary insight beyond accuracy for TensorFlow classifiers. Use Keras metrics during training, compute additional post-hoc metrics and threshold analysis after prediction, and interpret results based on business tradeoffs. Metric discipline leads to better model decisions and safer production deployment.
For imbalanced datasets, evaluate metrics per class and across multiple thresholds rather than relying on one operating point. A model can have acceptable aggregate F1 while failing a critical minority class. Class-specific confusion matrices and per-class recall often reveal these blind spots. Incorporating such analysis into model review templates improves decision quality before deployment.
In production monitoring, track drift in confusion-matrix-derived rates over time using delayed ground truth labels. Sudden changes in false-positive or false-negative rates can indicate data drift, label delays, or upstream pipeline issues. Monitoring the same metrics in production that you used in validation creates a consistent quality loop from training through operations.
Teams should define metric acceptance criteria before training starts, so deployment decisions are not made on ad hoc interpretations after the fact. Predefined thresholds for precision/recall tradeoffs create clearer governance.
Where possible, evaluate confidence intervals or bootstrap variability for key metrics. A single point estimate may look good but still be unstable on small validation sets.
Clear metric policy prevents ambiguous deployment decisions.
Related reading
- Tensorflow Precision / Recall / F1 score and Confusion matrix
- Tensorflow predict the class of output
- Tensorflow print all placeholder variable names from meta graph
- Tensorflow Print doesn't print anything if exception is thrown during downstream operations
- Tensorflow prints the same info twice while training
- tensorflow py_func is handy but makes my training step very slow.
- Tensorflow Py_func returns unknown shape
- Tensorflow python Accessing individual elements in a tensor
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.