The question

An actuary has a motor book of 58,592 policies and a claim rate of 0.063968. Someone already modelled it: an earlier study built a three-rung ladder — a logistic GLM on one-hot features, the same GLM with spline terms and isotonic calibration, and a gradient-boosted tree — and wrote six keeps into its ledger, the best at an AUC of 0.664322.

That study had no measured noise floor, no sealed partition and no claims lock. So this one asks the only question worth asking about a result you inherit:

Which of those six keeps survive when the same ladder is re-run under a contract that measures its own resolution first?

It is a port, deliberately. The contract here reproduces the earlier study's training rows exactly — the same 46,873 policies, chosen by index arithmetic before the first gate — and splits its validation set in half: one half to develop on, one half sealed. Every rung is refitted unchanged. So the fitted models are the earlier study's models, and the only thing the port changes about a number is which rows it is graded on.

Three things a reader should take away, and none of them is “use gradient boosting”:

The method taught

The models here are ordinary. What the study's decisions actually turn on are two measuring instruments, and those are what this section teaches.

Two things can be wrong with a risk score, and AUC sees only one

Pick a random claimant and a random non-claimant. The AUC is the probability the model scores the claimant higher:

A \;=\; \Pr\!\left(s_i > s_j \mid y_i = 1,\, y_j = 0\right)

That is ranking, and it is all AUC measures. Now take the same model and run every score through any strictly increasing curve — halve them, square them. Concordant pairs stay concordant, so A does not move at all, while the probabilities can be off by an order of magnitude. A technical premium is a claim probability multiplied by a severity and attached policy by policy: it lives entirely in that level. A model can rank beautifully and still be unfilable.

Reweighting destroys the level; calibrating repairs it for free

Weighting the 6.4 % of claim rows up until they carry the same total weight as the rest tells the model it lives in a balanced world. For a logit model the whole effect is a shift of the intercept:

\log\frac{\pi'/(1-\pi')}{\pi/(1-\pi)} \;=\; \log\frac{w_1}{w_0}

The slopes — hence the ranking — barely move, and every fitted probability comes out far too high. Isotonic calibration goes the other way: fit the best non-decreasing staircase from score to observed frequency, which is a constrained maximum-likelihood problem,

\min_{g_1 \le g_2 \le \cdots \le g_n} \sum_{i=1}^{n} \left(y_{(i)} - g_i\right)^2

solved exactly by pool-adjacent-violators. Because the staircase never goes down it cannot reorder anything, so calibration is free in AUC terms up to the ties it creates and the cross-fitting that keeps it honest. That is the whole of “calibrate, do not reweight”, and this study measures both halves of it on the same rows.

The instrument that decides everything: a paired floor

Every claim in a ladder study has the form “rung B beat rung A by \Delta”. Re-drawing the evaluation rows moves each rung's own AUC by about ±0.017964 here — larger than most of the gaps in the ladder. But both rungs are scored on the same rows, so their errors partly cancel and the difference is better resolved than either level. How much better is an empirical question, and the paired bootstrap answers it: draw one index vector per replicate, apply it to both rungs, and take the spread of the differences.

\Delta^{(b)} = A_B\big(\mathcal{I}^{(b)}\big) - A_A\big(\mathcal{I}^{(b)}\big), \qquad d = \max\!\left(2\sigma_\Delta, \tfrac{1}{2}\operatorname{range}\right)

One draw, not two: two draws would inflate \sigma_\Delta by roughly \sqrt{2} and quietly raise the bar. The result d is the keep bar — the smallest difference this measurement can resolve.

And one formula that ran before any model did

The anchor tolerance was not chosen after seeing a residual. It came from the closed-form variance of an AUC estimate, evaluated on row counts and a class balance alone:

\widehat{\operatorname{Var}}(A) \;=\; \frac{A(1-A) + (n_1-1)(Q_1 - A^2) + (n_0-1)(Q_2 - A^2)}{n_1 n_0}

with Q_1 = A/(2-A) and Q_2 = 2A^2/(1+A). Because the development partition is one half of the earlier study's validation set, the standard deviation of the difference between the two AUCs works out at 0.011226, and twice that — 0.0225 — became the registered tolerance of three predictions, written down before the first fit.

The data story

58,592 motor policies, 45 prepared columns, a claim rate of 0.063968. The preparation is a faithful port: the 2,000-row fixture regenerated from this study's own prepare.py is byte-identical to the fixture the earlier study committed, which is how the port knows it is modelling the same table and not merely a similar one.

The war story that is still live

Seventeen is_* equipment flags plus two more binary categoricals arrive as the strings "Yes" and "No". Under this machine's pandas they report a dtype of str, not object — so a check written as dtype == "object" skips all nineteen and silently drops them from the model. That cost an ancestor campaign about two hours. Every dtype check in this framework is a value-pattern check for exactly that reason, and the clean-room auditor re-confirmed it column by column here.

The gate said NO-GO

A separate auditor, in a fresh context, reading only the contract, the preparation script and the prepared table — never the lab notebook — ran the mechanized four-row leakage audit and failed row 3:

[OK]   split-reproduces: kind=stratified reproduces deterministically from study.yaml (train=46873 development=5859 test=5860 rows)
[FAIL] duplicate-rows: 615 duplicated row-content hash(es) straddle partitions (train/development=297, train/test=310, development/test=32)
[OK]   group-overlap: N/A — split kind is not 'group'
[OK]   metric-direction[primary]: val_auc: contract direction 'higher' matches the canonical registry
[OK]   constant-chance[primary]: val_auc=0.5000 for the constant predictor (chance anchor 0.5)
[OK]   shuffled-chance[primary]: val_auc=0.5114 for the label-shuffled predictor (chance anchor 0.5)
5/6 checks passed: 1 FAIL — any FAIL is a BLOCKER at the DATA gate

Read the last two [OK] lines first: that is the negative control, and it fired correctly. A constant predictor and a label-shuffled predictor both score at chance. A pipeline that cannot score chance at chance cannot be trusted with 0.664051.

Now the failure. 0.051203 of development rows and 0.053242 of sealed rows are byte-identical twins — all 45 columns, target included — of a row in training. The cause is structural: with 22 region codes, 11 vehicle models and 17 binary flags, the rating space is coarse enough that identical rows recur.

Overridden, not fixed — and why that is not the easy way out

Both available fixes (dedupe, or a split grouped on the row-content hash) change which rows are trained on, which destroys the one identity this port is built on and repairs nothing about the number being reproduced. And for a rating model the modelling unit is the cell, not the policy: two policies with identical rating characteristics are supposed to be priced alike, and policy_id — the only identifier of an individual policy — is dropped and crosses nothing.

So the gate was overridden on the record, the card still says NO-GO, and the risk was carried with a number attached. Every run from that point prints its AUC restricted to the evaluation rows with no twin among the rows it was fitted on. The measured answer, four rungs later: at most 0.001415 of AUC, and three of the four development rungs score higher without the twins. The same table also measured the earlier study's own validation partition — 0.052223 of it carried a training twin, and nobody had ever looked.

The experiment journey

Phase 0: measure the instrument before using it

Three recipes, three estimands, and they disagree by four orders of magnitude. That spread is the whole reason the framework refuses to let a study guess its keep bar.

That bar is 0.9671 of the distance from the earlier study's worst recorded model to its best. Before a single candidate ran, the ladder was already known to be almost entirely inside its own measurement error.

The four development runs, and the one sealed run

Tracks: primary — val_auc (higher is better)

ExpTrackKindMetricStatusDescription
E0001primarydevelopment0.61414keepE0001 anchor: the v1 split-identity rung (LR + OHE(min_frequency=20) + class_weight=balanced) refitted on the identical v1 training rows; decides P1; first valid result on this track
E0002primarydevelopment0.650095discardE0002 spline+isotonic: the v1 E2-redux chain (quantile-knot splines on 3 numerics, log1p density, 2 interactions, isotonic cv=5) against the anchor refitted on the same rows; decides P2 and P3; did not improve track frontier 0.61414 by minimum_delta=0.0375805
E0003primarydevelopment0.664051keepE0003 HGBT: the v1 tree rung (learning_rate 0.05, 500 iters, 31 leaves, class_weight=balanced, early stopping), the only rung recoverable verbatim from a committed file, against the calibrated GLM refitted on the same rows; decides P4 and P5; frontier improvement over 0.61414 with minimum_delta=0.0375805
E0004primarydevelopment0.612675discardE0004 doctrine A/B: the anchor with class_weight=None plus isotonic calibration (cv=5) against the same rung with class_weight=balanced refitted on the same rows; decides P6; did not improve track frontier 0.664051 by minimum_delta=0.0375805
E0005primaryfinal_test0.657739discardE0005 sealed confirmation: E0003's configuration unchanged, fitted on train+development and evaluated once on the sealed half of the v1 validation set; decides P7; sealed final-test evidence; excluded from the adaptive frontier

Read the ledger with the floor in hand:

Decision trajectory: two keeps, three non-keeps, the sealed run marked separately, with the measured floor band around the frontier.
The primary track's ledger as the notary recorded it — development keeps stepping the frontier line, discards left as retained-evidence dots, the sealed final test drawn as a star and excluded from the frontier — with the declared keep bar and the paired noise floor shaded around it. Read the bands, not the dots: after the anchor keep the frontier steps exactly once, and every other gap in the ladder is narrower than the band that prices it. Close

The picture the study is really about

Every gap the ladder measured, drawn twice: in metric units against the declared bar, and divided by the floor that actually prices each comparison. Both panels are zero-based.

Left: each comparison's absolute lift and its own pair's floor, against the declared bar. Right: the same gaps in floors, with the one-floor line drawn.
Every rung-to-rung comparison on the primary track's development partition, drawn twice on zero-based axes: left in val_auc units against the declared bar, right divided by the declared floor and by each pair's own floor. Which floor prices a gap decides its verdict — the splines rung stands at 0.9568 of the declared bar and 1.0926 of its own pair's floor, refuted against the first and supported against the second. Close

The right panel is where the honesty lives. The spline rung sits at 0.9568 of the declared bar — refuted — and at 1.0926 of the floor of the comparison it actually makes, where it would have been supported. The registered verdict stands, because a bar chosen after the measurement is not a bar; but that refutation is instrument-limited, and the study had pre-committed to saying so.

Then the seal

Fitted on train plus development, evaluated once on the sealed half: 0.657739 against a development score of 0.664051 — a shift of 0.1680 of one floor. The level held. What did not hold was the top-decile lift, which fell 0.5101, from 2.2167 to 1.7067, at a claim rate of 0.063968: a decile rests on a tenth of the rows, and it is a far noisier statistic than the AUC computed beside it.

Decile lift for the frontier incumbent on the development partition, bars from zero.
Lift over the portfolio claim rate by predicted-probability decile for the frontier incumbent on the primary track's development partition, bars from zero against the no-lift line. The top decile reaches 2.2167 here and 1.7067 on the sealed rows — a decile rests on a tenth of the rows, so size a triage list from a sealed number rather than from this one. Close

Finally klein replicate re-executed the kept run in a detached worktree and reproduced it exactly, difference 0.

Findings & insights

The ladder reproduced; the keeps did not

All three rungs land inside the tolerance that was derived before any fit — residuals of 0.011322, 0.001612 and 0.001154 against 0.0225. The models port. What does not port is the verdict: under a measured bar the same ladder yields exactly one frontier improvement instead of six keeps, and the earlier study's sixth row — a learning-rate sweep recorded as a keep on an AUC lift of 0.001425 — is 0.0379 of one floor. Under a measured bar it is a discard.

Prose that names its kwargs is nearly as good as a commit

One rung was recoverable verbatim from a committed file; two survived only as prose. But that prose named its three non-default constructor arguments, because the earlier study had made naming them its own parting advice. The verbatim rung reproduces to 0.001154 and the prose rung to 0.001612: the whole advantage of having the code is 0.000458 of AUC. That is a stronger endorsement of the advice than the prior that predicted it.

Calibration is cheap and enormous; rank is expensive and invisible

Reliability diagram for the frontier incumbent: predicted probability against observed frequency by bin.
Mean predicted probability against observed claim rate over ten quantile bins for the frontier incumbent on the primary track's development partition, with perfect calibration as the diagonal. Every bin sits far below the line: balanced class weighting inflates the whole level while leaving the ranking intact, which is precisely why the insurance doctrine calibrates rather than reweights. Close

Replacing balanced class weighting with unweighted fitting plus a cross-fitted isotonic wrapper improves the Brier score by a factor of 4.055, from 0.240641 to 0.059337, and pays 0.001465 of AUC — 0.0390 of one floor, one twenty-fifth of the smallest difference this study can resolve. Meanwhile the tree that ranks best carries a Brier score worse by a factor of 3.789 than the calibrated GLM, and its rank advantage over that GLM is 0.3714 of a floor. Rank and level are not two views of one quantity; they are two currencies, and the exchange rate here is brutal.

The profile's rank views of the same incumbent, for completeness: the ROC curve the primary metric integrates, and the precision-recall curve, which is the harder read at a claim rate of 0.063968 and the one that shows how little of the book any model can pick out with confidence.

ROC curve for the frontier incumbent on the development partition, with the chance diagonal.
True-positive against false-positive rate for the same incumbent on the same primary development rows, with the chance diagonal — the curve the primary metric integrates. It is the rank view and blind to the level by construction: run every score through any increasing curve and this picture does not move. Close
Precision-recall curve for the frontier incumbent on the development partition.
Precision against recall for the same incumbent on the same primary development rows, against the flat line a random ranker would hold at a claim rate of 0.063968. Precision never rises far above that line at any recall — that is how little of a book at this claim rate any of these rungs can pick out with confidence. Close
Lorenz curves for all three rungs on the development partition, each with its Gini in the legend.
Share of realised claims against share of policies ordered from lowest predicted risk, for all three rungs on the primary track's development partition, with each rung's Gini in the legend and the no-discrimination diagonal. The calibrated GLM and the boosted tree trace nearly the same curve — the pricing-side reading of a rank gap of 0.3714 of a floor, which the measured bar cannot resolve. Close

Four surprises, each with a mechanism

What a sealed access can confirm

The incumbent's level on the sealed partition is what this design can confirm; a rung-to-rung gap is not, because one track gets one sealed access, and that confirms a level, never a difference. So every rung-to-rung gap on this page is development evidence and is exploratory by construction, which the plan registered before the first run rather than discovering afterwards.

What the records say

claims
12 locked in claims.lock
by strength
confirmed 1 · exploratory 11
by class
empirical-description 7 · mechanism-interpretation 1 · procedural-verdict 2 · research-discipline 2
errata
0 of 12 claims tagged · 0 erratum record(s) in the lock
locked at
f54ee1afa657 · klein 2.0.0
label
confirmed
referee
PASS-WITH-NOTES — klein-referee (Claude Code subagent, model: claude-opus-5[1m]) · independent of the experimenter: no

Model coding advice

Here is the entire per-candidate surface of this study — the actual bytes, included by reference so this page cannot drift from the code that produced the numbers above. Read the four constants under “the candidate” first. That block is an experiment; everything else is machinery that a per-experiment edit is not allowed to touch.

train.py · executed by E0003 (development, track primary) at commit c846660d73b1 · sha256 783421a41a05…
"""The only per-candidate mutable surface in this study.

The per-experiment diff is the four constants under "the candidate" — ``CANDIDATE``
(the rung being tried), ``REFERENCE`` (the rung it claims to beat, refitted on the same
rows in this same process), ``V1_ANCHOR`` (the value the v1 ledger recorded for this
rung, or ``None``) and ``DEV_INCUMBENT`` (set only for the sealed run) — and nothing
else. The rung definitions live in ``lib/rungs.py``, which is stable study library code:
a per-experiment edit must not be able to change what Phase 0 measured its floor on.

What every run prints, on top of the canonical block
---------------------------------------------------
Nothing here is a literal a later reader must trust: the floor comes from the contract,
the anchor comes from the v1 ledger transcribed in ``scouting_ledger.md``, and the
reference rung is refitted on the SAME evaluation rows so a comparison lives inside one
printed block instead of being subtracted across two log files.

============================ =================================================
``rung``                     which rung this run is
``v1_anchor``                what the v1 study recorded for this rung, on its
                             own (two-way) partition
``anchor_gap``               ``val_auc - v1_anchor`` — the transfer residual
``reference_rung``           the rung refitted here for comparison
``reference_auc``            that rung's AUC on these same rows
``delta_vs_reference``       ``val_auc - reference_auc`` (a PAIRED difference)
``delta_in_floors``          that difference in units of the contract's
                             ``minimum_delta`` — the number P3, P5 and P6 read
``reference_brier``          the reference rung's Brier score on these rows
``brier_delta_vs_reference`` candidate Brier minus reference Brier; negative
                             means better-calibrated
``dev_incumbent``            (sealed run only) the development incumbent's score
``sealed_shift_in_floors``   (sealed run only) the sealed score's distance from
                             that incumbent, in floors
``twin_free_rows``           evaluation rows with NO byte-identical twin among the
                             rows this run was fitted on
``twin_free_auc``            the AUC on exactly those rows
``twin_free_gap``            ``twin_free_auc - val_auc`` — how much of the headline
                             number the duplicated rows were worth
============================ =================================================

The last three exist because the DATA gate FAILED this study on duplicate row content
straddling the partitions and the gate was overridden rather than fixed (`program.md`,
2026-09-03; `data_card.md` BLOCKER #1). An accepted risk that is never measured is an
excuse, so every run measures it. ``primary_metric`` deliberately stays the
full-partition AUC: the registered anchors compare against v1 values computed the same
contaminated way, and re-defining the measurement would make that comparison
meaningless.

``delta_in_floors`` and ``sealed_shift_in_floors`` are printed only once the contract
carries a measured ``minimum_delta``. Before Phase 0 sets it there is no floor to divide
by, and a prediction whose key is not printed is INCONCLUSIVE rather than refuted, which
is the honest answer.
"""

from __future__ import annotations

import os
import time

from sklearn.metrics import brier_score_loss, roc_auc_score

import kleinlib
from kleinlib.contract import load_contract
from kleinlib.data import load_partition
from lib.duplicate_exposure import duplicate_free_mask
from lib.rungs import fit_rung, positive_probabilities

SMOKE = os.environ.get("KLEIN_SMOKE") == "1"
EXPERIMENT_ID = os.environ.get("KLEIN_EXPERIMENT_ID") or ("SMOKE" if SMOKE else None)
TRACK = os.environ.get("KLEIN_TRACK") or ("primary" if SMOKE else None)

# --- the candidate: the whole per-experiment diff surface -------------------
# Empty between experiments. Choosing a rung IS the falsifiable idea a candidate
# transaction carries, so the surface carries no rung until one is chosen.
CANDIDATE = "hgbt_balanced"          # E0003: the v1 tree rung, recoverable verbatim
REFERENCE = "glm_splines_isotonic"   # the calibrated GLM rung it claims to beat
V1_ANCHOR = 0.662897                 # scouting_ledger.md S1, v1 results.tsv row 3
DEV_INCUMBENT = None             # set only for the sealed confirmation run


def main() -> None:
    t0 = time.time()
    evaluation_kind = os.environ.get("KLEIN_EVALUATION_KIND")
    if SMOKE:
        evaluation_kind = evaluation_kind or "development"
    missing = [
        name
        for name, value in (
            ("KLEIN_EVALUATION_KIND", evaluation_kind),
            ("KLEIN_EXPERIMENT_ID", EXPERIMENT_ID),
            ("KLEIN_TRACK", TRACK),
        )
        if value is None
    ]
    if missing:
        raise RuntimeError(
            "train.py must be invoked through `klein run-one`. For a pre-run "
            "syntax/shape check use `KLEIN_SMOKE=1 python train.py` — it prints the "
            "canonical block, writes no sidecars or snapshots, and is not evidence. "
            "Missing: " + ", ".join(missing)
        )

    if CANDIDATE is None:
        raise RuntimeError(
            "no rung is chosen: set CANDIDATE to a key of lib.rungs.RECIPES. The "
            "surface is empty between experiments on purpose — choosing the rung is "
            "the one falsifiable idea a candidate transaction carries."
        )

    X_fit, X_eval, y_fit, y_eval = load_partition(evaluation_kind, study_dir=".")
    minimum_delta = float(
        load_contract(".")["tracks"][TRACK]["metric"].get("minimum_delta") or 0.0
    )

    fit_start = time.time()
    model, _, X_eval_t = fit_rung(CANDIDATE, X_fit, X_eval, y_fit)
    fit_seconds = time.time() - fit_start

    probabilities = positive_probabilities(model, X_eval_t)
    candidate_auc = float(roc_auc_score(y_eval, probabilities))
    candidate_brier = float(brier_score_loss(y_eval, probabilities))

    # The overridden DATA-gate BLOCKER, measured on this run's own rows.
    twin_free = duplicate_free_mask(X_fit, y_fit, X_eval, y_eval)
    twin_free_auc = float(roc_auc_score(y_eval[twin_free], probabilities[twin_free]))

    extra: dict[str, str] = {
        "rung": CANDIDATE,
        "twin_free_rows": str(int(twin_free.sum())),
        "twin_free_auc": f"{twin_free_auc:.6f}",
        "twin_free_gap": f"{twin_free_auc - candidate_auc:.6f}",
    }
    if V1_ANCHOR is not None:
        extra["v1_anchor"] = f"{V1_ANCHOR:.6f}"
        extra["anchor_gap"] = f"{candidate_auc - V1_ANCHOR:.6f}"
    if REFERENCE is not None:
        reference_model, _, X_reference_eval = fit_rung(REFERENCE, X_fit, X_eval, y_fit)
        reference_probabilities = positive_probabilities(reference_model, X_reference_eval)
        reference_auc = float(roc_auc_score(y_eval, reference_probabilities))
        reference_brier = float(brier_score_loss(y_eval, reference_probabilities))
        extra["reference_rung"] = REFERENCE
        extra["reference_auc"] = f"{reference_auc:.6f}"
        extra["delta_vs_reference"] = f"{candidate_auc - reference_auc:.6f}"
        extra["reference_brier"] = f"{reference_brier:.6f}"
        extra["brier_delta_vs_reference"] = f"{candidate_brier - reference_brier:.6f}"
        if minimum_delta > 0:
            extra["delta_in_floors"] = f"{(candidate_auc - reference_auc) / minimum_delta:.4f}"
    if DEV_INCUMBENT is not None:
        extra["dev_incumbent"] = f"{DEV_INCUMBENT:.6f}"
        if minimum_delta > 0:
            extra["sealed_shift_in_floors"] = (
                f"{(candidate_auc - DEV_INCUMBENT) / minimum_delta:.4f}"
            )

    kleinlib.eval.evaluate(
        model,
        X_eval_t,
        y_eval,
        exp_id=EXPERIMENT_ID,
        study_dir=".",
        t0=t0,
        fit_seconds=fit_seconds,
        train_n=len(X_fit),
        val_n=len(X_eval),
        metric_name="val_auc",
        metric_goal="higher",
        extra=extra,
    )


if __name__ == "__main__":
    main()

Six things worth stealing

Pitfalls this study actually hit

Next steps + references

What to try next, in priority order

  1. Give each model family its own track. The one question this study could not answer — is the calibrated GLM's rank shortfall real? — needs the gap to be a difference of two sealed numbers, and one track gets one seal. Two tracks declared at the consult gate is the single highest-information change to this design.
  2. Re-measure the floor on a larger development partition. The bar here is 0.0375805 on 5859 rows. Doubling the development partition roughly halves the sampling variance — at the cost of the training-row identity with the earlier study, which is the trade this study made in the other direction and recorded.
  3. Test the duplicate-row question instead of bounding it. Fit on a deduplicated training partition and evaluate on the same development rows. This study bounded the effect at 0.001415 without ever separating “the duplicates do not help” from “these models cannot exploit them”.
  4. Threshold tuning, with a decile-stability measurement. The doctrine is unweighted fitting plus isotonic calibration plus threshold tuning, and only the first two were tested here. The sealed drop of 0.5101 in top-decile lift says the third deserves its own registered measurement rather than an assumption.

What an actuary should carry away

Calibration first: on this book a filable probability is available at a rank cost the measurement cannot resolve. Balanced class weighting should not reach a rate filing — it costs a factor of 4.055 on Brier and buys 0.0390 of a floor. And a fourth decimal of AUC is not a rate change: nothing here is priced, no materiality block is registered, so the honest statement is simply that the registered keep-sized bar was not cleared.

Verified references

Every entry was checked against its publisher, arXiv or proceedings page on the date recorded in references.yaml; none is unverified.