Threshold tuning changes the cutoff point for deciding if a prediction is positive or negative. This affects Precision and Recall. We focus on these because changing the threshold shifts how many true positives, false positives, and false negatives we get. Accuracy alone can hide these changes. So, Precision and Recall help us understand the balance between catching positives and avoiding false alarms.
Threshold tuning in ML Python - Model Metrics & Evaluation
Start learning this pattern below
Jump into concepts and practice - no test required
+-----------------------+
| Confusion Matrix |
+-----------------------+
| | Predicted |
| Actual | Pos | Neg |
+----------+-----+-----+
| Pos | TP=80 | FN=20 |
| Neg | FP=10 | TN=90 |
+-----------------------+
Total samples = 80 + 20 + 10 + 90 = 200
Precision = TP / (TP + FP) = 80 / (80 + 10) = 0.89
Recall = TP / (TP + FN) = 80 / (80 + 20) = 0.80
When you lower the threshold, the model predicts more positives:
- Recall increases: You catch more true positives (good for disease detection).
- Precision decreases: You get more false positives (more healthy people flagged).
When you raise the threshold, the model predicts fewer positives:
- Precision increases: Most predicted positives are correct (good for spam filters).
- Recall decreases: You miss some true positives.
Threshold tuning helps find the best balance for your problem.
Good: Precision and Recall values close to each other and high (e.g., both above 0.8) show a balanced threshold.
Bad: Very high Precision but very low Recall means many positives are missed. Very high Recall but very low Precision means many false alarms.
Example: Precision=0.95 and Recall=0.30 is bad if missing positives is costly.
- Ignoring class imbalance: Accuracy can be misleading if one class is much bigger.
- Overfitting threshold: Tuning threshold on test data leaks information and inflates performance.
- Using only one metric: Focusing only on Precision or Recall hides the full picture.
- Not validating threshold: Threshold should be chosen using validation data, not training or test data.
Your model has 98% accuracy but 12% recall on fraud detection. Is it good for production? Why or why not?
Answer: No, it is not good. The low recall (12%) means the model misses most fraud cases, which is dangerous. High accuracy is misleading because fraud is rare, so the model mostly predicts no fraud correctly but fails to catch fraud.
Practice
Solution
Step 1: Understand threshold tuning concept
Threshold tuning is about choosing a cutoff value for predicted probabilities to decide class labels.Step 2: Identify the main goal
The goal is to find the cutoff that best separates positive and negative classes for better decisions.Final Answer:
To find the best cutoff probability to decide between classes -> Option AQuick Check:
Threshold tuning = best cutoff choice [OK]
- Confusing threshold tuning with feature selection
- Thinking threshold tuning changes training data size
- Assuming threshold tuning speeds up training
probs in Python to get binary predictions?Solution
Step 1: Understand threshold application
We compare each probability to 0.7 to get True/False, then convert to 0/1 integers.Step 2: Check correct syntax
Using (probs > 0.7).astype(int) converts boolean array to integer array correctly.Final Answer:
preds = (probs > 0.7).astype(int) -> Option AQuick Check:
Threshold applied with boolean then int cast [OK]
- Forgetting to convert boolean to int
- Using int() on entire array instead of element-wise
- Using >= instead of > changes threshold logic
from sklearn.metrics import f1_score probs = [0.2, 0.8, 0.6, 0.4] true_labels = [0, 1, 1, 0] threshold = 0.5 preds = [1 if p > threshold else 0 for p in probs] f1 = f1_score(true_labels, preds) print(round(f1, 2))
Solution
Step 1: Calculate predictions with threshold 0.5
probs > 0.5 gives preds = [0, 1, 1, 0]Step 2: Compute F1 score for preds vs true_labels
True positives = 2, false positives = 0, false negatives = 0, so F1 = 2*TP/(2*TP+FP+FN) = 2*2/(4+0+0) = 1.0, since preds and true_labels are identical.Final Answer:
1.00 -> Option CQuick Check:
Perfect match means F1 = 1.00 [OK]
- Miscomputing predictions from threshold
- Confusing precision and recall in F1 calculation
- Rounding errors in final score
probs = [0.1, 0.4, 0.6, 0.9]
true_labels = [0, 0, 1, 1]
thresholds = [0.3, 0.5, 0.7]
best_f1 = 0
for t in thresholds:
preds = (probs > t)
f1 = f1_score(true_labels, preds)
if f1 > best_f1:
best_f1 = f1
print(best_f1)Solution
Step 1: Check code for missing imports
The code uses f1_score but does not import it from sklearn.metrics.Step 2: Identify error cause
Without importing f1_score, Python will raise a NameError when calling f1_score.Final Answer:
Missing import of f1_score -> Option BQuick Check:
Always import functions before use [OK]
- Assuming boolean preds cause error (they don't)
- Ignoring missing import errors
- Thinking loop variable is unused
Solution
Step 1: Understand the trade-off
High recall catches more sick patients but may increase false alarms; precision reduces false alarms but may miss sick patients.Step 2: Identify best metric for balance
F1 score balances precision and recall, making it best to tune threshold for this trade-off.Final Answer:
Choose threshold maximizing F1 score -> Option DQuick Check:
F1 balances recall and precision [OK]
- Maximizing recall ignores false alarms
- Maximizing precision ignores missed cases
- Minimizing accuracy is not meaningful
