Winning Kaggle the Reproducible Way

Interactive chapter

This page shows the chapter notebook with its saved results. Constructed examples do not measure competition gains.

Chapter 30: External Data and Leakage

Try the decision first

How far does a validation score built on revised data drift from deployment, and when does the training join start to cost accuracy too?

Write your expectation before opening the worked results. Use the chapter activity to compare supported inputs. To change the calculation itself, run the notebook on GitHub.

Your answers stay on this page until you download them. They are not sent to a server.

Open the chapter activity

Worked notebook and saved results

How far does a validation score built on revised data drift from deployment, and when does the training join start to cost accuracy too?

Adjusted and revised sources are common, and joining them by event date is the default of most merge code. The validation score then describes data that did not exist at prediction time, and the model learns to trust it too much.

Constructed series with declared release and revision schedules; the sizes of these effects are properties of this generator, not a competition result.

The experiment

One hundred constructed series, each with 300 months of 30 daily rows. A monthly indicator follows a persistent process; its first release comes 10 days after the month ends with noise of the control size (standard deviation, the true indicator has standard deviation 1.0), and a revision 15 days later is close to the truth. Each daily row is about the month that just ended, and its label depends on that month's true value plus an internal feature. A ridge regression is trained on months 0 to 99 and validated on months 100 to 139. The event-date join uses the revised value for every row; the as-of join uses the latest version of the latest period published at the row's cutoff. Both models are then scored on months 140 to 299 (4,800 rows) with the as-of join, the only data that exist at prediction time.

Calculation code
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.metrics import r2_score

from kaggle_companion.activities._common import clean

SEED = 30
REPLICATES = 100        # independent constructed series; every estimate is their mean
MONTHS, DAYS = 300, 30  # 300 months of 30 daily rows each
TRAIN_END, VALID_END = 100, 140   # months 0-99 train, 100-139 validate, 140-299 are the deployment period
LAG, REVISION_DELAY = 10, 15      # first release 10 days after the period ends, revised 15 days later
REVISED_SD = 0.1                  # the revised value is close to the truth, whatever the first release was


def generate(first_release_sd, seed):
    """A monthly indicator with a first release (noisy) and a later revision (close to the truth), and daily rows.
    Each daily row concerns the month that just ended, so its label depends on that month's true indicator."""
    rng = np.random.default_rng(seed)
    truth = np.zeros(MONTHS)
    for m in range(1, MONTHS):
        truth[m] = 0.6 * truth[m - 1] + rng.normal(0, 0.8)
    first = truth + rng.normal(0, first_release_sd, MONTHS)
    revised = truth + rng.normal(0, REVISED_SD, MONTHS)

    t = np.arange(MONTHS * DAYS)                    # absolute day of each row: the row's prediction cutoff
    month = t // DAYS
    period = np.maximum(month - 1, 0)               # the indicator period the row is about
    own = rng.normal(size=len(t))                   # a feature known inside the table
    y = truth[period] + 0.5 * own + rng.normal(0, 0.7, len(t))

    # Event-date join: the revised value of the row's period, which exists only weeks after the cutoff.
    event_date = revised[period]
    # As-of join: for each row, the latest period whose first release is out by the cutoff, in its latest published version.
    as_of = np.zeros(len(t))
    for age in (0, 1):                              # try the row's own period, then the one before it
        p = np.maximum(period - age, 0)
        released = DAYS * (p + 1) + LAG <= t
        revised_out = DAYS * (p + 1) + LAG + REVISION_DELAY <= t
        value = np.where(revised_out, revised[p], first[p])
        as_of = np.where(released & (as_of == 0), value, as_of)   # 0 means nothing eligible found yet
    return month, np.column_stack([own, event_date]), np.column_stack([own, as_of]), y


def one_series(first_release_sd, seed):
    month, X_event, X_asof, y = generate(first_release_sd, seed)
    train, valid, deploy = month < TRAIN_END, (month >= TRAIN_END) & (month < VALID_END), month >= VALID_END
    out = {}
    # Event-date pipeline: train and validate on revised values, then deploy where only as-of values exist.
    model = Ridge(1.0).fit(X_event[train], y[train])
    out["event_valid"] = r2_score(y[valid], model.predict(X_event[valid]))
    out["event_deploy"] = r2_score(y[deploy], model.predict(X_asof[deploy]))
    # As-of pipeline: the same point-in-time join in training, validation and deployment.
    model = Ridge(1.0).fit(X_asof[train], y[train])
    out["asof_valid"] = r2_score(y[valid], model.predict(X_asof[valid]))
    out["asof_deploy"] = r2_score(y[deploy], model.predict(X_asof[deploy]))
    return out


def run(first_release_sd):
    series = [one_series(first_release_sd, SEED * 1000 + i) for i in range(REPLICATES)]
    keys = ["event_valid", "event_deploy", "asof_valid", "asof_deploy"]
    return clean({
        "first_release_sd": first_release_sd,
        **{k: float(np.mean([s[k] for s in series])) for k in keys},
        "sd": {k: float(np.std([s[k] for s in series])) for k in keys},
        "replicates": REPLICATES, "lag_days": LAG, "revision_days": REVISION_DELAY,
        "deployment_rows": (MONTHS - VALID_END) * DAYS,
    })

Measure it across the control

The control is noise in the first release (standard deviation of its error). Each value below runs the whole experiment from the generator up.

Calculation code
import pandas as pd
from kaggle_companion.activities.ch30 import explain

VALUES = [0, 0.3, 0.6, 1.0]
results = {value: run(value) for value in VALUES}
table = pd.DataFrame({str(v): explain(results[v], v)['metrics'] for v in VALUES})
print(table.to_string())
                              0    0.3    0.6    1.0
Event-date validation     0.691  0.691  0.691  0.691
Event-date at deployment  0.553  0.527  0.450  0.266
As-of validation          0.536  0.517  0.468  0.385
As-of at deployment       0.562  0.543  0.494  0.412
Validation inflation      0.138  0.164  0.241  0.425

Look at it

The figure shows the default setting, noise in the first release (standard deviation of its error) = 0.6.

Calculation code
import matplotlib.pyplot as plt
from kaggle_companion.activities.ch30 import draw, NCOLS, HEIGHT

DEFAULT = 0.6
fig, axes = plt.subplots(1, NCOLS, figsize=(6.6 if NCOLS == 1 else 10.4, HEIGHT), layout='constrained')
draw(axes, results[DEFAULT], DEFAULT)
plt.show()
Saved figure from this chapter calculation

What the result says

With first-release noise 0.6, the event-date join validates at 0.691 but scores 0.450 at deployment, 0.691 - 0.450 = 0.241 of inflation. The as-of join validates at 0.468 and scores 0.494, a difference of -0.026. Training on the event-date join also costs 0.044 of deployment R-squared (0.494 for the as-of model against 0.450).

Apply this to your competition

Book location: Chapter 30, A Version-Aware Join.

Technical corrections

Apply a lesson from this chapter

Select a lesson whose conditions match your project. State how you would test it and what would make you reject it.

Check external-label compatibility before increasing training data

Conditions

  • external medical datasets use different target definitions

Action

  • Proposed adaptation of source observation: Audit label definitions and mapping before adding external examples.

Check

  • Proposed verification: Manually inspect source-specific positive and negative labels and compare matched external-data ablations.

Limits

  • Incorrect labels are suggested rather than established; the source does not report a numeric effect.

Find source links and value grades in the lesson atlas

Audit future-click features against prediction-time availability

Conditions

  • an offline click-classification batch contains later events

Action

  • Proposed adaptation of source observation: Audit whether future and all-batch click features are permitted by the task and available at the intended prediction time.

Check

  • Proposed verification: For online use recompute features using only past events and compare performance loss.

Limits

  • These are configured feature names with no implementation details or ablation; future-event availability is a proposed audit, not an author validation claim.

Find source links and value grades in the lesson atlas

Canonicalize molecular strings and audit near-duplicate fold leakage

Conditions

  • external molecular datasets repeat molecules with different notation or labels

Action

  • Proposed adaptation of source observation: Canonicalize molecular identity, track label-source conflicts and compare exact versus near-duplicate group isolation.

Check

  • Proposed verification: Audit fold molecule identities and quantify score sensitivity and filtering cost.

Limits

  • Near-duplicate filtering had little measured impact here and cannot substitute for fixing the original leakage bug.

Find source links and value grades in the lesson atlas

Match augmentation domains for language QA

Conditions

  • external QA examples have a different domain distribution

Action

  • Proposed conditional application: Check domain alignment before adding randomly sampled external QA examples.

Check

  • Proposed check: Compare domain-matched and random external QA additions on untouched target-domain questions by length/domain.

Limits

  • Domain mismatch is author attribution; tokenizer length limits also confound outcomes.

Find source links and value grades in the lesson atlas

Corroborate meter anomalies across neighboring buildings

Conditions

  • multiple meters at a site show simultaneous suspicious values

Action

  • Proposed conditional application: Check spikes, constant streaks and visually detected anomalies across all buildings at a site before filtering.

Check

  • Proposed check: Overlay suspected events across meters, check outages/weather and compare filtered versus retained training on time holdouts.

Limits

  • Common real events can resemble shared meter faults; filtering may remove useful extremes.

Find source links and value grades in the lesson atlas

Allocate synthetic reasoning samples by problem difficulty

Conditions

  • building synthetic math reasoning data with verifier access

Action

  • Proposed adaptation of source observation: Estimate difficulty from pass rates, sample more hard problems, verify answer equivalence and separately track unverified majority-answer labels.

Check

  • Proposed verification: Audit correctness by difficulty bin and compare equal versus difficulty-based sampling.

Limits

  • Model verification and majority answers can be wrong; generation is expensive.

Find source links and value grades in the lesson atlas

Deduplicate comments using relevant semantic columns

Conditions

  • the same labeled rule/comment occurs across subreddits

Action

  • Proposed conditional application: Exclude subreddit before deduplication to avoid retaining cross-subreddit duplicates.

Check

  • Proposed check: Audit contradictory labels and deduplicate by justified text/rule keys before group splitting; compare duplicate counts and holdout score.

Limits

  • Subreddit can change meaning; remove only when it is not part of target semantics.

Find source links and value grades in the lesson atlas

Rescale noisy external labels against a trusted teacher

Conditions

  • external label scales differ from the host domain

Action

  • Proposed conditional application: Fit isotonic mapping from external raw labels to host-trained ensemble predictions and blend mapped and raw labels, tuning by dataset.

Check

  • Proposed check: Fit teacher and rescaling inside outer folds; compare raw, mapped and blended labels by dataset and inspect discarded chemical regions.

Limits

  • Teacher bias can erase novel chemistry; nested tuning and independent evaluation are necessary.

Find source links and value grades in the lesson atlas

Use held-out predictions for a source-specific label-noise audit

Conditions

  • training labels may have source-dependent noise

Action

  • Proposed adaptation of source observation: Generate predictions on each held-out training fold and audit disagreement separately by source before choosing a filtering threshold.

Check

  • Proposed verification: Manually inspect flagged and retained examples; compare filtering on untouched source-stratified validation.

Limits

  • Prediction disagreement does not prove annotation error; the source-specific thresholds and 20% exclusion have no isolated gain here.

Find source links and value grades in the lesson atlas

Constrain duplicate assignments by remaining label counts

Conditions

  • test chunks are drawn without replacement from an available labeled reference set

Action

  • Proposed adaptation of source observation: Group identical decoded chunks; subtract observed training occurrences; sample assignments without replacement.

Check

  • Proposed verification: Check conservation of reference label counts and known reconstructed rows.

Limits

  • The sampling design must really be without replacement; incorrect assumptions force wrong labels.

Find source links and value grades in the lesson atlas

Audit anomalous positive examples before excluding them

Conditions

  • positive labels have anomalously little observable supporting behavior

Action

  • Proposed adaptation of source observation: Inspect anomalous positives and compare retention/exclusion as an explicit sensitivity analysis.

Check

  • Proposed verification: Evaluate on representative held-out positives and document uncertainty in label rationale.

Limits

  • Exclusion may remove valid difficult cases; the source hypothesis is not proof that labels were wrong.

Find source links and value grades in the lesson atlas

Check whether ambiguous values affect traversed decision paths

Conditions

  • a small sequence dataset has rare ambiguous characters

Action

  • Proposed conditional application: Inspect whether ambiguous positions occur on actual prediction paths before investing in imputation.

Check

  • Proposed check: Trace paths on ambiguous examples and perturb ambiguous values, then recheck after refitting or changing features.

Limits

  • Only seven ambiguous training rows were removed; new trees may use positions previously irrelevant.

Find source links and value grades in the lesson atlas

Use shared generation metadata to resolve ambiguous chunks

Conditions

  • chunks of the same reference document share generation metadata

Action

  • Proposed adaptation of source observation: Intersect possible reference documents with each chunk’s difficulty and propagate compatible class assignments.

Check

  • Proposed verification: Verify the metadata invariant across known training chunks before applying it.

Limits

  • Puzzle-specific information; access to original documents and the invariant are required.

Find source links and value grades in the lesson atlas

Keep raw predictions while testing a suspected label offset

Conditions

  • evaluation residuals suggest a constant target bias

Action

  • Proposed conditional application: Investigate a suspected constant label offset using an independent trusted labeled sample and retain raw predictions as a separate baseline.

Check

  • Proposed check: Test suspected offsets against an independent trusted labeled sample, retain raw outputs, and separate label-pipeline diagnosis from benchmark-probe selection.

Limits

  • Coefficient0.5644is leaderboard-tuned and source includes later probes; p-value<0.01does not imply99%probability labels are wrong.

Find source links and value grades in the lesson atlas

Audit soft leakage before reusing powerful context features

Conditions

  • context aggregates can contain information unavailable at serving time

Action

  • Proposed adaptation of author advice: Map each feature to information available at prediction time and compare with suspicious query-context features removed.

Check

  • Proposed verification: Replay feature availability at historical decision times.

Limits

  • The source reports a warning rather than a deployment audit.

Find source links and value grades in the lesson atlas

Compare kernel-informed training-point selection with full-data trees

Conditions

  • low-data demographic regression may contain unevenly useful observations

Action

  • Proposed adaptation of source observation: Proposed: formalize and cross-validate kernel-based point-value selection before fitting trees.

Check

  • Proposed verification: Compare selected versus all-data trees with selection inside the training fold.

Limits

  • The packet lacks the actual point-value definition, selection threshold and comparative result.

Find source links and value grades in the lesson atlas

Audit transductive preprocessing boundaries

Conditions

  • numeric and categorical preprocessing across train and test

Action

  • Proposed: record whether scaling and category vocabulary are fitted on concatenated train and test rows.

Check

  • Proposed: compare fold-local fitting with the observed concatenated-data preprocessing and ensure test access is permitted.

Limits

  • This is observed transductive preprocessing, not proof that it is valid for every deployment. Proposed stricter evaluation fits learned transforms within each training fold.

Find source links and value grades in the lesson atlas

Retrieve repository usage examples before generating reproduction tests

Conditions

  • smaller local code models invent imports or initialization

Action

  • Proposed conditional application: Retrieve related tests, imports and function/class skeletons before generating issue-reproduction tests.

Check

  • Proposed check: Compare context/no-context tests on isolated issue fixtures; count valid imports and true reproductions.

Limits

  • Retrieved examples may be irrelevant; generated source is untrusted and requires controlled execution in proposed reuse.

Find source links and value grades in the lesson atlas

Require a clean reproduction before assessing a repair

Conditions

  • generated tests can fail for unrelated reasons

Action

  • Proposed conditional application: Run candidate reproduction tests, retain only those reproducing the issue without unrelated errors, retry one higher-temperature batch, and skip if none reproduce.

Check

  • Proposed check: Verify failure matches the issue on original code, passes expected fixed behavior and preserves regression tests; track skipped coverage.

Limits

  • Printed strings do not prove test validity; abstention reduces coverage.

Find source links and value grades in the lesson atlas

Use plain resizing as a preprocessing baseline

Conditions

  • retinal images already have usable image quality

Action

  • Proposed adaptation of source observation: Start with simple resizing and compare any proposed image corrections against that baseline.

Check

  • Proposed verification: Hold architecture and split fixed while comparing preprocessing alternatives.

Limits

  • Image-quality judgment is source-specific and no preprocessing ablation is supplied.

Find source links and value grades in the lesson atlas

Audit geocoding failures before creating spatial features

Conditions

  • housing addresses have inconsistent geocoding coverage

Action

  • Proposed adaptation of source observation: Track geocoding status and audit coordinates before using spatial predictors.

Check

  • Proposed verification: Check map locations, missingness by neighborhood and held-out effects of corrected coordinates.

Limits

  • Manual correction is costly and external geocoding accuracy may vary.

Find source links and value grades in the lesson atlas

Route expensive data generation using predicted failure risk

Conditions

  • a fast simulation configuration crashes often and a stable one is much slower

Action

  • Proposed conditional application: Train a failure-risk classifier from cheap descriptors/conformer statistics and route easy polymers to fast simulation while downsampling difficult cases.

Check

  • Proposed check: Evaluate failure calibration and end-to-end throughput on untouched polymers; audit the generated distribution and retain a route for difficult cases.

Limits

  • Fast search fails for roughly half the polymers; downsampling difficult cases can bias training coverage.

Find source links and value grades in the lesson atlas

Validate external label cleaning on original-domain holdouts

Conditions

  • external polymer labels have biases and outliers

Action

  • Proposed conditional application: Train with selected external data while computing five-fold validation only on original host data.

Check

  • Proposed check: Audit external-host overlap and teacher fitting within outer folds, then compare external-data configurations only on untouched host-domain samples.

Limits

  • Teacher cleaning and repeated Optuna selection can leak held-out information unless nested; source's p-value interpretation of label-error probability is unjustified.

Find source links and value grades in the lesson atlas

Verify corpus-derived identifier candidates against normalized article text

Conditions

  • external dataset-article mappings generate mention candidates

Action

  • Proposed conditional application: Unicode-normalize and remove text whitespace as appropriate before matching candidate DOIs, retaining only identifiers present in PDF or XML.

Check

  • Proposed check: Test Unicode and whitespace variants against annotated identifier spans and measure mention precision and recall before and after normalization.

Limits

  • Corpus omissions constrain recall; aggressive whitespace removal can introduce false matches.

Find source links and value grades in the lesson atlas

Generate search-replace edits then validate patches and regressions

Conditions

  • LLM repair outputs are scored by correct patches with regression risk

Action

  • Proposed adaptation of source observation: Use explicit contiguous search-replace edits, validate conversion/application and compare selected regression tests with the unpatched baseline.

Check

  • Proposed verification: Measure valid-patch rate and repair/regression outcomes; run model-generated code only in an appropriate isolated harness.

Limits

  • Passing a selected test subset does not prove correctness and the pipeline executes generated code.

Find source links and value grades in the lesson atlas

Reconcile reconstructed text with keyboard-edit logs

Conditions

  • cursor positions and reported text changes disagree

Action

  • Proposed conditional application: Use nearest fuzzy matching and correct Undo operations during reconstruction, while recording unresolved events.

Check

  • Proposed check: Replay known edits including Undo and compare reconstructed text with expected final text; log unresolved events and test their downstream effect.

Limits

  • Fuzzy correction can choose an incorrect match; the source still had 142 unexpected events.

Find source links and value grades in the lesson atlas

Group metadata classification by article

Conditions

  • multiple dataset mentions belong to one scientific article

Action

  • Proposed conditional application: Validate primary/secondary DOI classification with article-grouped folds, using dataset/article title and author similarities.

Check

  • Proposed check: Audit article isolation across folds and report type-only and end-to-end mention/type scores separately.

Limits

  • The 0.87 type score conditions on 302 true-positive mentions; it cannot be compared directly to end-to-end 0.82 as a method gain.

Find source links and value grades in the lesson atlas