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.
train.py, verbatimRead 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.
CONFIG block is the entire experiment surface. Seven
named configs, a seed, three capacity knobs and an INTERACTIONS tuple. Every
one of the twelve ledger rows is a diff inside those nine lines. The comment on
INTERACTIONS — "surrogate-derived only" — is the
data-card's lookahead directive written where the person editing the file will see
it.KLEIN_EVALUATION_KIND,
KLEIN_EXPERIMENT_ID and KLEIN_TRACK must all be present or it
raises. A file that can be run by hand is a file whose results can end up unlogged.wall_seconds is passed explicitly through extra.
It looks decorative. It is load-bearing — friction F1 below.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.
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.
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)
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)
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.
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)
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
screened / adopted either 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.max_iter /
n_estimators / iterations are 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.checklist.md, not from
findings.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.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.