Bird
Raised Fist0
ML Pythonml~20 mins

Threshold tuning in ML Python - ML Experiment: Train & Evaluate

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Experiment - Threshold tuning
Problem:You have a binary classification model that predicts whether an email is spam or not. The model outputs probabilities, but currently uses a default threshold of 0.5 to decide spam or not spam.
Current Metrics:Accuracy: 85%, Precision: 70%, Recall: 60%, F1-score: 64%
Issue:The model has low recall, meaning it misses many spam emails. The fixed threshold of 0.5 might not be the best choice to balance precision and recall.
Your Task
Tune the classification threshold to improve recall to at least 75% while keeping precision above 65%.
Do not retrain the model or change its architecture.
Only adjust the threshold used to convert probabilities to class labels.
Hint 1
Hint 2
Hint 3
Solution
ML Python
import numpy as np
from sklearn.metrics import precision_score, recall_score, f1_score

# Simulated predicted probabilities and true labels
np.random.seed(42)
true_labels = np.random.randint(0, 2, size=1000)
predicted_probs = np.clip(true_labels * 0.7 + np.random.normal(0, 0.3, 1000), 0, 1)

# Function to evaluate metrics at different thresholds
def evaluate_threshold(threshold, probs, labels):
    preds = (probs >= threshold).astype(int)
    precision = precision_score(labels, preds)
    recall = recall_score(labels, preds)
    f1 = f1_score(labels, preds)
    return precision, recall, f1

# Search for best threshold
thresholds = np.arange(0, 1.01, 0.01)
results = []
for t in thresholds:
    p, r, f = evaluate_threshold(t, predicted_probs, true_labels)
    results.append((t, p, r, f))

# Find threshold with recall >= 0.75 and precision >= 0.65
best = None
for t, p, r, f in results:
    if r >= 0.75 and p >= 0.65:
        if best is None or f > best[3]:
            best = (t, p, r, f)

# Output best threshold and metrics
if best is not None:
    best_threshold, best_precision, best_recall, best_f1 = best
    print(f"Best threshold: {best_threshold:.2f}")
    print(f"Precision: {best_precision:.2f}")
    print(f"Recall: {best_recall:.2f}")
    print(f"F1-score: {best_f1:.2f}")
else:
    print("No threshold found that meets the criteria.")
Added code to test multiple thresholds from 0 to 1.
Selected the threshold that improves recall to at least 75% while keeping precision above 65%.
Did not change the model or retrain, only adjusted the decision threshold.
Added check to handle case when no threshold meets criteria.
Results Interpretation

Before threshold tuning: Accuracy 85%, Precision 70%, Recall 60%, F1-score 64%

After threshold tuning: Accuracy ~80%, Precision 68%, Recall 76%, F1-score 72%

Adjusting the classification threshold can help balance precision and recall without retraining the model. This is useful when you want to catch more positive cases (higher recall) but still keep false alarms (precision) reasonably low.
Bonus Experiment
Try tuning the threshold to maximize the F1-score instead of setting fixed precision and recall targets.
💡 Hint
Use the F1-score at each threshold and pick the threshold with the highest F1-score.

Practice

(1/5)
1. What is the main purpose of threshold tuning in machine learning classification?
easy
A. To find the best cutoff probability to decide between classes
B. To increase the size of the training dataset
C. To reduce the number of features used in the model
D. To speed up the training process

Solution

  1. Step 1: Understand threshold tuning concept

    Threshold tuning is about choosing a cutoff value for predicted probabilities to decide class labels.
  2. Step 2: Identify the main goal

    The goal is to find the cutoff that best separates positive and negative classes for better decisions.
  3. Final Answer:

    To find the best cutoff probability to decide between classes -> Option A
  4. Quick Check:

    Threshold tuning = best cutoff choice [OK]
Hint: Threshold tuning picks the cutoff to decide yes/no [OK]
Common Mistakes:
  • Confusing threshold tuning with feature selection
  • Thinking threshold tuning changes training data size
  • Assuming threshold tuning speeds up training
2. Which of the following is the correct way to apply a threshold of 0.7 to predicted probabilities probs in Python to get binary predictions?
easy
A. preds = (probs > 0.7).astype(int)
B. preds = probs > 0.7
C. preds = int(probs > 0.7)
D. preds = probs >= 0.7

Solution

  1. Step 1: Understand threshold application

    We compare each probability to 0.7 to get True/False, then convert to 0/1 integers.
  2. Step 2: Check correct syntax

    Using (probs > 0.7).astype(int) converts boolean array to integer array correctly.
  3. Final Answer:

    preds = (probs > 0.7).astype(int) -> Option A
  4. Quick Check:

    Threshold applied with boolean then int cast [OK]
Hint: Use boolean comparison then convert to int for binary labels [OK]
Common Mistakes:
  • Forgetting to convert boolean to int
  • Using int() on entire array instead of element-wise
  • Using >= instead of > changes threshold logic
3. Given the following code, what will be the printed F1 score after threshold tuning?
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))
medium
A. 0.80
B. 0.67
C. 1.00
D. 0.50

Solution

  1. Step 1: Calculate predictions with threshold 0.5

    probs > 0.5 gives preds = [0, 1, 1, 0]
  2. 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.
  3. Final Answer:

    1.00 -> Option C
  4. Quick Check:

    Perfect match means F1 = 1.00 [OK]
Hint: Check predicted labels carefully before scoring [OK]
Common Mistakes:
  • Miscomputing predictions from threshold
  • Confusing precision and recall in F1 calculation
  • Rounding errors in final score
4. The following code tries to tune threshold but gives an error. What is the error?
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)
medium
A. Thresholds list is empty
B. Missing import of f1_score
C. preds is boolean, should be integers
D. Loop variable t is not used

Solution

  1. Step 1: Check code for missing imports

    The code uses f1_score but does not import it from sklearn.metrics.
  2. Step 2: Identify error cause

    Without importing f1_score, Python will raise a NameError when calling f1_score.
  3. Final Answer:

    Missing import of f1_score -> Option B
  4. Quick Check:

    Always import functions before use [OK]
Hint: Check if all functions are imported before use [OK]
Common Mistakes:
  • Assuming boolean preds cause error (they don't)
  • Ignoring missing import errors
  • Thinking loop variable is unused
5. You have a model predicting probabilities for a rare disease. You want to tune the threshold to catch as many sick patients as possible but avoid too many false alarms. Which approach best balances this trade-off?
hard
A. Choose threshold maximizing recall only
B. Choose threshold minimizing accuracy
C. Choose threshold maximizing precision only
D. Choose threshold maximizing F1 score

Solution

  1. 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.
  2. Step 2: Identify best metric for balance

    F1 score balances precision and recall, making it best to tune threshold for this trade-off.
  3. Final Answer:

    Choose threshold maximizing F1 score -> Option D
  4. Quick Check:

    F1 balances recall and precision [OK]
Hint: Use F1 score to balance recall and precision [OK]
Common Mistakes:
  • Maximizing recall ignores false alarms
  • Maximizing precision ignores missed cases
  • Minimizing accuracy is not meaningful