The Question
A pricing actuary on a French motor third-party liability book has a boosted model that scores better than the filed GLM. Everyone knows this. The question that actually reaches a committee is narrower and harder:
How much accuracy are we giving up by filing the interpretable model — and is that number real, or is it an artefact of the fold we happened to measure it on?
This study answers it three ways at once. Its goal statement:
On freMTPL2 claim frequency, WHERE does a gradient-boosted model's Poisson-deviance advantage over a spline-shaped GLM live, how much of it transfers back into GLM-representable structure, and does the gap itself survive two sealed final-test evaluations?
Why "two sealed evaluations" is the whole design
Klein studies seal a final-test partition and allow each research track exactly one access to it. Everything else — every candidate, every discard, every tuning decision — happens on train and development only. The sealed number is therefore an honest out-of-sample confirmation rather than the last of many peeks.
Its predecessor, study 04, ran a single track. It could seal the level of one model, but the GLM→GBDT gap was still a development quantity, and it filed a protocol caveat saying so. This study splits the work into two tracks with independent frontiers:
glm— the interpretable family: OHE anchor, column-scoped splines, surrogate-derived interaction products.gbdt— the black box: sklearn HGBT, LightGBM, CatBoost, and a monotone-constrained filability probe.
Each track selects its own incumbent adaptively on development, then spends its one sealed access on that incumbent. The headline gap becomes a difference of two sealed numbers — neither of which was chosen after looking at the sealed fold. That is the protocol contribution, and it is what closes study 04's caveat.
The two tracks are never merged into one leaderboard. Each owns its metric contract,
its measured minimum_delta, and its guardrails:
| Track | Metric | Direction | minimum_delta | Guardrail |
|---|---|---|---|---|
glm | val_poisson_deviance | lower is better | 0.000539 | wall_seconds ≤ 400 |
gbdt | val_poisson_deviance | lower is better | 0.000573 | wall_seconds ≤ 400 |
Both minimum_delta values were measured, not guessed
— section 2 explains how, and why the floor that governs the headline gap is a
third number entirely.
The seven research questions
Each was registered with a prior before the loop ran, so each could come out wrong. Several did.
| RQ | Question | Registered prior |
|---|---|---|
| RQ1 | Does the gap survive as a difference of two SEALED test numbers, within 2 paired-bootstrap SEs of the development gap (0.010172)? | Yes — study 04's level replicated at 0.65× fold SE; the gap should too |
| RQ2 | Is LightGBM-Poisson within 2× the gbdt floor of sklearn HGBT at matched capacity? | Yes, a tie (knowledge/gbdt-tabular.md) |
| RQ3 | Does CatBoost's ordered-target-statistics package beat OHE-HGBT at cardinality ≤ 22? | No — study 04 found native-vs-OHE a 0.37×-floor tie here |
| RQ4 | With column-SCOPED splines, what fraction of the gap does additive shaping close? | 30–45%, up from study 04's leaky 18% |
| RQ5 | How much of the residual gap do the top surrogate-derived interactions recover? | A further 20–30% (uninformed) |
| RQ6 | At what training-set size does the gap fall below 2× the paired floor? | ~10–15% of train, 40–60k rows (uninformed) |
| RQ7 | Does a monotone BonusMalus constraint cost more than 1× the gbdt floor? | No — "filability is nearly free" (knowledge/glm-pricing.md) |
RQ1 is the estimand. RQ4–RQ5 are the translate-back programme: can the black box's advantage be handed back to a filable model? RQ6 asks whether the whole question is even live at your portfolio's size. RQ7 prices the regulator's shape guarantee. RQ2–RQ3 clear the ground so no one can attribute the gap to a library choice.
The Method
Four things had to be taught before a single number could be believed: what the metric is, what "different" means on it, how to interrogate a black box for structure, and what a shape constraint actually constrains.
1. The metric — and why exposure is a weight, not an offset
The response is a rate: , claims divided by exposure-years, with the exposure serving as the fitting and scoring weight. Every model on both tracks is driven that way — no per-library offset plumbing anywhere.
Unit Poisson deviance — the per-row loss:
Fold deviance — the exposure-weighted mean across the fold ():
The gap — positive means GBDT is better:
That the exposure-weighted rate form is identical to the textbook offset form is the load-bearing step, so the method card derives it rather than citing it:
Substitute and drop the θ-free terms:
And:
…whose θ-dependent part is:
Hence:
Left: the count likelihood with offset . Right: the exposure-weighted rate deviance.
Both give the same score equation:
For a GBDT the equality holds at the level of the loss and its gradients, so
it propagates into every split gain and every leaf value. This is why
PoissonRegressor, HistGradientBoostingRegressor,
LGBMRegressor(objective="poisson") and CatBoostRegressor(loss_function="Poisson")
can all be handed the identical (y_rate, sample_weight=Exposure) pair and
still be comparing like with like. One caveat worth carrying into a filing memo: the
equivalence is for the fitted function; dispersion-based standard errors differ
unless φ is handled consistently. Irrelevant here — the metric is a deviance,
not a Wald test.
2. Three floors, not one — the metrology that governs every verdict
A delta is only evidence if it exceeds the noise of the comparison that produced it. This study measured four distinct floors and they differ by more than a factor of four. Getting this wrong is the single most common way a gap becomes a fiction.
| Floor | Value | What it governs |
|---|---|---|
| glm fit-seed std (k = 5) | exactly 0 | nothing — PoissonRegressor is deterministic. The degenerate value IS a finding: quoting a seed floor for a GLM is meaningless. |
| gbdt fit-seed std (k = 5) | 0.000210 | HGBT re-fit reproducibility only |
| glm paired-bootstrap SE (B = 1000, CRN) | 0.000270 → minimum_delta 0.000539 | within-glm-track comparisons |
| gbdt paired-bootstrap SE (B = 1000, CRN) | 0.000287 → minimum_delta 0.000573 | within-gbdt-track comparisons |
| cross-track paired SE (development) | 0.000963 | the headline GLM↔GBDT gap on development |
| cross-track paired SE (sealed) | 0.001028 | the headline gap on the sealed test |
Why the paired floor is the one that governs. A seed floor asks "if I re-fit this model, how much does its score move?" — which says nothing about whether two different models differ. The paired bootstrap asks the right question: resample the evaluation rows once with common random numbers, score both models on the same resample, and take the standard deviation of the difference across B = 1000 draws. Shared row-level noise cancels; only the disagreement between the models survives. Bootstrapping the two levels separately and differencing their SEs would overstate the comparison noise several-fold.
Note the asymmetry that follows: the cross-track SE (0.000963) is 4.6×
the GBDT seed floor and is the only one of the four that legitimately
bands the headline gap. It is an uncertainty band, not a
minimum_delta — it never gates a keep/discard decision. Track
frontiers are gated by the within-track deltas; the gap is reported against the
cross-track SE.
3. The forensics instruments — how to ask a black box where
Three tools, all off-ledger (descriptive analysis, never evidence), all reading artifacts the sanctioned loop already produced.
M4 — train-fold surrogate distillation
Knowledge distillation trains a small student on a big teacher's outputs. Here the machinery is repurposed as a measurement instrument, and that changes how you read it:
The GBDT's log-prediction surface is a smooth function of the rating factors. Fit a GLM-shaped surrogate — main effects only, in a basis the real GLM could actually use — to that surface. Whatever the surrogate cannot reproduce is, by construction, the part of the teacher's structure that is not representable as GLM main effects. Correlate that residual against candidate two-way products and the largest correlations name which interactions the GBDT found.
Teacher's log-score (train fold only):
Main-effects surrogate — a per-column cubic basis , fit by weighted least squares:
is the weighted correlation between the standardised product column and the residual. Five numeric factors give C(5,2) = 10 candidate pairs; rank them, promote the top-K into the real GLM as design-matrix columns, and measure development deviance. The instrument and the intervention are the same object — the column that scored highest IS the column you add, so a screening hit is immediately falsifiable by one refit.
Three properties make this a screen rather than a fishing expedition:
- It never touches evaluation labels. The surrogate's target is the
teacher's train-fold predictions, not
y. Derivation lives entirely inside train; development is spent only on the adopt/reject decision; the sealed fold confirms. - Multiplicity is fixed in advance and published. 10 screened, at most 2 adopted, both counts reported either way. A screen you report is a screen; a screen you hide is p-hacking.
- is itself a headline number. It answers RQ5's real question — is the gap an interaction gap at all? — before a single interaction is adopted.
Read it correctly. lives on the log-score surface, not on deviance. It is a diagnostic, not a bound on recoverable deviance. A high value with a stubborn gap would have meant the gap lives in basis/knot curvature the scoped splines do not span — a different, equally reportable answer.
M4 cross-check — the manual two-way partial dependence
A single instrument that names an interaction is a hypothesis; two instruments agreeing is evidence. The cross-check is model-agnostic and computed by hand on the log scale (GLM additivity is log-scale additivity):
All surfaces mean-centred, on an 8×8 quantile grid, evaluated on .
If a pair is genuinely additive, the 2-D partial-dependence surface equals the sum of the two 1-D curves and the residual surface is flat. Its standard deviation is the pair's non-additivity in log-rate units. A pair is adopted only if the surrogate ranking and the PD signature agree on it.
M5 — segment deviance decomposition
The weighted deviance is a sum of per-row contributions, so any disjoint partition of the evaluation rows partitions the total exactly — no cross terms, no residual, nothing approximated:
That identity is what converts a leaderboard row into a WHERE answer. "72% of the gap sits in three segments covering 11% of exposure" is a completely different business story from "the gap is spread evenly across the book" — and both produce the same headline number. Discipline: individual may be negative (segments where the GLM wins), so shares can exceed 1; always print each segment's exposure share next to its gap share, or a 1%-exposure segment will look decisive when it is noise.
4. Monotone constraints — and the distinction that explains their price
A monotone constraint is not a post-hoc smoothing. It is enforced inside split finding: every node carries a value band inherited from its ancestors, and a split on the constrained feature is admissible only if
The children's bands are tightened so the ordering can never be undone deeper in the tree.
Additive stagewise composition preserves the property, so the whole ensemble inherits the guarantee scikit-learn states as .
Read that guarantee slowly, because it is the entire finding of RQ7. It is quantified over every value of — i.e. monotonicity is enforced pointwise in every conditioning context, not on the marginal curve. So:
Marginal monotonicity does not imply conditional monotonicity, and it is the conditional version the library enforces.
A factor can be perfectly non-decreasing when you plot mean frequency against it, and the constraint can still be expensive — because it forbids the model from letting that factor's slope vary with another factor. Section 5 shows exactly that happening, for exactly the reason the surrogate screen predicted.
Encoding note: +1 increase, 0 unconstrained, -1
decrease, one entry per input feature. Categorical features cannot be
constrained (categories are unordered), so hgbt_monotone puts 0
on every categorical position and +1 on BonusMalus only — which is why
that config also switches to the native-categorical encoder, and why RQ7 needed a
same-encoding control.
The Data
freMTPL2 — French motor third-party liability claim counts, the
standard actuarial benchmark. Prepared once, then frozen byte-for-byte to
study 04 so both studies' anchors stay comparable (prepared SHA-256
db82e802…1cf948, verified by hash identity against the reference cell,
not by re-running prep).
| Property | Value |
|---|---|
| Rows × columns | 678,013 × 12 |
| Target | ClaimNb (mean 0.038946 claims/row; 96.321% zero-claim) |
| Exposure-weighted frequency | 26,406 / 358,360.11 = 0.073686 claims per exposure-year |
| Modelled response | ClaimNb / Exposure, with Exposure as the Poisson sample weight |
| Features | 9 — 5 numeric (VehPower, VehAge, DrivAge, BonusMalus, Density) + 4 categorical (Area, VehBrand, VehGas, Region) |
| Split | random 60/20/20 at seed 42 → train 406,807 / development 135,603 / sealed test 135,603 |
| Null (intercept-only) dev deviance | 0.473037 — the split-identity anchor re-asserted on every run |
The value-pattern gotchas (checked against raw tokens, never dtypes)
Klein's standing war story is that dtype == "object" checks lie under
pandas string dtypes, so the audit reads raw CSV tokens with
dtype=str, na_filter=False. All 12 columns, by value:
VehGasis a two-level string binary — exactly{Regular: 345,877, Diesel: 332,136}. NotYes/No, not0/1. This is the exact shape that silently skipped categorical handling in the ancestor campaign. It is listed inpipeline.CATEGORICAL, so OHE picks it up — no dtype-based skip.VehBrandandRegionare digits-inside-strings (B12,R24). They must never be coerced to numbers.Densityhas a real censoring ceiling — 10,515 rows (1.55%) pinned at exactly 27,000, so p99 == max. A genuine ceiling in the source, not a sentinel; never treat it as missing. Skew 4.65 → 0.05 afterlog1p, which is why the shaped GLM configs log it first.- The
SENTINELregex fired twice and both were false positives — the substring999inside legitimateIDpol/Densityintegers, and the letterFas anArealevel. Dismissed by inspecting the full value sets. IDpolis a perfect row identifier (678,013 unique, monotone increasing, r = −0.0396 with the target). Structurally excluded —Xis built from the 9 modelled columns only.- The exposure lower clip silently binds. 1,060 rows sit at exactly
repr(1/365.25)— the 19-decimal fingerprint ofprepare.py's clip — while the hygiene counter reports 0, because it only counts rows outside (0, 1]. Recorded, not fixed: prep is frozen. - The
ClaimNbcap at 4 is a no-op here. 0 rows exceed 4 pre-clip; 13 rows sit at the cap. The hub table arrives already capped — the guard is inherited, not applied. - Zero missing values, zero whitespace padding, zero mixed-type columns, zero true sentinels.
The dominant caveat: feature-profile twins straddle the split
The 9 modelled features repeat heavily — 528,765 distinct profiles over 678,013 rows. Under the seed-42 split, 31,798 profile groups span train and development, so:
26.54% of development rows (35,985 / 135,603) and 26.37% of sealed-test rows have a feature-identical twin in the train fold.
These are not full-row duplicates — IDpol is unique and
Exposure varies, so the mechanized duplicate-row check correctly passes.
They are policies with identical rating characteristics. The decision was to
record, not fix: deduplicating or switching to a group split would break
the 0.454861 / 0.444689 anchors and destroy cross-study comparability.
This is exactly why the study's standing directive is report the GAP, never the levels. Both tracks consume identical contamination, so the GLM↔GBDT difference — the actual estimand — is unbiased by it; what is optimistic is every absolute deviance versus a fresh portfolio. The upside is also bounded: twin rows are claim-poor (1.97% claim-bearing among the dev twins vs 3.68% overall).
The other reason levels lie: the folds are not identically frequent
Exposure-weighted frequency by partition:
train 0.073900 development 0.072375 sealed test 0.074350
A model calibrated on train therefore must over-predict development by 0.073900 / 0.072375 = 1.021 and under-predict the sealed test by 0.073900 / 0.074350 = 0.994 — before any question of model quality. Hold that thought; section 5 shows it explaining an apparent calibration finding almost exactly.
The clean-room leakage audit — and the leak that was already removed
Performed in a fresh context reading only study.yaml,
prepare.py, pipeline.py, the prepared artifact and the profile
— program.md and every other study's files stayed closed. Rows 3–4
are mechanized: 9/9 checks passed: clean.
The most instructive row is target leakage. prepare.py's
RAW_KEEP is an allowlist, not a denylist: it admits exactly
12 canonical raw columns and drops 46 hub columns — including the
hub's derived Frequency column, which is the target in disguise. Verified by
value rather than by trusting the code, and quantified as a contrast:
| Column | Correlation with ClaimNb | Reading |
|---|---|---|
the dropped Frequency (if it had survived) | +0.3055 (and +1.0000 with the modelled rate) | the leak signature |
BonusMalus — the strongest surviving feature | +0.0667 | two orders of magnitude away from a leak |
BonusMalus is also legitimate ex ante: the coefficient is fixed from prior years' experience at renewal, so it cannot encode this period's claims. The eval harness was sanity-checked too — the constant predictor scores 0.2554 and the label-shuffled predictor 1.5327 (glm) / 1.5296 (gbdt), both no-information baselines, with the metric direction matching the contract on both tracks.
Go / no-go
Decision: GO-WITH-CAUTIONS. No BLOCKER open. Three WARNs carried forward as standing directives: (1) report the gap, never the levels; (2) derive interaction pairs from a train-fold surrogate only — the pairs are a caller-supplied argument, which is the one live lookahead surface no static check can catch; (3) never filter the 365× rate tail — exposure weighting already down-weights a one-day policy to 1/365 of a full-year policy.
One structural limitation the card flags for the findings: the prepared artifact has no time column, so a temporal split is impossible and the frozen random split is the only realizable design. Every conclusion here is an in-period statement about this portfolio, not a forward-in-time generalization.
The Journey
Twelve ledger rows across two tracks and four phases, every one still resolvable to the exact code that produced it — the loop commits each candidate before it runs, so discards and crashes stay as resolvable as keeps. Every phase finished far inside its budget — the entire study is well under a minute of compute.
| Phase | Experiments (used/max) | Seconds (used/budget) | What it was for |
|---|---|---|---|
adaptive-1 | 3 / 3 | 8.9 / 1800 | anchors + the three metrology sweeps |
adaptive-2 | 5 / 5 | 18.0 / 3600 | the forensics ladder: libraries, splines, interactions |
adaptive-3 | 2 / 3 | 5.5 / 2400 | post-forensics redirect: monotone cost, matched capacity |
confirmation | 2 / 2 | 6.9 / 900 | one sealed final-test access per track |
Two tracks, two frontiers
Each track's development frontier is a step function of keeps; discards sit below or above it as retained evidence; the purple star is that track's single sealed final-test access, deliberately drawn off the frontier because sealed evidence is excluded from adaptive selection.
glm track. One real frontier step (E0002 → E0004),
then two interaction candidates that land inside the shaded
minimum_delta band — visibly sub-floor, therefore discards.gbdt track. The anchor was never beaten: LightGBM
(E0005, E0010) ties inside the floor bands, CatBoost (E0006) and the monotone constraint
(E0009) sit clearly above. A flat frontier with four informative discards is a
result, not a failure.| Exp | Metric | Status | Description |
|---|---|---|---|
| E0001 | 0.454861 | discard | GLM-OHE anchor (intentional replication of the committed baseline config): the v0.4.0 registry val_poisson_deviance reproduces study-04's hand-rolled 0.454861 to 1e-9 on identical prep/split; any mismatch means split/weight/clip drift - STOP; guardrails failed: guardrail metric 'wall_seconds' missing |
| E0002 | 0.454861 | keep | GLM-OHE anchor rerun after F1 harness fix (wall_seconds now printed via extra): registry val_poisson_deviance must reproduce study-04's 0.454861 to 1e-9 - STOP on mismatch; first valid result on this track |
| E0003 | 0.444689 | keep | HGBT-OHE anchor (seed 0, lr 0.1, 200 iters, 31 leaves): registry val_poisson_deviance must reproduce study-04's 0.444689 to 1e-9; effective_trees logged per method-card R1 (early_stopping auto engages >10k rows); first valid result on this track |
| E0004 | 0.453156 | keep | RQ4: column-SCOPED splines (DrivAge/BonusMalus/log-Density only; basis never touches OHE dummies, fixing study-04 E0002 leak) close >=30% of the 0.010172 gap; pre-loop signal says ~16.8% - prior doubted, honest-no informs the translate-back program either way; frontier improvement over 0.454861 with minimum_delta=0.000539 |
| E0005 | 0.444413 | discard | RQ2/M1: LightGBM poisson at nominal-matched config (31 leaves, lr .1, 200 rounds) lands within 2x gbdt floor 0.000573 of HGBT 0.444689 - tie predicted DISCARD; capacity confound acknowledged: HGBT effective_trees=67 (early stopping) vs LGBM full 200; M1-b matched-capacity lever fires in adaptive-3 only if this breaks the tie; did not improve track frontier 0.444689 by minimum_delta=0.000573 |
| E0006 | 0.446332 | discard | RQ3/M2: CatBoost Poisson (CTR categorical statistics + symmetric trees, boosting_type=Plain on CPU, depth 6, 200 iters, Exponent predictions) vs HGBT-OHE incumbent at cardinality <=22 (Region 22, VehBrand 11): prior says NO pay - pre-loop deficit +0.001643 = 2.9x gbdt floor; wording per method-card R3: this tests the CTR+symmetric package, NOT ordered boosting; did not improve track frontier 0.444689 by minimum_delta=0.000573 |
| E0007 | 0.452926 | discard | RQ5/M4: + top TRAIN-fold surrogate interaction VehAge x BonusMalus (rank 1/10, |resid corr| 0.1536; PD strength 0.029; DrivAge x BonusMalus ranked 8/10 - literature prior refuted in ranking). Screened 10 pairs, adopting 1. Predicted: closes >= 2x glm floor 0.000539 beyond E0004's 0.453156; did not improve track frontier 0.453156 by minimum_delta=0.000539 |
| E0008 | 0.452913 | discard | RQ5/M4-c ceiling: + BOTH top surrogate pairs (VehAge x BonusMalus 0.1536, BonusMalus x logDensity 0.0985; PD strengths 0.029/0.043). Screened 10, adopted 2, rejections reported. E0007 showed pair 1 alone buys 0.43x floor; prediction now honest-uncertain: two products still < 1x glm floor beyond E0004 -> the scoped-spline model IS the practical GLM ceiling; did not improve track frontier 0.453156 by minimum_delta=0.000539 |
| E0009 | 0.447455 | discard | RQ7/M3: monotone +1 BonusMalus on the NATIVE-categorical HGBT. Constraint cost read TWO ways per method-card R2: vs same-encoding unconstrained control (study-04 E0004 native 0.445343, tag v1.0.0, same split/prep) and vs the OHE incumbent 0.444689 (total cost incl. encoding). Prediction: constraint component < 1x gbdt floor 0.000573 - filability nearly free; did not improve track frontier 0.444689 by minimum_delta=0.000573 |
| E0010 | 0.444431 | discard | M1-b: LightGBM poisson at n_estimators=67 - matched to HGBT's EFFECTIVE capacity (E0003 early-stopped at 67 trees). Prediction: |delta| vs 0.444689 stays < 2x gbdt floor 0.000573 -> the RQ2 tie is algorithmic, not an early-stopping artefact; did not improve track frontier 0.444689 by minimum_delta=0.000573 |
| E0011 | 0.459231 | discard | sealed confirmation of the glm incumbent (E0004 scoped splines) + holdout prediction export for the off-ledger sealed-gap computation; sealed final-test evidence; excluded from the adaptive frontier |
| E0012 | 0.449667 | discard | sealed confirmation of the gbdt incumbent (E0003 hgbt_ohe, seed 0, lr .1, nominal 200 iters) + holdout prediction export for the off-ledger sealed-gap computation; sealed final-test evidence; excluded from the adaptive frontier |
adaptive-1 — anchors, then metrology
Nothing may be compared before the ruler is calibrated. This phase did two jobs: prove the pipeline reproduces study 04 exactly, and measure the floors.
Friction F1 — a burned slot, and it teaches something. E0001
printed the anchor-exact metric 0.454861 and was still dispositioned discard
— "guardrail metric wall_seconds missing". Cause:
evaluate_regression writes wall_seconds into
aux_metrics.tsv but does not print it in the canonical block, and
the runner's guardrail check reads the printed block. Study 04 had avoided this by
passing wall_seconds explicitly via extra — a line that
looked decorative and was load-bearing. The fix was E0002's one-line candidate diff;
adaptive-1's max_experiments was raised 2→3 to un-burn the
slot, and the reason was recorded in the contract description rather than quietly
patched.
E0002 and E0003 then reproduced study 04's published
anchors to 1e−9 through a different metric implementation (the v0.4.0
registry against study 04's hand-rolled deviance): glm_ohe
0.454861, hgbt_ohe 0.444689. Anchor gap
+0.010172.
The phase's headline discovery was an aux column nobody would have logged
without the method card. Risk R1 forced effective_trees into the
aux ledger on every GBDT row, and E0003's HistGradientBoostingRegressor(max_iter=200)
came back having fitted 67 trees — early_stopping="auto"
switches on above 10,000 samples and holds out 10% of the train fold. The nominal
capacity setting was a third of the truth, invisible in the config.
Then the floors, all as sanctioned sweeps with sidecar TSVs:
glm fit-seed sweep (k=5) -> std EXACTLY 0 (deterministic solver)
gbdt fit-seed sweep (k=5) -> std 0.000210
paired CRN bootstrap B=1000 -> glm-pair SE 0.000270 -> minimum_delta 0.000539
gbdt-pair SE 0.000287 -> minimum_delta 0.000573
CROSS-track SE 0.000963
dev gap +0.010172 = 10.6x the cross-track paired SE
adaptive-2 — the forensics ladder
The phase opened with the slate ritual: six falsifiable candidates scored on novelty / testability / expected information, the table recorded before any of them ran.
| # | Candidate | Nov | Test | Info | Sum |
|---|---|---|---|---|---|
| 3 | [glm] scoped splines close ≥ 30% of the gap (RQ4) | 3 | 3 | 3 | 9 |
| 1 | [gbdt] LightGBM at nominal-matched config ties HGBT (RQ2) | 2 | 3 | 3 | 8 |
| 2 | [gbdt] CatBoost CTR + symmetric package (RQ3) | 2 | 3 | 3 | 8 |
| 4 | [glm] + top surrogate pair (RQ5) | 3 | 2 | 3 | 8 |
| 6 | [gbdt] LGBM matched to HGBT's effective 67 trees (M1-b) | 2 | 3 | 2 | 7 |
| 5 | [glm] + both top pairs (RQ5 ceiling) | 2 | 2 | 2 | 6 |
Candidate 3 went first because its verdict decides what the rest of the study is about: if additive shaping closes a third of the gap, the translate-back story is "splines plus interactions"; if it closes a sixth, interactions are the only hope. It closed a sixth.
- E0004 KEEP — column-scoped splines, 0.454861 → 0.453156. A real frontier improvement (3.2× the glm floor) that closes only 16.8% of the gap. RQ4's 30–45% prior refuted in magnitude on the very first candidate.
- E0005 discard — LightGBM-Poisson, 0.444413, i.e. 0.48× floor better than HGBT. A tie, as predicted — but recorded with the capacity confound stated in the description (200 LGBM trees vs HGBT's effective 67).
- E0006 discard — CatBoost, 0.446332, +2.9× floor worse. A real deficit, not a tie.
Then the loop stopped and ran the instruments (off-ledger — analysis, never evidence). The train-fold surrogate returned = 0.6647: only two thirds of the teacher's log-rate surface is main-effects-representable. The gap is substantially non-additive, and M4-a's "> 0.90" prior was falsified. The residual ranking:
rank 1 VehAge x BonusMalus 0.1536 PD cross-check strength 0.029
rank 2 BonusMalus x logDensity 0.0985 PD cross-check strength 0.043
rank 3 VehAge x DrivAge 0.0789 PD cross-check strength 0.016
...
rank 8 DrivAge x BonusMalus <-- the literature's favourite pair
The segment decomposition (M5) came back DIFFUSE: the top-3 BonusMalus bins carry 87% of the gap on 89% of exposure — essentially proportional to exposure. No bad segment to carve out.
- E0007 discard — scoped splines + the rank-1 product, 0.452926: 0.43× floor. Sub-floor.
- E0008 discard — both top pairs, 0.452913: 0.45× floor. Still sub-floor.
Multiplicity ledger: 10 pairs screened, 0 adopted — and both rejections filed as ledger rows rather than deleted. That published zero is the phase's real product.
adaptive-2 phase in one picture. Additive shaping takes 16.8%; the two
strongest interaction products the black box itself nominated are sub-floor and rejected;
83.2% of the gap is an irreducible non-additive residue at this basis.
Note the honesty caption: the y-axis is a zoomed level axis, so the bar
heights are the deltas and the grey band shows one cross-track SE at true
scale.adaptive-3 — the post-forensics redirect
The forensics reframed the remaining questions, so the reserve slots went to mechanism rather than to more library shootouts.
- E0009 discard —
hgbt_monotone, 0.447455. Priced two ways, per method-card risk R2: against a same-encoding unconstrained control (study 04's native HGBT 0.445343, identical split and prep, tag v1.0.0) the constraint alone costs +0.002112 = 3.7× floor; against the OHE incumbent, constraint plus encoding switch costs +0.002766 = 4.8× floor. The constraint also cut effective capacity to 53 trees. - E0010 discard — LightGBM truncated to
n_estimators=67, matching HGBT's effective capacity: 0.444431, Δ = 0.45× floor. The tie shrank under matching, so RQ2's tie is algorithmic, not an early-stopping artefact.
Two more off-ledger instruments fired here. M3-a checked the
empirical shape before interpreting E0009's cost: exposure-weighted mean frequency is
non-decreasing in BonusMalus over 100% of train exposure (the 8-bin qcut
collapsed to 4 usable bins because 68.8% of exposure sits in BM 50–54). The
+1 sign is not merely defensible — it is right. And the
RQ6 data-volume sweep refit both anchor configs on nested train
subsamples, scoring each on the unchanged dev fold: seven fits, ~14 s.
confirmation — the two sealed accesses
Friction F2 — the second burned slot, and a framework bug.
E0012 was refused with "sealed final-test state is missing for track 'gbdt'".
Cause: klein new scaffolds a single track and initial_state
derives the final_holdout_access keys from the tracks at scaffold
time; adding a second track by editing study.yaml — the only way
to build a two-track study today — leaves that map stale, and load_state
performs no reconciliation. Fixed by an atomic scripted edit adding the missing
gbdt entry, byte-identical in shape to what initial_state
generates, committed with a note. Both frictions are filed as framework-fix candidates in
section 7.
Then, one access each, on the incumbent each track had already selected:
E0011 glm incumbent (E0004 scoped splines) sealed 0.459231
E0012 gbdt incumbent (E0003 hgbt_ohe) sealed 0.449667 effective_trees 67
SEALED GAP = 0.459231 - 0.449667 = 0.009564
Both runs exported their per-row holdout prediction tables, and the two were joined
off-ledger (135,603 rows, y and weights verified identical) for the paired
sealed-gap computation. E0012 also reproduced study 04's sealed HGBT number
bit-identically across a study boundary — determinism nothing
currently guards.
Findings
Seven claims carry the study. One is confirmed against sealed
evidence; the rest are development-fold findings and say so. Claim IDs are stable
(05-fremtpl2-gap-forensics#C<n>) and are never renumbered.
C1 — the gap survives as a difference of two sealed numbers [confirmed]
sealed gap 0.459231 - 0.449667 = +0.009564 = 9.3x the sealed cross-track SE (0.001028)
dev gap 0.453156 - 0.444689 = +0.008467 (incumbent vs incumbent)
| sealed - dev | = 0.001097 = 1.07x SE -> inside the 2-SE band
anchor gap 0.454861 - 0.444689 = +0.010172 = 10.6x the dev cross-track SE (0.000963)
This is the study's estimand and both tracks' single sealed accesses were spent on it. The pre-registered band was "within 2 paired SEs of the development gap"; the observed displacement is 1.07 SE. The anchor-config gap — the reference the whole study was designed around — replicates too. Study 04's protocol caveat, that a gap cannot be sealed-confirmed under one-access-per-track, is closed.
C4 — additive shaping tops out near 17%, and the leak was never the constraint
Column-scoped splines on DrivAge, BonusMalus and log-Density moved the GLM 0.454861 → 0.453156: −0.001705, a real kept improvement at 3.2× the glm floor — and only 16.8% of the 0.010172 anchor gap, less than half the 30–45% prior.
The decisive sub-finding is a comparison, not a level. Study 04's shaped GLM had a leaky basis (the spline transform spilled onto the OHE dummies) and closed 17.6%. This study's clean, column-scoped basis — the whole reason RQ4 existed — closed 16.8%.
Fixing the leak changed the closure by −0.8 percentage points. The leak was never the binding constraint. Mechanism: splining a dummy is a no-op in expressiveness — a 0/1 column's cubic basis spans the same two-point space — so the "leak" added parameters and a hair of overfit, never signal.
C5 — 83% of the gap is non-additive residue: 10 screened, 0 adopted
The surrogate said the structure exists ( = 0.6647) and named where it is. The GLM could not use it:
| Candidate | Dev deviance | Δ vs E0004 | × glm floor | Disposition |
|---|---|---|---|---|
| E0004 scoped splines (incumbent) | 0.453156 | — | — | keep |
| E0007 + VehAge×BonusMalus (rank 1) | 0.452926 | −0.000230 | 0.43× | discard |
| E0008 + both top pairs | 0.452913 | −0.000244 | 0.45× | discard |
The scoped-spline GLM is therefore the practical GLM ceiling on this feature set, and the non-additive residue is 0.008467 = 83.2% of the anchor gap = 8.8× the cross-track SE — an irreducible remainder at this basis, not a measurement artefact.
The honest zero is the finding. A floor-free search over ten pairs would have reported the best of them as an improvement; the multiplicity budget was fixed in advance (10 screened, ≤ 2 adopted, nothing adopted below 1× floor, every rejection reported) and it came in at 10 / 0 with room to spare.
Surprise inside the surprise: the interaction the literature would bet on — BonusMalus × DrivAge, the canonical French-MTPL confound where young drivers enter at the base level 100 — ranked 8 of 10. What the tree actually adds is vehicle-age conditioning of the experience-rating signal: an old car with a bad BM record is not the linear sum of "old car" and "bad record". The DrivAge–BonusMalus relationship is largely marginal confounding, which additive main effects already absorb.
C6 — the gap is a function of portfolio size, and below the crossover it reverses
5% of train ~20.3k rows -0.001931 <-- the GLM WINS
10% ~40.7k +0.003446
15% ~61.0k +0.003195 (a sub-floor inversion, see below)
25% ~102k +0.006370
50% +0.008471
75% +0.009240
100% 406,807 +0.010172
The gap crosses zero between 20k and 41k rows and first clears 2× the cross-track SE (2 × 0.000963) at 10% of train. The prior's ~10–15% band was right about where the gap becomes measurable; the sign flip is one octave below it.
Two honesty caveats, both load-bearing. First: at 2.0× the full-data cross SE, the 5% reversal sits right on the 2-SE line, and the SE at 5% of the data is larger than the SE it is being judged against — so read the crossover as established and the magnitude of the GLM's win as at the edge of measurability. Second: the 15% cell sits 0.000251 = 0.26× SE below the 10% cell, which is noise — describe the curve as "increasing apart from one sub-floor inversion", never as "monotonically increasing".
C7 — a filable monotone constraint costs 3.7× the floor even though it is true
This is the study's sharpest mechanism finding, and it only exists because two instruments were run in the right order.
M3-a first: BonusMalus is non-decreasing in frequency over 100% of TRAIN EXPOSURE
(marginally). So +1 is not merely defensible - it is the right sign.
E0009 then: constraint cost vs a SAME-ENCODING control (study 04 native HGBT 0.445343)
0.447455 - 0.445343 = +0.002112 = 3.7x the gbdt floor
vs the OHE incumbent (constraint + encoding switch)
0.447455 - 0.444689 = +0.002766 = 4.8x floor
effective_trees fell 67 -> 53: the constraint also cut capacity.
The prior said filability is nearly free. It is not. And because the marginal shape was checked first, the cost is interpretable rather than mysterious:
The cost is not a wrong-sign penalty. It is the price of forbidding conditional non-monotonicity. sklearn enforces the constraint pointwise in every conditioning context; the model wants the BonusMalus slope to bend differently for old vehicles than for new ones — precisely the VehAge×BonusMalus interaction that ranked first in the surrogate screen.
Two forensics instruments, run for unrelated reasons, landed on the same structure by different routes. That convergence is worth more than either number alone. And it is a completely different conversation with a regulator: not "your model wanted the wrong shape" but "your shape guarantee costs this much, and here is exactly which interaction it forbids".
C2 — the library tie, and the capacity trap underneath it
LightGBM-Poisson vs sklearn HGBT, at both capacities:
| Comparison | Deviance | Δ vs HGBT 0.444689 | × gbdt floor |
|---|---|---|---|
| nominal-matched (200 rounds, E0005) | 0.444413 | −0.000276 | 0.48× |
| effective-matched (67 trees, E0010) | 0.444431 | −0.000258 | 0.45× |
A tie at both capacities, so the tie is algorithmic rather than an early-stopping artefact. Both are discards by the contract — and the discard IS the finding: library choice on this data is an operations decision (deployment target, native-categorical support, team familiarity), not an accuracy decision.
Underneath sits a trap worth more than the tie. HistGradientBoostingRegressor(max_iter=200)
fitted 67 trees; LightGBM at n_estimators=200 built all 200;
CatBoost built all 200; the monotone variant managed 53. Every "matched-capacity
library comparison" published with those two default configs is comparing 67 trees to
200. Here the confound was real but inert — matching capacity made
the delta shrink, because both libraries saturate this signal well before 67
trees. That is luck, not design: it was only visible because the method card forced
effective_trees into the aux ledger on every GBDT row.
For completeness: CatBoost's CTR + symmetric-tree package (E0006, 0.446332) landed
+2.9× floor worse than plain OHE-HGBT — a real deficit, not a
tie. At ≤ 22 levels with ~9,000 train rows per Region level, ordered target statistics
have nothing to de-bias. Open caveat: the isolation lever (one_hot_max_size=32)
was never run, so CTR-vs-symmetric-tree attribution remains unresolved; the claim is
package-level only.
The bonus finding: the "+2% calibration bias" was a fold, not a model
Every development row reports calibration_ratio ≈ 1.014–1.022
— a consistent 2% over-prediction that the method card froze as a known bias to be
reported and never recalibrated. On the sealed test both models flip to
under-prediction: 0.9962 (GLM, E0011) and 0.9905 (GBDT, E0012).
Nothing about either model changed. The data card's partition frequencies explain it almost exactly:
predicted over-prediction on dev 0.073900 / 0.072375 = 1.021 observed 1.0216
predicted under-prediction on test 0.073900 / 0.074350 = 0.994 observed 0.9962
The A/E number was measuring split sampling variation, not model calibration.
Both tracks move together, so the gap is untouched — which makes this the sharpest available demonstration of why "report the gap, never the levels" is the operative discipline. Practical consequence: the ±2% swing between folds is portfolio-sampling noise and should not be booked as a model loading. Both sealed models land within 1% of unity on A/E with no recalibration applied, so the deviance comparison is between two adequately-calibrated models rather than a rank-versus-calibration trade.
The scorecard — priors were right about decisions, wrong about magnitudes
Fourteen registered levers: 6 fully held (RQ1 replication, the RQ2 tie, M1-a's early stopping, M1-b's matched capacity, M3-a's monotone sign, M4-c's multiplicity budget); 2 held on disposition but falsified on magnitude (CatBoost's deficit is real, not a tie; splines keep but at half the predicted closure); 5 outright falsified (RQ5's further recovery, RQ7's free constraint, M4-a's additivity, M4-b's favourite pair, M5-a's concentration); 1 untested (the CatBoost isolation lever).
The study's priors were right about what the loop would decide far more often than about how much. Every magnitude prior that was stakeable came out wrong.
Worth noting for anyone maintaining a knowledge base: knowledge/-sourced
priors went 1 fully held / 1 partially / 2 refuted, while uninformed priors went
1 held / 1 refuted. Informed priors did not outperform uninformed ones here,
and both card refutations are cases where a large-sample, main-effects intuition was
generalised into a regime where the binding structure was interactions.
What this means for a pricing committee
- The price of interpretability is now a number with an error bar. A filed additive GLM — even a properly spline-shaped one — leaves 83.2% of the modelling gap on the table at this portfolio size. "Rebuild the GLM better" is not a route to closing it: the remaining advantage is non-additive structure a linear score cannot represent.
- But the price is a function of portfolio size, and below ~40k rows it is zero or negative. For a small book, a new line, a thin segment carved out for separate rating, or a territory with sparse history, the boosted model buys nothing measurable and costs the whole governance, documentation and monitoring apparatus. Do not buy a GBDT programme for a portfolio that cannot feed it.
- The shape guarantee has a price tag: 27% of the boosted edge. The unconstrained incumbent captures the full 0.010172 gap; the monotone variant captures 0.454861 − 0.447455 = 0.007406 = 72.8%. That is a concrete trade a committee can actually decide.
- Where the gap does NOT live is as useful as where it does. The decomposition is diffuse — top-3 BonusMalus bins carry 87% of the gap on 89% of exposure. There is no thin high-frequency pocket where a specialist model earns its keep. Any capture of this gap is a book-wide re-rate, not a targeted intervention — which raises implementation cost and filing burden relative to the "just fix the bad segment" story the concentration prior would have supported.
- Operational cost is not the deciding variable. Per fit: GLM 1.1–1.5 s, HGBT 2.9 s, LightGBM 2.2–3.2 s, CatBoost 7.1 s — all three orders of magnitude inside the 400 s guardrail.
Limitations, stated plainly
- Feature-profile twins straddle the split (26.54% of dev rows, 26.37% of sealed-test rows). Every absolute deviance here is optimistic relative to a fresh portfolio; the gap is not, because both tracks consume identical contamination.
- The surrogate screen is numeric-only. Region×DrivAge, VehBrand×VehAge and pure threshold interactions are structurally invisible to the ranking and to the E0007/E0008 adoption test. "0 of 10 adopted" bounds what numeric-product translate-back can recover, not what any GLM-representable structure could.
- One split, one seed. The paired bootstraps quantify comparison noise within the seed-42 split; they say nothing about split-to-split variation. With no time column available, C1 is an in-period statement, not a forward-in-time generalization.
- Hub-prepped data. Pre-clipped, with a silently-binding exposure lower clip — absolute values are not directly comparable to published freMTPL2 numbers from other preparations.
- Off-ledger forensics carry no uncertainty. , the pair rankings, the PD strengths and the M5 shares are same-fold descriptive instruments. They are cited as directional evidence, and every conclusion they support is independently confirmed by a ledger row — no verdict rests on a forensics number alone.
- M2-a untested. The CatBoost deficit's attribution was never isolated.
Coding Advice
This is the section that makes the artifact useful. Below is the actual
committed train.py — the only mutable surface in a Klein v2
study — followed by the pitfalls that bit this study and the seven pieces of
transferable advice they earned.
The winning train.py, verbatim
Read it for its shape first. It is 114 lines and it contains no model code at
all: constructors live in the frozen study library pipeline.py, the metric
lives in the framework registry, and the per-experiment surface is a nine-line
CONFIG block. That is the point — a 5–15 line diff per candidate
is only possible if everything else is already immovable.
"""The only per-candidate mutable surface in a Klein v2 study.
freMTPL2 claim frequency, sealed two-track GLM vs GBDT. The CONFIG block is the
experiment surface; pipeline.py is the stable study library. Metric: exposure-
weighted mean Poisson deviance on the scoring fold, computed by the v0.4.0
registry (`kleinlib.eval.evaluate_regression`) — predictions are clipped positive
by the ClippedRegressor wrapper because the registry refuses pred <= 0 by contract.
A sealed final-test run additionally exports the per-row holdout prediction table
(`save_holdout_predictions`) so the off-ledger sealed-gap + paired-SE computation
and the pricing-eval double-lift card can be built after BOTH tracks have spent
their one sealed access.
"""
from __future__ import annotations
import os
import time
import math
from kleinlib.eval import evaluate_regression, save_holdout_predictions
from pipeline import effective_trees, fit_model, null_dev_deviance, read_reference
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 ("glm" if SMOKE else None)
# ---- CONFIG: the per-experiment surface (keep diffs 5-15 lines) ----
MODEL = "hgbt_ohe" # glm_ohe | glm_scoped_splines | glm_interactions |
# hgbt_ohe | hgbt_monotone | lgbm_poisson | catboost_poisson
SEED = 0
LR = 0.1
MAX_ITER = 200
MAX_LEAF = 31
INTERACTIONS = () # e.g. (("BonusMalus", "DrivAge"),) — surrogate-derived only
# --------------------------------------------------------------------
PRED_DIMS = ["DrivAge", "BonusMalus", "VehGas", "Region"]
def main() -> None:
t0 = time.time()
evaluation_kind = os.environ.get("KLEIN_EVALUATION_KIND") or (
"development" if SMOKE else None
)
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`; missing "
+ ", ".join(missing)
)
if evaluation_kind not in {"development", "final_test"}:
raise RuntimeError(f"invalid KLEIN_EVALUATION_KIND={evaluation_kind!r}")
if evaluation_kind == "development":
# Split-identity anchor: the null-model development deviance must match
# prepare.py's reference cell exactly, every run, before any model fits.
reference = read_reference()["null_dev_deviance"]
recomputed = null_dev_deviance()
if abs(reference - recomputed) > 1e-9:
raise RuntimeError(
f"split-identity anchor FAILED: reference {reference!r} vs "
f"recomputed {recomputed!r} — split or data drifted, STOP"
)
model, X_ev, y_rate_ev, w_ev, fit_seconds, train_n = fit_model(
MODEL,
evaluation_kind=evaluation_kind,
seed=SEED,
learning_rate=LR,
max_iter=MAX_ITER,
max_leaf_nodes=MAX_LEAF,
interactions=INTERACTIONS,
)
evaluate_regression(
model,
X_ev,
y_rate_ev,
exp_id=EXPERIMENT_ID,
t0=t0,
fit_seconds=fit_seconds,
train_n=train_n,
val_n=len(X_ev),
metric_name="val_poisson_deviance",
metric_goal="lower",
sample_weight=w_ev,
study_dir=".",
extra={"model_config": MODEL, "wall_seconds": time.time() - t0}
| ({"effective_trees": n_trees} if math.isfinite(n_trees := effective_trees(model)) else {}),
)
if evaluation_kind == "final_test" and not SMOKE:
save_holdout_predictions(
".",
EXPERIMENT_ID,
y_true=y_rate_ev,
y_pred=model.predict(X_ev),
weight=w_ev,
dims=X_ev[PRED_DIMS],
)
print(f"holdout predictions exported: predictions/{EXPERIMENT_ID}_holdout.csv.gz")
if __name__ == "__main__":
main()
Annotated: the five things this file does that matter
- The
CONFIGblock is the entire experiment surface. Seven named configs, a seed, three capacity knobs and anINTERACTIONStuple. Every one of the twelve ledger rows is a diff inside those nine lines. The comment onINTERACTIONS— "surrogate-derived only" — is the data-card's lookahead directive written where the person editing the file will see it. - It refuses to run outside the harness.
KLEIN_EVALUATION_KIND,KLEIN_EXPERIMENT_IDandKLEIN_TRACKmust all be present or it raises. A file that can be run by hand is a file whose results can end up unlogged. - The split-identity anchor fires before any model fits. On every development run it recomputes the intercept-only deviance and compares it to the frozen reference cell at 1e−9. If the split, the prep or the weights ever drift, the study stops immediately rather than producing plausible-looking numbers on different data.
wall_secondsis passed explicitly throughextra. It looks decorative. It is load-bearing — friction F1 below.- The sealed branch exports per-row predictions. A sealed access is spent once, so it must yield everything downstream analysis will ever need: the joined prediction tables are what the off-ledger sealed-gap and paired-SE computation ran on, and what a pricing-eval double-lift card would consume.
War stories — the traps that actually fired
F1 — a guardrail metric that is written but not printed
E0001 printed the anchor-exact 0.454861 and was still dispositioned discard:
"guardrail metric wall_seconds missing". evaluate_regression
writes wall_seconds to aux_metrics.tsv, but the runner's
guardrail check reads the printed canonical block. One experiment slot, gone.
# the one-line fix that un-burned the slot (E0002's candidate diff):
extra={"model_config": MODEL, "wall_seconds": time.time() - t0}
# ^^^^^^^^^^^^^^ not decorative
Transferable rule: a declared guardrail must appear in whatever surface the checker actually reads. If your harness reads stdout, write it to stdout.
F2 — per-track state that was derived once, at scaffold time
E0012 was refused: "sealed final-test state is missing for track 'gbdt'".
klein new scaffolds a single track, and the initial state derives its
final_holdout_access keys from the tracks that existed then. Adding a second
track by editing study.yaml — the only way to build a two-track study
today — leaves that map stale, and state loading performs no reconciliation.
Transferable rule: any state map derived from a contract must be topped up from the contract at load time, not frozen at creation. Both frictions are filed as framework fixes in section 7 — each one cost a real experiment slot.
The CatBoost prediction-space trap
CatBoostRegressor.predict returns RawFormulaVal — a
log — for most losses, and Exponent only for Poisson and
Tweedie if you ask. Handing raw scores to a Poisson deviance produces a nonsense number,
or gets rejected by the positivity guard, which is the lucky outcome. The call
site is frozen in the study library and never inlined in train.py:
class CatBoostPoisson:
"""CatBoost with Poisson loss on the raw frame (native categoricals).
predict() must return expected counts (exp space), not the raw score."""
def predict(self, X: pd.DataFrame) -> np.ndarray:
return np.asarray(self.model.predict(X, prediction_type="Exponent"), dtype=float)
The registry refuses non-positive predictions — by contract
Poisson deviance needs strictly positive μ, and the metric registry raises rather than silently clipping. That is the right contract, but it means every estimator needs a wrapper — which is also the natural place to replay the stateless frame-level transform at predict time, so that fit and predict can never diverge:
class ClippedRegressor:
def predict(self, X: pd.DataFrame) -> np.ndarray:
X = _transform_frame(X, shaped=self.shaped, interactions=self.interactions)
return np.clip(np.asarray(self.inner.predict(X), dtype=float), MIN_PRED, None)
Scoping the spline basis — the study-04 fix, in three lines
Study 04 splined everything the transformer was handed, including the one-hot dummies. The scoped version puts the spline pipeline on the three continuous rating factors only:
("spline", Pipeline([("scale", StandardScaler()),
("spline", SplineTransformer(n_knots=6, degree=3))]), SPLINED),
("num", StandardScaler(), rest + inter_cols),
("cat", OneHotEncoder(handle_unknown="ignore", min_frequency=20), CATEGORICAL),
The punchline from section 5 is worth repeating here: this fix was correct, hygienic, and changed the answer by −0.8 percentage points. Splining a 0/1 column is a no-op in expressiveness. Fix it because it is right, not because you expect it to buy signal.
Monotone constraints index the input columns
The constraint vector is one entry per input feature, categoricals must be
0, and the whole config therefore has to switch to the native-categorical
encoder so the index order is the raw NUMERIC + CATEGORICAL order the vector
assumes. That is two changes at once, which is exactly why RQ7 needed a
same-encoding control:
pre = build_preprocessor(NUMERIC, CATEGORICAL, kind="native")
cst = [1 if c == "BonusMalus" else 0 for c in NUMERIC] + [0] * len(CATEGORICAL)
The effective-capacity probe
Three libraries, three different attributes, one aux column. Without this the RQ2 verdict would have compared 67 trees to 200 and called it "matched capacity":
def effective_trees(clipped) -> float:
if isinstance(est, HistGradientBoostingRegressor): return float(est.n_iter_)
if isinstance(inner, CatBoostPoisson): return float(inner.model.tree_count_)
if hasattr(est, "booster_"): return float(est.booster_.num_trees())
return float("nan") # deterministic GLMs: no tree count
The seven transferable rules
- [C8] Run the translate-back programme as a screen with a budget, not
as a search. Distil the black box on the train fold only into an
interpretable surrogate, rank candidate structure by residual explanation, then adopt on
development only above the measured floor — and publish
screened / adoptedeither way. Here that was 10 screened, 0 adopted, and the honest zero is a stronger result than any of the ten "improvements" a floor-free search would have reported. - [C9] Report the GAP, never the levels. 26.54% of development rows and 26.37% of sealed-test rows have a feature-identical twin in train, and the three partitions differ in exposure-weighted frequency by ±1.3%. Both effects hit both tracks identically, so the difference survives what the levels do not — as the A/E flip demonstrates, with no model change whatsoever.
- [C10] Log EFFECTIVE capacity on every boosted row before you claim a library
difference — or a library tie.
max_iter/n_estimators/iterationsare nominal;n_iter_,booster_.num_trees(),tree_count_are what you fitted. HGBT early-stops above 10,000 samples by default and delivered 67 of a nominal 200. Match on the effective number and re-run before writing the verdict. - [C11] Measure the paired floor that governs YOUR comparison before believing any gap. There is more than one floor and they differ by a factor of five or more: a GLM fit-seed std of exactly 0 (deterministic solver — quoting a seed floor for a GLM is meaningless), a GBDT fit-seed std of 0.000210, within-track paired SEs of 0.000270 / 0.000287, and a cross-track paired SE of 0.000963 — 4.6× the GBDT seed floor and the only one that legitimately bands the headline gap. Use common random numbers and bootstrap the difference, not the two levels.
- [C12] Size-gate the model class before you spend a week on it. Refit both candidates on nested subsamples of your own train fold and plot the gap against n: seven fits, 14 seconds here, and it tells you whether the boosted model is worth its governance overhead at all. Below the crossover a filed additive GLM is not a concession — it is the better model.
- [C13] Price a shape constraint against a control that differs ONLY by the constraint, and check the MARGINAL shape first so you know what you are pricing. Differencing against a differently-encoded incumbent measures constraint plus encoding (4.8× floor); the same-encoding control isolates the constraint (3.7×). And confirm the empirical direction before interpreting: a constraint that is true on the margin can still be expensive, because it is the conditional version the library enforces.
- [C14] Start the next study from
checklist.md, not fromfindings.md. The transferable product of this study is a seven-row dataset-characteristics → method-choice checklist shipped alongside the findings; each row names the measurable property of your data, the cheap way to measure it, the method choice it implies, and the claim ID that earned it. Read the checklist to decide; read the findings to audit the decision.
And one rule the harness enforces for you
Every candidate is committed before it runs, and a non-keep restores
train.py to the pre-candidate base commit while leaving the candidate commit
resolvable. This study's most-cited rows — E0007 and E0008 at 0.43× and
0.45× floor, E0009's 3.7×-floor constraint cost — are all
discards. Negative evidence is evidence, and it is only citable if the
loop kept it.
Next Steps
What to try next, in priority order
- Tensor-product spline / GAM interactions on the
glmtrack — the real test of RQ5. E0007/E0008 tested raw standardised products, the crudest possible interaction basis, and found 0.43–0.45× floor. The surrogate says the structure exists ( = 0.6647) and names where it is (VehAge×BonusMalus). Fit a tensor-product spline basis, or a bivariate smooth, on that one pair inside the scoped-spline GLM. Highest-information follow-up: it decides whether "83% non-additive" means GLM-unrepresentable or merely not representable by products. Prediction to falsify: closes 2–5× the glm floor — enough to keep, far short of the residue. - Categorical interaction probe — close the numeric-only blind spot, and
spend the slot the isolation lever never got. Extend the screen to
categorical×numeric and categorical×categorical structure (Region×DrivAge,
VehBrand×VehAge) using the two-way PD instrument on the fitted HGBT rather than the
numeric-only surrogate, and re-run the segment decomposition over Region and VehBrand
levels instead of BonusMalus bins. In the same phase, run
catboost_poissonwithone_hot_max_size=32so C3's CTR-versus-capacity attribution stops being open. - A two-track CI anchor test. Both anchors reproduced to 1e−9
across a study boundary, and E0012 reproduced study 04's sealed number bit-identically.
Promote the pair (0.454861 / 0.444689 on the frozen prep SHA-256
db82e802…1cf948) into a repo-level regression test, so that any future change to the study library, the metric registry, or the environment that moves either anchor fails CI loudly. Determinism this exact is an asset; nothing currently guards it. - Framework fixes — both cost a real experiment slot in this study.
- F1 —
evaluate_regressionwriteswall_secondstoaux_metrics.tsvbut does not PRINT it, and the runner's guardrail check reads the printed block; E0001 was dispositioned discard with an anchor-exact metric because of it. Fix: printwall_secondsin the canonical block, or haveklein preflightfail when a declared guardrail metric is not among the keys the run will print. - F2 —
klein newscaffolds a single track and the initial state derivesfinal_holdout_accesskeys from the tracks at scaffold time; adding a second track by editingstudy.yaml(the only way to build a two-track study today) leaves that map stale, and E0012 was refused. Fix: have state loading top up per-track maps from the current contract, or letklein newaccept repeated--track.
- F1 —
- Severity / pure-premium extension. Frequency is one of two factors in the premium. The same two-track sealed-gap protocol on a Gamma severity track and a Tweedie pure-premium track would say whether the 83% non-additive residue is a frequency phenomenon or a property of this book — and whether the 20–41k crossover moves when the response gets noisier.
And the artifact to start from
The transferable product of this study is checklist.md
— seven rows of measurable property of your data → method choice it
implies, each citing the claim that earned it and each naming the cheap measurement
to run before trusting it. Its 15-minute protocol:
- Count your rows. Under ~40k, stop and build the GLM well.
- Fit one default GBDT, distil it, read . This single number tells you whether an interpretable rebuild can ever close the gap.
- If the gap is non-additive and you must file an interpretable model, run the screen with a published multiplicity budget, and price your shape constraints.
- Do not spend slots on encoder or library shootouts until your cardinality and capacity numbers say you are outside the regime where they are ties.
- Before any of it becomes a number in a document, measure your floors. It is the cheapest step and the only one that can invalidate all the others.
Scope honesty: those rows were earned on ONE dataset — freMTPL2 claim frequency, 678,013 rows, 9 features, exposure-weighted Poisson, a single seed-42 split. They are starting priors with measured magnitudes, not laws.
References
All 18 entries in the method card were verified on 2026-07-31 against arXiv, the NeurIPS proceedings, official library documentation, Springer, and the Swiss Association of Actuaries' Actuarial Data Science index. 0 UNVERIFIED. Three carry honest caveats, reproduced here rather than smoothed away.
Papers
- Prokhorenkova, L., Gusev, G., Vorobev, A., Dorogush, A.V., Gulin, A. (2018). CatBoost: unbiased boosting with categorical features. NeurIPS 31; arXiv:1706.09516.
- Ke, G., Meng, Q., Finley, T., Wang, T., Chen, W., Ma, W., Ye, Q., Liu, T.-Y. (2017). LightGBM: A Highly Efficient Gradient Boosting Decision Tree. NIPS 30.
- Craven, M. & Shavlik, J.W. Extracting Tree-Structured Representations of Trained Networks (TREPAN). NIPS 8; MIT Press. Year ambiguity, stated honestly: papers.nips.cc labels the volume "NIPS 1995" while the MIT Press volume appeared 1996 — cite as "NIPS 8 (1995 conference; MIT Press, 1996)" rather than silently picking one.
- Hinton, G., Vinyals, O., Dean, J. (2015). Distilling the Knowledge in a Neural Network. arXiv:1503.02531; NIPS 2014 Deep Learning Workshop.
- Lundberg, S.M., Erion, G.G., Lee, S.-I. (2018). Consistent Individualized Feature Attribution for Tree Ensembles. arXiv:1802.03888 — the SHAP interaction-value construct this study deliberately declines to use.
- Grinsztajn, L., Oyallon, E., Varoquaux, G. (2022). Why do tree-based models still outperform deep learning on typical tabular data? NeurIPS 35, Datasets & Benchmarks Track; arXiv:2207.08815. Title differs between sources: arXiv reads "…on tabular data?", the proceedings read "…on typical tabular data?" — the proceedings title is used.
Insurance / actuarial
- Noll, A., Salzmann, R., Wüthrich, M.V. Case Study: French Motor Third-Party Liability Claims. SSRN 3164764. Verified through two independent indexes — papers.ssrn.com returns HTTP 403 to automated fetches.
- Wüthrich, M.V. & Merz, M. (2023). Statistical Foundations of Actuarial Learning and its Applications. Springer Actuarial, Open Access, DOI 10.1007/978-3-031-12409-9, Ch. 2 & 5 — the offset / exposure-weight treatment behind the equivalence taught in section 2.
- Denuit, M., Hainaut, D., Trufin, J. (2019). Effective Statistical Learning Methods for Actuaries I: GLMs and Extensions. Springer Actuarial, DOI 10.1007/978-3-030-25820-7.
- Lorentzen, C. & Mayer, M. (2020). Peeking into the Black Box: An Actuarial Case Study for Interpretable Machine Learning. SSRN 3595944 — the closest published precedent for this study's forensics layer, on the same dataset, without a sealed confirmation.
- Mayer, M., Meier, D., Wüthrich, M.V. (2023). SHAP for Actuaries: Explain any Model. SSRN 4389797 — the tooling line this study does not follow.
- Actuarial Data Science tutorials index, Swiss Association of Actuaries — the corroborating index for entries 7, 10 and 11.
Library documentation (the implementation facts rest on these)
- scikit-learn user guide — Ensembles: gradient boosting, v1.9.0 —
the
+1 / 0 / -1monotone encoding, the guarantee , and "it is not possible to enforce monotonic constraints on categorical features". - scikit-learn API — HistGradientBoostingRegressor, v1.9.0 —
early_stopping='auto'= "early stopping is enabled if the sample size is larger than 10000", withvalidation_fraction=0.1. The source of the 67-tree discovery. - scikit-learn example — Tweedie regression on insurance claims, v1.9.0 — same freMTPL2 parameterisation. Verified absence: the page does not state the offset↔weight equivalence in prose, which is why section 2 derives it.
- LightGBM parameters documentation (stable) —
objective="poisson", andpoisson_max_delta_stepdefault 0.7, an HGBT-absent regulariser. - CatBoost training parameters (common) —
boosting_typedefaultPlainon CPU (ordered boosting is OFF) andone_hot_max_sizedefault 2 (ordered target statistics are ON for Region / VehBrand / Area). This pair of facts is why C3 is worded as a claim about the CTR + symmetric-tree package and never about ordered boosting. - CatBoost CatBoostRegressor.predict — "Exponent for Poisson and Tweedie, RawFormulaVal for all other loss functions". The fact the study library encodes.
Honest positioning. None of the five methods taught here is a frontier architecture; all are well-established. What this study contributes is not a new method but a protocol — deriving translate-back structure on train, adopting it on development under a reported multiplicity budget, and confirming the resulting gap as a difference of two sealed test numbers. Reference 10 does the forensics without the seal; study 04 did the seal on one track only. Doing both at once is the gap in the literature this study fills.