Choose the right validation scheme, get honest tuning estimates with nested CV, pick metrics and cost-based thresholds, calibrate probabilities, handle class imbalance, and put bootstrap confidence intervals on every score with scikit-learn.
A model is only as trustworthy as the procedure used to score it. This tutorial works through the evaluation decisions that separate a credible result from a lucky one: how to split data, how to tune without fooling yourself, which metrics to report, how to turn probabilities into decisions, and how to put an honest error bar on every number. All examples run end to end on synthetic data, and every number shown is real output.
The examples use Python 3.13 with scikit-learn 1.9.1, NumPy 2.5.5, SciPy 1.18.1 and pandas 3.1.2 (the latest stable releases at the time of writing). Any Python 3.12+ works. The code blocks build on each other, so run them in a single session or notebook.
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install "scikit-learn>=1.9,<2.0" "numpy>=2.5,<3.0" "scipy>=1.18,<2.0"
The running example is a binary problem with 5.5% positives, which is typical for fraud, churn or defect detection. The signal is partly non-linear, so a linear model and a gradient-boosted model will genuinely differ.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
X, y = make_classification(
n_samples=6000, n_features=20, n_informative=6, n_redundant=4,
weights=[0.95, 0.05], flip_y=0.01, class_sep=0.8, random_state=42,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
print(f"positives: {y.mean():.3%} train={len(y_train)} test={len(y_test)}")
positives: 5.500% train=4500 test=1500
With 94.5% negatives, a model that never predicts the positive class scores 94.5% accuracy. Compare a constant baseline with a real logistic regression at the default 0.5 threshold:
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score, balanced_accuracy_score, recall_score
dummy = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
logreg = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
logreg.fit(X_train, y_train)
for name, m in [("dummy", dummy), ("logreg", logreg)]:
p = m.predict(X_test)
print(f"{name:7s} acc={accuracy_score(y_test, p):.3f} "
f"bal_acc={balanced_accuracy_score(y_test, p):.3f} "
f"recall={recall_score(y_test, p):.3f}")
dummy acc=0.945 bal_acc=0.500 recall=0.000
logreg acc=0.945 bal_acc=0.529 recall=0.061
Identical accuracy, yet one model finds 6% of the positives and the other none. Accuracy conflates two separate questions: how well the model ranks cases, and where the threshold is set. The rest of this tutorial keeps those questions apart. Ranking quality is measured with threshold-free metrics; the threshold is chosen afterwards from the costs of each kind of error.
A single train/test split gives one number, but that number depends on which rows happened to land in the test set. Repeating the split with 20 different seeds shows how much:
from sklearn.metrics import roc_auc_score
aucs = []
for seed in range(20):
Xa, Xb, ya, yb = train_test_split(X, y, test_size=0.25, stratify=y, random_state=seed)
m = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)).fit(Xa, ya)
aucs.append(roc_auc_score(yb, m.predict_proba(Xb)[:, 1]))
aucs = np.array(aucs)
print(f"holdout AUC over 20 splits: min={aucs.min():.3f} max={aucs.max():.3f} sd={aucs.std(ddof=1):.3f}")
holdout AUC over 20 splits: min=0.785 max=0.861 sd=0.021
The same model on the same data scores anywhere from 0.785 to 0.861 depending on the split. Differences between candidate models are often smaller than that range. With only 83 positives per test set, this is expected.
K-fold cross-validation uses every row for testing exactly once and averages over folds. Stratification keeps the class ratio constant in every fold, which matters when positives are rare. Repeating the whole procedure with different shuffles averages out the arbitrary choice of fold boundaries.
from sklearn.model_selection import (
KFold, StratifiedKFold, RepeatedStratifiedKFold, cross_val_score,
)
schemes = {
"KFold(5, shuffle)": KFold(5, shuffle=True, random_state=0),
"StratifiedKFold(5)": StratifiedKFold(5, shuffle=True, random_state=0),
"RepeatedStratified(5x10)": RepeatedStratifiedKFold(n_splits=5, n_repeats=10, random_state=0),
}
for name, cv in schemes.items():
s = cross_val_score(logreg, X, y, cv=cv, scoring="roc_auc")
print(f"{name:26s} n={len(s):2d} mean={s.mean():.3f} sd={s.std(ddof=1):.3f}")
kf = KFold(5, shuffle=True, random_state=0)
print("positives per KFold test fold:", [int(y[te].sum()) for _, te in kf.split(X, y)])
skf = StratifiedKFold(5, shuffle=True, random_state=0)
print("positives per Stratified fold:", [int(y[te].sum()) for _, te in skf.split(X, y)])
KFold(5, shuffle) n= 5 mean=0.825 sd=0.045
StratifiedKFold(5) n= 5 mean=0.826 sd=0.022
RepeatedStratified(5x10) n=50 mean=0.826 sd=0.030
positives per KFold test fold: [67, 69, 64, 63, 67]
positives per Stratified fold: [66, 66, 66, 66, 66]
The means agree, but stratification halves the fold-to-fold spread here because each fold sees the same number of positives. The fold standard deviation is not a standard error: folds share training data, so sd / sqrt(k) understates uncertainty (more on this below).
When several rows belong to the same entity (a customer, a patient, a device), random splits put rows of the same entity in both train and test. A flexible model then partly memorises the entity instead of learning the pattern, and the score measures recall of known entities rather than generalisation to new ones. The simulation below has 200 groups of 15 near-identical rows whose labels depend only weakly on the features:
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GroupKFold
rng = np.random.default_rng(0)
n_groups, per_group = 200, 15
centroids = rng.normal(size=(n_groups, 10))
p_group = 1 / (1 + np.exp(-(0.5 * centroids[:, 0] + rng.normal(scale=1.5, size=n_groups))))
groups = np.repeat(np.arange(n_groups), per_group)
Xg = centroids[groups] + rng.normal(scale=0.1, size=(len(groups), 10))
yg = (rng.random(len(groups)) < p_group[groups]).astype(int)
rf = RandomForestClassifier(n_estimators=200, random_state=0, n_jobs=-1)
naive = cross_val_score(rf, Xg, yg, cv=KFold(5, shuffle=True, random_state=0), scoring="roc_auc")
grouped = cross_val_score(rf, Xg, yg, groups=groups, cv=GroupKFold(5), scoring="roc_auc")
print(f"KFold AUC {naive.mean():.3f}")
print(f"GroupKFold AUC {grouped.mean():.3f}")
KFold AUC 0.789
GroupKFold AUC 0.561
The random split reports 0.789; on genuinely new groups the model achieves 0.561. The question to ask is: in production, will the model score entities it has already seen? If not, split by entity. StratifiedGroupKFold combines grouping with approximate class balance.
If the model will predict the future from the past, validation must do the same. TimeSeriesSplit produces expanding training windows followed by a later test window; the gap parameter drops rows between them to mimic the delay between data collection and prediction, and to stop features built from rolling windows leaking across the boundary. Rows must already be sorted by time.
from sklearn.model_selection import TimeSeriesSplit
tss = TimeSeriesSplit(n_splits=4, test_size=100, gap=10)
for i, (tr, te) in enumerate(tss.split(np.arange(600))):
print(f"split {i}: train [{tr[0]}..{tr[-1]}] test [{te[0]}..{te[-1]}]")
split 0: train [0..189] test [200..299]
split 1: train [0..289] test [300..399]
split 2: train [0..389] test [400..499]
split 3: train [0..489] test [500..599]
Report per-split scores, not only their mean: a downward trend signals drift that an average hides.
After a grid search, best_score_ is the maximum of many noisy estimates, so it is biased upwards. The more configurations you try and the smaller the data, the larger the bias. Nested cross-validation fixes this by treating the entire search as the estimator: an inner loop picks hyperparameters, and an outer loop scores that whole procedure on data the search never saw. Here, on an 800-row subset with 20 SVM configurations:
from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV
Xs, ys = X[:800], y[:800]
param_grid = {"svc__C": [0.01, 0.1, 1, 10, 100], "svc__gamma": [0.001, 0.01, 0.1, 1]}
inner = StratifiedKFold(5, shuffle=True, random_state=1)
outer = StratifiedKFold(5, shuffle=True, random_state=2)
search = GridSearchCV(make_pipeline(StandardScaler(), SVC()), param_grid, cv=inner, scoring="roc_auc")
search.fit(Xs, ys)
print(f"best inner score (optimistic): {search.best_score_:.3f} {search.best_params_}")
nested = cross_val_score(search, Xs, ys, cv=outer, scoring="roc_auc")
print(f"nested CV estimate: {nested.mean():.3f} +/- {nested.std(ddof=1):.3f}")
best inner score (optimistic): 0.859 {'svc__C': 10, 'svc__gamma': 0.01}
nested CV estimate: 0.813 +/- 0.087
The selected configuration looks like a 0.859 model; the procedure that selected it delivers about 0.813, with a wide spread because each outer fold holds only about nine positives. Nested CV estimates the performance of the tuning procedure, not of one specific setting; the outer folds may pick different ones. The model you ship is still search.fit(X, y) on all data; nested CV tells you what to expect from it. Every preprocessing step that learns from data (scaling, imputation, feature selection, resampling) must live inside the pipeline so it is refitted in every fold.
Pick metrics that answer the question the business is asking. Four are worth reporting for most probabilistic classifiers:
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import average_precision_score, log_loss, brier_score_loss
models = {
"logreg": make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
"hgb": HistGradientBoostingClassifier(random_state=0),
"naive_bayes": GaussianNB(),
}
proba = {}
for name, m in models.items():
proba[name] = m.fit(X_train, y_train).predict_proba(X_test)[:, 1]
p = proba[name]
print(f"{name:12s} ROC={roc_auc_score(y_test, p):.3f} PR={average_precision_score(y_test, p):.3f} "
f"logloss={log_loss(y_test, p):.3f} brier={brier_score_loss(y_test, p):.4f}")
print(f"PR AUC of a random ranker ~ prevalence = {y_test.mean():.3f}")
print(f"Brier of constant prevalence = {brier_score_loss(y_test, np.full_like(p, y_train.mean())):.4f}")
logreg ROC=0.842 PR=0.372 logloss=0.160 brier=0.0418
hgb ROC=0.934 PR=0.740 logloss=0.123 brier=0.0268
naive_bayes ROC=0.827 PR=0.226 logloss=0.246 brier=0.0745
PR AUC of a random ranker ~ prevalence = 0.055
Brier of constant prevalence = 0.0517
On ROC AUC, logistic regression and naive Bayes look nearly equal (0.842 vs 0.827). PR AUC separates them clearly (0.372 vs 0.226), because their top-ranked cases differ in quality. Naive Bayes also has a Brier score of 0.0745, worse than predicting 5.5% for everyone: it ranks reasonably but its probabilities are badly miscalibrated. Only proper scoring rules reveal that.
The 0.5 default threshold is arbitrary. The correct threshold follows from what each error costs. Suppose a missed positive costs 20 units and a false alarm costs 1. scikit-learn offers two post-processing wrappers: TunedThresholdClassifierCV searches for the threshold that maximises a scorer using internal cross-validation, and FixedThresholdClassifier applies a threshold you choose.
from sklearn.metrics import confusion_matrix, make_scorer
from sklearn.model_selection import TunedThresholdClassifierCV, FixedThresholdClassifier
COST_FN, COST_FP = 20, 1 # a missed positive costs 20x a false alarm
def neg_cost(y_true, y_pred):
tn, fp, fn, tp = confusion_matrix(y_true, y_pred, labels=[0, 1]).ravel()
return -(COST_FN * fn + COST_FP * fp)
cost_scorer = make_scorer(neg_cost) # greater is better, so negate the cost
default = HistGradientBoostingClassifier(random_state=0).fit(X_train, y_train)
tuned = TunedThresholdClassifierCV(
HistGradientBoostingClassifier(random_state=0),
scoring=cost_scorer, cv=5, random_state=0,
).fit(X_train, y_train)
bayes = FixedThresholdClassifier(
HistGradientBoostingClassifier(random_state=0),
threshold=COST_FP / (COST_FP + COST_FN),
).fit(X_train, y_train)
print(f"tuned threshold: {tuned.best_threshold_:.3f}")
for name, m in [("default 0.5", default), ("tuned", tuned), ("fixed 1/21", bayes)]:
tn, fp, fn, tp = confusion_matrix(y_test, m.predict(X_test)).ravel()
print(f"{name:12s} FN={fn:3d} FP={fp:4d} cost={COST_FN*fn + COST_FP*fp}")
tuned threshold: 0.010
default 0.5 FN= 41 FP= 6 cost=826
tuned FN= 12 FP= 113 cost=353
fixed 1/21 FN= 23 FP= 42 cost=502
Tuning the threshold cuts the test cost from 826 to 353 without touching the model. The third row deserves attention. Decision theory says that if probabilities are calibrated, the cost-minimising rule is to predict positive when p > C_FP / (C_FP + C_FN), here 1/21 ≈ 0.048. That rule does worse than the tuned threshold of 0.010, which tells us the model's probabilities are not calibrated: a case it scores at 0.02 is in reality positive far more often than 2% of the time. That is the next topic.
Two cautions. The tuned threshold is itself a fitted parameter; estimate its performance on data not used to tune it, as done here with the test set, or wrap the tuner in an outer CV. And the cost matrix is a business input: if it is uncertain, show results over a range of plausible ratios.
A classifier is calibrated if, among all cases it scores at 0.2, about 20% are positive. Boosted trees, random forests, SVMs and naive Bayes frequently are not. CalibratedClassifierCV fits a mapping from raw scores to probabilities on held-out folds: "sigmoid" (Platt scaling, two parameters, robust on small data) or "isotonic" (a monotone step function, more flexible, needs more data, roughly a thousand or more calibration samples).
from sklearn.calibration import CalibratedClassifierCV, calibration_curve
raw = HistGradientBoostingClassifier(random_state=0).fit(X_train, y_train)
iso = CalibratedClassifierCV(HistGradientBoostingClassifier(random_state=0),
method="isotonic", cv=5).fit(X_train, y_train)
sig = CalibratedClassifierCV(HistGradientBoostingClassifier(random_state=0),
method="sigmoid", cv=5).fit(X_train, y_train)
for name, m in [("raw", raw), ("sigmoid", sig), ("isotonic", iso)]:
p = m.predict_proba(X_test)[:, 1]
print(f"{name:9s} brier={brier_score_loss(y_test, p):.4f} logloss={log_loss(y_test, p):.3f}")
p_raw = raw.predict_proba(X_test)[:, 1]
p_iso = iso.predict_proba(X_test)[:, 1]
for name, p in [("raw", p_raw), ("isotonic", p_iso)]:
frac_pos, mean_pred = calibration_curve(y_test, p, n_bins=5, strategy="quantile")
print(name)
for mp, fp in zip(mean_pred, frac_pos):
print(f" predicted {mp:.3f} observed {fp:.3f}")
thr = COST_FP / (COST_FP + COST_FN)
bayes_cal = FixedThresholdClassifier(iso, threshold=thr).fit(X_train, y_train)
tn, fp, fn, tp = confusion_matrix(y_test, bayes_cal.predict(X_test)).ravel()
print(f"calibrated + threshold 1/21: FN={fn} FP={fp} cost={COST_FN*fn + COST_FP*fp}")
raw brier=0.0268 logloss=0.123
sigmoid brier=0.0239 logloss=0.095
isotonic brier=0.0239 logloss=0.095
raw
predicted 0.000 observed 0.003
predicted 0.000 observed 0.007
predicted 0.001 observed 0.007
predicted 0.002 observed 0.017
predicted 0.169 observed 0.240
isotonic
predicted 0.003 observed 0.003
predicted 0.004 observed 0.006
predicted 0.009 observed 0.007
predicted 0.021 observed 0.007
predicted 0.242 observed 0.250
calibrated + threshold 1/21: FN=10 FP=176 cost=376
The reliability table is the numeric form of a reliability diagram. With strategy="quantile" each bin holds the same number of test cases (300 here), which avoids nearly empty bins when most predictions sit near zero. The raw model is overconfident: in the fourth bin it predicts 0.2% on average while 1.7% are positive, and in the top bin it predicts 16.9% against an observed 24.0%. After isotonic calibration, predicted and observed rates line up within the noise you expect from bins of 300 cases with only a handful of positives each. Log loss drops from 0.123 to 0.095.
With calibrated probabilities, the theoretical threshold of 1/21 now gives a cost of 376, close to the 353 of the directly tuned threshold. That is the practical payoff of calibration: thresholds derived from costs become meaningful, and they stay meaningful when the costs change, without retuning. Calibration barely changes the ranking (isotonic steps can create ties), and must be assessed on data not used to fit the calibrator.
Common advice for imbalanced data is to reweight classes or resample until the classes are balanced. It helps less than people expect, and it has a cost. The experiment below compares the options inside a proper 5-fold loop, plus one common mistake: oversampling before splitting.
from sklearn.base import clone
def oversample(X, y, rng):
pos = np.flatnonzero(y == 1)
extra = rng.choice(pos, size=(y == 0).sum() - len(pos), replace=True)
idx = np.concatenate([np.arange(len(y)), extra])
return X[idx], y[idx]
def evaluate(model, X, y, resample=False, leak=False, seed=0):
rng = np.random.default_rng(seed)
if leak: # WRONG: duplicate before splitting
X, y = oversample(X, y, rng)
rows = []
for tr, te in StratifiedKFold(5, shuffle=True, random_state=seed).split(X, y):
Xtr, ytr = (oversample(X[tr], y[tr], rng) if resample else (X[tr], y[tr]))
p = clone(model).fit(Xtr, ytr).predict_proba(X[te])[:, 1]
rows.append((roc_auc_score(y[te], p), average_precision_score(y[te], p),
brier_score_loss(y[te], p), p.mean()))
return np.mean(rows, axis=0)
hgb = HistGradientBoostingClassifier(random_state=0)
variants = {
"plain": (hgb, False, False),
"class_weight": (HistGradientBoostingClassifier(class_weight="balanced", random_state=0), False, False),
"oversample in fold": (hgb, True, False),
"oversample LEAKED": (hgb, False, True),
"logreg plain": (make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)), False, False),
"logreg balanced": (make_pipeline(StandardScaler(),
LogisticRegression(class_weight="balanced", max_iter=1000)), False, False),
}
print(f"{'variant':20s} ROC PR Brier mean p (true rate {y.mean():.3f})")
for name, (m, rs, lk) in variants.items():
roc, pr, br, mp = evaluate(m, X, y, resample=rs, leak=lk)
print(f"{name:20s} {roc:.3f} {pr:.3f} {br:.4f} {mp:.3f}")
variant ROC PR Brier mean p (true rate 0.055)
plain 0.918 0.698 0.0286 0.034
class_weight 0.917 0.674 0.0286 0.057
oversample in fold 0.920 0.672 0.0291 0.057
oversample LEAKED 0.999 0.999 0.0067 0.509
logreg plain 0.826 0.339 0.0432 0.055
logreg balanced 0.834 0.278 0.1628 0.339
Three lessons follow from these numbers:
Pipeline enforces.Reweighting can still help a low-capacity model that would otherwise ignore the minority class. Treat it as a hyperparameter to validate, not a default.
Every metric computed on a finite test set is an estimate. The percentile bootstrap resamples the test set with replacement, recomputes the metric many times, and reads off the 2.5th and 97.5th percentiles. For rare positives, resample within each class so every replicate contains both classes (a stratified bootstrap). For comparing two models, resample the same indices for both and bootstrap the difference: the paired design cancels out the shared difficulty of the test cases.
p_hgb, p_lr = proba["hgb"], proba["logreg"]
def bootstrap_auc(y_true, p_a, p_b=None, n_boot=2000, seed=0):
rng = np.random.default_rng(seed)
pos, neg = np.flatnonzero(y_true == 1), np.flatnonzero(y_true == 0)
out = np.empty(n_boot)
for i in range(n_boot):
# resample within each class so every replicate has both classes
idx = np.concatenate([rng.choice(pos, len(pos)), rng.choice(neg, len(neg))])
a = roc_auc_score(y_true[idx], p_a[idx])
out[i] = a if p_b is None else a - roc_auc_score(y_true[idx], p_b[idx])
return out
boot = bootstrap_auc(y_test, p_hgb)
lo, hi = np.percentile(boot, [2.5, 97.5])
print(f"HGB test AUC {roc_auc_score(y_test, p_hgb):.3f}, 95% CI [{lo:.3f}, {hi:.3f}]")
diff = bootstrap_auc(y_test, p_hgb, p_lr)
lo, hi = np.percentile(diff, [2.5, 97.5])
print(f"AUC(HGB) - AUC(LR) = {roc_auc_score(y_test, p_hgb) - roc_auc_score(y_test, p_lr):.3f}, "
f"95% CI [{lo:.3f}, {hi:.3f}]")
HGB test AUC 0.934, 95% CI [0.895, 0.966]
AUC(HGB) - AUC(LR) = 0.092, 95% CI [0.043, 0.145]
The interval for a single AUC is about 0.07 wide, again because only 83 positives drive it. The interval for the difference excludes zero, so on this test set the boosted model ranks better. This interval covers test-set sampling noise only; it treats both fitted models as fixed and ignores retraining variability.
To account for training variability as well, compare models on the same cross-validation splits and analyse the per-fold differences. A plain paired t-test over fold scores is wrong here: training sets overlap heavily between folds, so the differences are positively correlated and the test is overconfident. The Nadeau and Bengio corrected resampled t-test inflates the variance by a term that depends on the test/train size ratio:
from scipy import stats
cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=10, random_state=0)
s_hgb = cross_val_score(HistGradientBoostingClassifier(random_state=0), X, y, cv=cv, scoring="roc_auc")
s_lr = cross_val_score(make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
X, y, cv=cv, scoring="roc_auc")
def corrected_ttest(a, b, n_train, n_test):
d = a - b
k = len(d)
var = d.var(ddof=1) * (1 / k + n_test / n_train) # Nadeau & Bengio correction
t = d.mean() / np.sqrt(var)
p = 2 * stats.t.sf(abs(t), df=k - 1)
return d.mean(), t, p
n_test = len(y) // 5
mean_d, t, p = corrected_ttest(s_hgb, s_lr, len(y) - n_test, n_test)
naive_t, naive_p = stats.ttest_rel(s_hgb, s_lr)
print(f"mean diff {mean_d:.3f} corrected t={t:.2f} p={p:.2g} naive t={naive_t:.2f} p={naive_p:.2g}")
mean diff 0.094 corrected t=6.74 p=1.7e-08 naive t=24.76 p=2.3e-29
Both tests agree that the boosted model is better, but the naive test overstates the evidence by more than a factor of three in t. For closer races the difference decides the conclusion. Some rules for fair comparisons:
cv object with a fixed random_state).best_score_ as the expected performance.CalibratedClassifierCV if probabilities will be used as probabilities.TunedThresholdClassifierCV, or from C_FP / (C_FP + C_FN) on calibrated probabilities, and validate it on held-out data.Found a mistake in this tutorial? Let us know and we will fix it.