TExcelTAD
Home › Training Mechanics, Evaluation & Model Improvement › Log Loss and Choosing a Threshold

Log Loss and Choosing a Threshold

A loan model says "probability of default 0.03" and the bank prices the loan from that number. A triage model says 0.4 and a nurse decides whether to call the patient back. In both cases the probability itself is used, not just the ranking. Two questions follow: are the probabilities good (log loss measures that), and where do we cut to turn them into a decision (the threshold, chosen from the costs of the two errors). This lesson does both, and keeps the test set out of the choice.

Log loss

For binary labels yi∈{0,1}y_i \in \{0, 1\} and predicted probabilities pi=P^(yi=1)p_i = \hat{P}(y_i = 1), the log loss (binary cross-entropy, negative log-likelihood) is

LogLoss=−1n∑i=1n[yilog⁡pi+(1−yi)log⁡(1−pi)]\text{LogLoss} = -\frac{1}{n} \sum_{i=1}^{n} \big[ y_i \log p_i + (1 - y_i) \log (1 - p_i) \big]

Each example contributes −log⁡-\log of the probability the model gave to what really happened. Probability 0.9 on the true class costs −log⁡0.9=0.105-\log 0.9 = 0.105; 0.5 costs 0.693 (a coin flip); 0.01 costs 4.6, and 0 costs infinity. It is the training loss of logistic regression and of neural classifiers (Cross-Entropy), and as a metric it is a proper scoring rule: in expectation it is minimised by reporting the true probabilities, so it rewards both ranking and calibration. For KK classes it is −1n∑ilog⁡pi,yi-\frac{1}{n}\sum_i \log p_{i, y_i}, minus the mean log-probability of the true class.

python · try it yourself
import numpy as np
from sklearn.metrics import log_loss

y = np.array([1, 0, 1, 0, 0, 0, 1, 0])
p = np.array([0.9, 0.2, 0.7, 0.4, 0.1, 0.3, 0.8, 0.4])

def logloss(y, p, eps=1e-15):
    p = np.clip(p, eps, 1 - eps)                 # log(0) would be -inf
    return -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))

print(f"log loss ours {logloss(y, p):.4f}  sklearn {log_loss(y, p):.4f}")
print("per-example cost:", (-np.log(np.where(y == 1, p, 1 - p))).round(3).tolist())

p_bad = p.copy(); p_bad[1] = 0.99              # one confident mistake: a negative given 0.99
print(f"one confident error: log loss {logloss(y, p_bad):.4f}; accuracy only drops from {np.mean((p >= 0.5) == y):.3f} to {np.mean((p_bad >= 0.5) == y):.3f}")
print(f"always 0.5: {logloss(y, np.full(8, 0.5)):.4f}   always the base rate {y.mean()}: {logloss(y, np.full(8, y.mean())):.4f}")
log loss ours 0.2990  sklearn 0.2990
per-example cost: [0.105, 0.223, 0.357, 0.511, 0.105, 0.357, 0.223, 0.511]
one confident error: log loss 0.8468; accuracy only drops from 1.000 to 0.875
always 0.5: 0.6931   always the base rate 0.375: 0.6616

All eight predictions are on the right side of 0.5, and the log loss is 0.299. Changing a single negative's probability from 0.2 to 0.99 costs that example −log⁡0.01=4.6-\log 0.01 = 4.6 instead of 0.223, and the mean jumps to 0.847, almost three times as high, while accuracy only drops from 1 to 0.875. The two constant baselines are worth printing in every report: 0.693 for "always 0.5" and 0.662 for "always the base rate 0.375". A model whose log loss is not clearly below the base-rate line has learned little about probabilities.

From probabilities to decisions

A threshold tt turns probabilities into decisions: predict positive when p≥tp \ge t. The default t=0.5t = 0.5 is right only when the two errors cost the same and the probabilities are calibrated. Write the costs in a cost matrix: CFNC_{FN} for a miss, CFPC_{FP} for a false alarm, correct decisions cost 0. If pp is a calibrated probability, predicting positive costs (1−p) CFP(1 - p)\,C_{FP} in expectation and predicting negative costs p CFNp\,C_{FN}, so it pays to predict positive when

p CFN>(1−p) CFP  ⟺  p>t∗=CFPCFP+CFNp \, C_{FN} > (1 - p) \, C_{FP} \iff p > t^{*} = \frac{C_{FP}}{C_{FP} + C_{FN}}

With a miss ten times as expensive as a false alarm, t∗=111≈0.091t^{*} = \frac{1}{11} \approx 0.091. In practice the probabilities are not perfectly calibrated, so you also check thresholds empirically: compute the cost (or F1F_1, or recall) for every candidate threshold on a validation set, pick the best, and report the result once on the test set. Tuning the threshold on the test set is tuning on the test set.

python · try it yourself
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, f1_score, recall_score, precision_score

X, y = make_classification(n_samples=6000, n_features=10, n_informative=4, weights=[0.9], flip_y=0.02, random_state=0)
X_tr, X_tmp, y_tr, y_tmp = train_test_split(X, y, test_size=0.5, stratify=y, random_state=0)
X_val, X_te, y_val, y_te = train_test_split(X_tmp, y_tmp, test_size=0.5, stratify=y_tmp, random_state=0)
model = LogisticRegression(max_iter=1000).fit(X_tr, y_tr)
p_val, p_te = model.predict_proba(X_val)[:, 1], model.predict_proba(X_te)[:, 1]

C_FN, C_FP = 10, 1
def cost(y, p, t):
    tn, fp, fn, tp = confusion_matrix(y, p >= t).ravel()
    return (C_FN * fn + C_FP * fp) / len(y)       # average cost per case

grid = np.round(np.arange(0.02, 0.99, 0.01), 2)
t_cost = grid[np.argmin([cost(y_val, p_val, t) for t in grid])]
t_f1 = grid[np.argmax([f1_score(y_val, p_val >= t) for t in grid])]
ok = [t for t in grid if recall_score(y_val, p_val >= t) >= 0.90]
t_rec = max(ok)                                   # highest threshold that still gives recall >= 0.9

print(f"positives: train {y_tr.mean():.3f}  validation {y_val.mean():.3f}  test {y_te.mean():.3f}")
print(f"chosen on validation: cost {t_cost}  F1 {t_f1}  recall>=0.9 {t_rec}  (theory for cost: {C_FP / (C_FP + C_FN):.3f})")
for name, t in [("default 0.5", 0.5), ("min cost", t_cost), ("max F1", t_f1), ("recall>=0.9", t_rec)]:
    pred = p_te >= t
    print(f"test  {name:12s} t={t:.2f}  cost/case {cost(y_te, p_te, t):.3f}  precision {precision_score(y_te, pred):.3f}"
          f"  recall {recall_score(y_te, pred):.3f}  F1 {f1_score(y_te, pred):.3f}")
positives: train 0.110  validation 0.110  test 0.109
chosen on validation: cost 0.13  F1 0.28  recall>=0.9 0.03  (theory for cost: 0.091)
test  default 0.5  t=0.50  cost/case 0.937  precision 0.828  recall 0.146  F1 0.249
test  min cost     t=0.13  cost/case 0.687  precision 0.246  recall 0.537  F1 0.337
test  max F1       t=0.28  cost/case 0.776  precision 0.542  recall 0.317  F1 0.400
test  recall>=0.9  t=0.03  cost/case 0.869  precision 0.115  recall 0.890  F1 0.204

About 11 % of the cases are positive. The threshold that minimises cost on the validation set is 0.13, close to the theoretical t∗=0.091t^{*} = 0.091 (the logistic model is roughly, not perfectly, calibrated). On the test set it cuts the average cost from 0.937 per case at the default 0.5 to 0.687, by raising recall from 0.146 to 0.537 at the price of many more false alarms (precision 0.246). Maximising F1F_1 picks a different point (0.28), and a required recall of 0.9 forces the threshold down to 0.03, where the test recall comes out at 0.890: a target met on validation is usually met only approximately on new data. Each goal gives a different threshold; the business decides the goal.

The lab: moving the threshold

Here 10 % of the 1000 cases are positive. At threshold 1 the readouts show recall 0.700 and precision 0.310; at 1.5, recall 0.520 and precision 0.423, with the best F1F_1 of these settings (0.466); at 2.5, precision 0.773 but recall only 0.170. Accuracy keeps rising as the threshold goes up (0.814, 0.881, 0.912): with few positives, accuracy prefers predicting "negative" almost always. Which point is right is a question for the cost matrix, not for the metric.

05010005scorecountScores by true classpositive →← negativenegativepositivepredicted +predicted −actual posactual neg70TP30FN156FP744TNprecision 0.310 recall 0.700 F1 0.4290.00.51.00.00.51.0false positive rateTPRROC curveAUC 0.853- - chance0.00.51.00.00.51.0recallprecisionPrecision-recallAP 0.469- - chance

scikit-learn does the loop for you

TunedThresholdClassifierCV (scikit-learn 1.5 and later) wraps a classifier and picks the threshold by cross-validation on the training data, so the test set stays untouched:

python · try it yourself
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split, TunedThresholdClassifierCV
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score

X, y = make_classification(n_samples=6000, n_features=10, n_informative=4, weights=[0.9], flip_y=0.02, random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)
base = LogisticRegression(max_iter=1000).fit(X_tr, y_tr)
tuned = TunedThresholdClassifierCV(LogisticRegression(max_iter=1000), scoring="f1", cv=5).fit(X_tr, y_tr)
print(f"chosen threshold {tuned.best_threshold_:.3f}  (cross-validated F1 {tuned.best_score_:.3f})")
print(f"test F1 at 0.5 {f1_score(y_te, base.predict(X_te)):.3f}   at tuned threshold {f1_score(y_te, tuned.predict(X_te)):.3f}")
chosen threshold 0.229  (cross-validated F1 0.424)
test F1 at 0.5 0.204   at tuned threshold 0.457

Five-fold cross-validation inside the training set picks a threshold of 0.229, and the test F1F_1 rises from 0.204 at 0.5 to 0.457. The model is the same; only the decision rule changed. To minimise a cost instead, pass scoring=make_scorer(cost_fn, greater_is_better=False) with your own cost_fn(y_true, y_pred).

Pitfalls

  • Picking the threshold on the test set. The test score is then optimistic; use a validation set or cross-validation.
  • Thresholds do not transfer. A threshold depends on the class balance and on calibration. After retraining, or when the positive rate in production changes, choose it again (Distribution Shift).
  • Log loss with hard 0/1 predictions is infinite (or huge after clipping) as soon as one is wrong. Pass probabilities.
  • Comparing log loss across data sets with different base rates: the constant base-rate model already scores differently on each. Compare with that baseline.

Practice

  1. A model gives p=0.8p = 0.8 to a positive and p=0.8p = 0.8 to a negative. What does each add to the log loss sum?
Answer

The positive: −log⁡0.8≈0.223-\log 0.8 \approx 0.223. The negative: −log⁡(1−0.8)=−log⁡0.2≈1.609-\log(1 - 0.8) = -\log 0.2 \approx 1.609.

  1. A false alarm costs 5 and a miss costs 20. With calibrated probabilities, what threshold minimises the expected cost?
Answer

t∗=CFPCFP+CFN=525=0.2t^{*} = \frac{C_{FP}}{C_{FP} + C_{FN}} = \frac{5}{25} = 0.2.

Test yourself

Why does log loss punish a confident wrong prediction so much more than accuracy does?

  1. It squares the error
  2. It adds −log⁡-\log of the probability given to the true class, which grows without bound as that probability goes to 0
  3. It counts errors twice
  4. It ignores correct predictions

Missing a fraud costs 9 times as much as a false alarm. With calibrated probabilities, the cost-minimising threshold is…

  1. 0.9
  2. 0.5
  3. 0.1
  4. 0.01

Where should the decision threshold be chosen?

  1. On the test set, to get the best reported score
  2. On a validation set or by cross-validation on the training data, then reported once on the test set
  3. Always 0.5
  4. On the training predictions after fitting

Which of these is a proper scoring rule, minimised in expectation by the true probabilities?

  1. accuracy
  2. log loss
  3. F1F_1
  4. recall