Machine Learning

Threshold by minimizing expected business cost

When a false negative costs 50 times more than a false positive, the right threshold can't be read off any standard curve: you minimize the expected total cost directly on the validation set.

Prerequisites

numpy, scikit-learn

Python
import numpy as np
from sklearn.metrics import confusion_matrix

COUT_FP = 10.0      # vérification manuelle inutile
COUT_FN = 500.0     # fraude passée inaperçue

proba_val = model.predict_proba(X_val)[:, 1]
seuils = np.linspace(0.01, 0.99, 99)

couts = []
for s in seuils:
    pred = (proba_val >= s).astype(int)
    tn, fp, fn, tp = confusion_matrix(y_val, pred).ravel()
    couts.append(fp * COUT_FP + fn * COUT_FN)

best = int(np.argmin(couts))
print(f"Seuil optimal coût : {seuils[best]:.2f}")
print(f"Coût attendu       : {couts[best]:,.0f}")
print(f"Coût au seuil 0.50 : {couts[49]:,.0f}")
# L'écart entre les deux lignes = argent laissé sur la table par défaut.

Result

Seuil optimal coût : 0.08
Coût attendu       : 28,750
Coût au seuil 0.50 : 61,230
>>> float((proba_val >= 0.08).mean())   # part du flux vérifiée à ce seuil
0.214
Coût métierSeuilDécisionAsymétrie

Related snippets

Back to the Data Lab