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 52: Time Series Feature Engineering

Try the decision first

How much does a backtest flatter a model whose lag features read days that would not yet exist at the forecast origin?

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 much does a backtest flatter a model whose lag features read days that would not yet exist at the forecast origin?

A perfectly aligned array can still contain values that are unavailable when the forecast is made. A lag-1 column is safe for a next-day forecast and a leak for a three-day one, and the backtest cannot tell the difference because it holds the true values.

Constructed data with strong short-range autocorrelation; the sizes of these gaps are properties of this generator, not a competition result. The production-style score is only modestly worse than the direct model, so the main damage of a leaky builder is the false backtest, not the final forecast.

The experiment

Ten constructed panels of 30 daily series, each with a weekday profile and autocorrelated noise. A gradient boosting regressor forecasts the value h days after the origin, where h is the control, and is scored by mean absolute error (MAE) on the 150 days after the training period. Two pipelines are built: a shift-based builder that creates lags 1, 2, 3, 7, 14 and 21 and a 7-day mean ending yesterday, and a direct builder that keeps only lags of at least h days and a 7-day mean ending at the origin. The shift-based model is scored twice: in a backtest with the true lag values, and as production would run it, with each lag that is still in the future filled by the latest value known at the origin. An origin test then perturbs every value after the origin and counts the feature columns that move.

Calculation code
import numpy as np
from sklearn.ensemble import HistGradientBoostingRegressor

from kaggle_companion.activities._common import clean

SEED = 52
REPLICATES = 10             # independent panels of constructed series; every estimate is their mean
N_SERIES, DAYS, TRAIN_END = 30, 450, 300
LAGS = [1, 2, 3, 7, 14, 21]  # the lag set a shift-based builder would create


def generate(rng):
    """Daily series with a weekday profile and autocorrelated noise (AR coefficient 0.8), one row per series."""
    series = []
    for _ in range(N_SERIES):
        level = rng.uniform(50, 150)
        profile = rng.normal(0, 1, 7)
        profile = (profile - profile.mean()) * level * 0.06
        noise = np.zeros(DAYS)
        for t in range(1, DAYS):
            noise[t] = 0.8 * noise[t - 1] + rng.normal(0, level * 0.04)
        series.append(level + profile[np.arange(DAYS) % 7] + noise)
    return np.array(series)


def features(y, target_days, horizon, kind):
    """Feature columns for the target days. The forecast origin is `horizon` days earlier.

    leaky:  lag k reads day t-k, which is what shift(k) does; at horizon > k that day is still in the future.
    stale:  the same columns as production would fill them, with the latest value known at the origin.
    honest: built at the origin: keep only lags k >= horizon, and a 7-day mean ending at the origin.
    """
    origin = target_days - horizon
    cols = []
    for k in LAGS:
        if kind == "honest" and k < horizon:
            continue
        source = np.minimum(target_days - k, origin) if kind == "stale" else target_days - k
        cols.append(y[:, source])
    end = target_days - 1 if kind == "leaky" else origin   # the rolling mean ends yesterday, or at the origin
    total = np.concatenate([np.zeros((len(y), 1)), np.cumsum(y, axis=1)], axis=1)
    cols.append((total[:, end + 1] - total[:, end - 6]) / 7)
    cols.append(np.tile(target_days % 7, (len(y), 1)))     # weekday is known in advance
    return np.column_stack([c.reshape(-1) for c in cols])


def new_model():
    return HistGradientBoostingRegressor(max_iter=80, learning_rate=0.1, max_leaf_nodes=12, random_state=0)


def one_panel(horizon, replicate):
    rng = np.random.default_rng(SEED * 1000 + replicate)
    y = generate(rng)
    train = np.arange(30, TRAIN_END)
    test = np.arange(TRAIN_END + horizon, DAYS)             # every test origin is after the last training day
    y_train, y_test = y[:, train].reshape(-1), y[:, test].reshape(-1)
    leaky = new_model().fit(features(y, train, horizon, "leaky"), y_train)
    honest = new_model().fit(features(y, train, horizon, "honest"), y_train)
    mae = lambda pred: float(np.mean(np.abs(pred - y_test)))
    out = {"backtest": mae(leaky.predict(features(y, test, horizon, "leaky"))),
           "deployed": mae(leaky.predict(features(y, test, horizon, "stale"))),
           "honest": mae(honest.predict(features(y, test, horizon, "honest"))),
           "seasonal_naive": mae(y[:, test - 7].reshape(-1))}  # same weekday last week, usable at every horizon here
    # Origin test from the chapter: change every value published after the origin and see which features move.
    target = np.array([test[0]])
    shifted = y.copy()
    shifted[:, target[0] - horizon + 1:] += rng.normal(0, 10, shifted[:, target[0] - horizon + 1:].shape)
    for kind in ("leaky", "honest"):
        before, after = features(y, target, horizon, kind), features(shifted, target, horizon, kind)
        out["moved_" + kind] = int((np.abs(before - after) > 1e-9).any(axis=0).sum())
        out["columns_" + kind] = before.shape[1]
    return out


def run(horizon):
    panels = [one_panel(horizon, i) for i in range(REPLICATES)]
    mean = lambda key: float(np.mean([p[key] for p in panels]))
    keys = ["backtest", "deployed", "honest", "seasonal_naive"]
    return clean({
        "horizon": horizon,
        **{k: mean(k) for k in keys},
        "per_panel": {k: [p[k] for p in panels] for k in keys},
        "moved_leaky": panels[0]["moved_leaky"], "columns_leaky": panels[0]["columns_leaky"],
        "moved_honest": panels[0]["moved_honest"], "columns_honest": panels[0]["columns_honest"],
        "replicates": REPLICATES, "series": N_SERIES, "test_days": DAYS - TRAIN_END - horizon,
    })

Measure it across the control

The control is forecast horizon (days between the origin and the target day). Each value below runs the whole experiment from the generator up.

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

VALUES = [1, 3, 5, 7]
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())
                                         1       3       5       7
Shift-based backtest MAE              4.96    4.96    4.97    4.96
Shift-based, run at the origin        4.96    5.95    6.49    6.28
Direct model MAE                      4.96    5.69    6.03    6.03
Hidden error (direct - backtest)      0.00    0.73    1.06    1.07
Columns that move after the origin  0 of 8  3 of 8  4 of 8  4 of 8

Look at it

The figure shows the default setting, forecast horizon (days between the origin and the target day) = 3.

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

DEFAULT = 3
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

At a horizon of 3 days the shift-based backtest reports an MAE of 4.96. The direct model, which uses only history available at the origin, scores 5.69, so 5.69 - 4.96 = 0.73 is the error the backtest hides. Run at the origin, the shift-based model scores 5.95. The origin test moves 3 of 8 shift-based columns and 0 of 6 direct columns. The seasonal-naive forecast scores 6.83.

Apply this to your competition

Book location: Chapter 52, One-Step and Three-Step Forecasts Use Different Histories.

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.

Forecast related stores within each department

Conditions

  • retail departments share seasonal patterns across stores
  • retail seasonality follows department more than store

Action

  • Proposed adaptation of source observation: Arrange each department’s weekly series into a store panel and compare departmental modelling with independent store models.
  • Proposed conditional application: Build a weeks-by-stores matrix separately for each department and forecast across stores.

Check

  • Proposed verification: Validate on later weeks and check departments with heterogeneous store seasonality.
  • Proposed check: Compare department pooling with independent store-department models at rolling origins, inspect holidays and sparse departments, and enforce historical-only inputs.

Limits

  • The seasonal rationale is author-attributed and the matrix-based model internals are not described.
  • Seasonality attribution is author rationale; the six component models are not fully described in the packet.

Find source links and value grades in the lesson atlas

Audit autoregressive rollout assumptions

Conditions

  • one-step spatial forecasts must extend recursively over a horizon

Action

  • Proposed: average model outputs, append the predicted target channel, and shift the history window.

Check

  • Proposed: measure error at each horizon and test the assumption that the other copied channels can remain unchanged.

Limits

  • Only xi is updated; theta and ustar are copied from the last frame. This assumption and long-horizon quality are not validated by this source.

Find source links and value grades in the lesson atlas

Benchmark an expensive forecast component by marginal return

Conditions

  • one ensemble component takes much longer than the others
  • one additional time-series model dominates ensemble runtime

Action

  • Proposed conditional application: Compare the full ensemble with the version omitting Fourier ARIMA before accepting the extra runtime.
  • Proposed adaptation of source observation: Compare the ensemble with and without the slow component under the required deadline.

Check

  • Proposed check: Ablate the expensive component on the same rolling folds, record total wall-clock and serving cost, and compare marginal error improvement.
  • Proposed verification: Record paired forecast loss and total training time on the same holdout.

Limits

  • Historical runtimes are hardware-dependent; approximate final scores are a method-inclusion comparison rather than proof of rank causality.
  • The metric is unnamed and scores approximate; inclusion may change the equal-weight ensemble beyond the added model’s standalone quality.

Find source links and value grades in the lesson atlas

Check compatibility before blending horizon forecasts

Conditions

  • direct-horizon and recursive predictions have matching rows and output coordinates

Action

  • Proposed: check prediction shapes before combining the two forecast arrays.

Check

  • Proposed: also assert identical ID ordering and timestep-pixel flattening order before blending; compare the blend to both components.

Limits

  • Shape equality alone cannot prove row identity or coordinate alignment. The weights are an implementation example, without a demonstrated gain.

Find source links and value grades in the lesson atlas

Blend naive and seasonal automated forecasting baselines

Conditions

  • many short retail time series need per-series forecasts

Action

  • Proposed conditional application: Combine NaiveForecaster and AutoARIMA for each series and evaluate SMAPE.

Check

  • Proposed check: Backtest naive, AutoARIMA and their blend at the target horizon using SMAPE per series and overall.

Limits

  • No blend weights, seasonality configuration or isolated gain supplied.

Find source links and value grades in the lesson atlas

Evaluate holiday weekday alignment after weekly forecasting

Conditions

  • weekly sales near Christmas depend on its weekday placement
  • a moving holiday weekday reallocates weekly sales

Action

  • Proposed adaptation of source observation: Compare a holiday-week alignment correction with the unadjusted weekly forecast.
  • Proposed conditional application: Apply and validate a Christmas-adjacent weekly transformation reflecting the changing day of week.

Check

  • Proposed verification: Test on historical Christmas periods whose holiday weekdays differ.
  • Proposed check: Compare holiday-week alignment rules under year-held-out validation and inspect adjacent-week totals and department-specific shifts.

Limits

  • The actual transformation is only linked externally, so this packet supports the adjustment decision but not a reproducible formula.
  • Exact source transformation is unspecified; holiday effects depend on sales aggregation and shopping behavior.

Find source links and value grades in the lesson atlas

Use a horizon-aware growth-adjusted naive forecast as a baseline

Conditions

  • series show sustained long-term growth

Action

  • Proposed adaptation of source observation: Compare an unadjusted last-value baseline with a horizon-scaled growth-adjusted baseline.

Check

  • Proposed verification: Tune growth using rolling historical origins rather than the final evaluation horizon.

Limits

  • The 5.5% factor is competition-specific and no numeric MASE comparison is given.

Find source links and value grades in the lesson atlas

Compare game-week encoding without assuming complex models improve

Conditions

  • sports tabular inputs include a seasonal week variable

Action

  • Proposed adaptation of source observation: Compare categorical week encoding in a simple baseline before adopting complex models.

Check

  • Proposed verification: Use season/time-held-out validation and check model/encoding effects separately.

Limits

  • The packet gives no tuning/split detail or numeric model comparison; outcome is local.

Find source links and value grades in the lesson atlas

Use robust forecast aggregation to contain disastrous components

Conditions

  • a few series produce implausible model forecasts

Action

  • Proposed conditional application: Compare global validation-weighted forecasts with a median of multiple algorithms and training windows.

Check

  • Proposed check: Compare median, weighted mean and their blend under rolling origins, inspecting catastrophic series errors and horizon-wise MASE.

Limits

  • A median can suppress useful extreme forecasts; source's leaderboard-tuned1.04year-two growth factor is not transferable.

Find source links and value grades in the lesson atlas

Route missing time-series entries by imputation suitability

Conditions

  • some missing weather intervals interpolate well while others need regression

Action

  • Proposed conditional application: Compare interpolation and linear-regression imputation for different missing-entry conditions.

Check

  • Proposed check: Hide known values using realistic gap patterns, compare interpolation and regression by gap length and season, and enforce available-neighbor timing.

Limits

  • Routing thresholds are absent; two-sided interpolation requires future neighbors and may be unsuitable for live forecasting.

Find source links and value grades in the lesson atlas

Compare simple trend extrapolation before high-degree polynomials

Conditions

  • a forecast extrapolates a historical trend

Action

  • Proposed adaptation of source observation: Compare linear trend forecasting against higher-order polynomial extrapolations.

Check

  • Proposed verification: Evaluate at the required horizon across several historical origins and inspect extreme extrapolated values.

Limits

  • The packet supplies a qualitative comparison only and does not specify preprocessing or series-level results.

Find source links and value grades in the lesson atlas

Trim unreliable overlap boundaries in chunked time-series inference

Conditions

  • sequence models predict long series through overlapping chunks

Action

  • Compare overlap averaging with boundary trimming while guaranteeing coverage of the original timeline.

Check

  • Proposed verification: Check global timestamp coverage and held-out event performance at chunk boundaries.

Limits

  • Trimming requires enough overlap to preserve coverage; chosen durations are source-specific.
  • The CV 0.8117 to 0.8142 comparison is author-reported within a sequential single-model recipe; the passage does not establish replication, additive gain or final-ensemble attribution.

Find source links and value grades in the lesson atlas

Compare per-level and global normalization representations

Conditions

  • vertical scientific features carry both local anomalies and absolute level structure

Action

  • Proposed adaptation of source observation: Compare per-level and across-level standardized representations and their concatenation as a proposed adaptation.

Check

  • Proposed verification: Compute normalization on training data and ablate representations on held-out regimes.

Limits

  • This packet ends before the full third representation; do not invent it or assume the earlier ASL example proves gain here.

Find source links and value grades in the lesson atlas

Aggregate event history across meaningful time horizons

Conditions

  • behavioral outcomes depend on recent and cumulative interaction history

Action

  • Proposed adaptation of source observation: Construct cutoff-safe multi-horizon aggregates and task-related game/assessment mappings.

Check

  • Proposed verification: Ablate horizons and check interval and clip-duration edge cases.

Limits

  • Shared-device rationale was a hypothesis; next-event features require careful cutoff availability.

Find source links and value grades in the lesson atlas

Select event timestamps by expected tolerance coverage

Conditions

  • event scoring matches predictions within several time tolerances

Action

  • Proposed adaptation of source observation: Convert event probabilities into expected coverage for each tolerance, select the highest-value timestamp and discount mass already covered.

Check

  • Proposed verification: Compare against ordinary peak picking and test duplicate suppression on known event sequences.

Limits

  • This decoder depends on the exact matching metric and minute-aligned labels; it is not universal peak detection.

Find source links and value grades in the lesson atlas

Align timestamps before joining sensor and weather data

Conditions

  • sensor records and external weather metadata use different timezones

Action

  • Proposed conditional application: Correct timezone offsets before constructing weather joins or time-dependent features.

Check

  • Proposed check: Check known timestamp-weather events after conversion, audit timezone and daylight-saving boundaries, and verify join cardinality by site.

Limits

  • Source does not give offset values; unseen sites and daylight-saving rules need task-specific validation.

Find source links and value grades in the lesson atlas

Construct promotion-aware sales-history windows

Conditions

  • forecasting daily sales from a sufficiently long history

Action

  • Proposed adaptation of source observation: Create trailing multi-window sales averages conditional on day of week and promotion status.

Check

  • Proposed verification: Recompute features at each forecast cutoff and check that no future sales enter any window.

Limits

  • Feature importance is the author’s qualitative assessment; individual windows were not ablated.

Find source links and value grades in the lesson atlas

Audit periodic device artifacts and calendar shortcuts

Conditions

  • sensor data contain device-removal artifacts and annotation timing biases

Action

  • Proposed adaptation of source observation: Detect artifact periodicity and compare masking, periodic flags and selected calendar features.

Check

  • Proposed verification: Evaluate artifact detection and event accuracy on unseen participants/time periods.

Limits

  • Minute bias may be annotation-specific; filtering can suppress real events if artifacts are misidentified.

Find source links and value grades in the lesson atlas

Predict a horizon through output channels

Conditions

  • spatial forecasts have a fixed output horizon

Action

  • Proposed: emit output_channels times horizon channels and reshape them into explicit timestep and output-channel axes.

Check

  • Proposed: compare direct-horizon forecasts with recursive one-step forecasts on held-out simulations and verify reshape ordering.

Limits

  • This source shows an implementation, without an isolated gain, execution result, or confirmed final-submission provenance. Historical dependencies and dataset assumptions require local checks.

Find source links and value grades in the lesson atlas

Represent calendar events by relative time

Conditions

  • sales depend on event timing rather than fixed calendar date

Action

  • Proposed adaptation of source observation: Encode days relative to known holidays or store events alongside calendar features.

Check

  • Proposed verification: Test at later forecast cutoffs and ensure event dates were available at prediction time.

Limits

  • The source does not quantify the contribution of individual relative-time indicators.

Find source links and value grades in the lesson atlas

Compare decomposition and prior-period scale correction in energy forecasting

Conditions

  • energy forecasts show prior-period systematic scale bias

Action

  • Proposed adaptation of source observation: Estimate a calibration factor on an earlier labeled period and compare corrected with uncorrected future predictions after anomaly preprocessing.

Check

  • Proposed verification: Backtest chronologically, fitting decomposition/interpolation only from available past observations.

Limits

  • The April ratio may not remain stable in May; no isolated correction ablation is reported.

Find source links and value grades in the lesson atlas

Learn temporal postprocessing from neighboring probabilities

Conditions

  • event classification outputs have useful temporal context

Action

  • Proposed conditional application: Fit a boosted postprocessor on blended video/tabular probabilities from neighboring steps, with subtype-specific windows.

Check

  • Proposed check: Fit the postprocessor on out-of-fold base scores, group by games, and compare causal and retrospective windows with latency accounting.

Limits

  • Future neighboring steps are unavailable to a live causal detector; postprocessor training needs out-of-fold base predictions.

Find source links and value grades in the lesson atlas

Build a separate model per forecast horizon and variable as a fast baseline

Conditions

  • multivariate forecasting needs a rapid direct baseline

Action

  • Proposed adaptation of source observation: Fit one regressor per horizon-variable pair from lag features; then tune lag count and objective against the specified metric.

Check

  • Proposed verification: Use chronological backtests, check target offsets and account for all model runtimes.

Limits

  • Eight lags were arbitrary, and source used RMSE-related training despite MAE evaluation.

Find source links and value grades in the lesson atlas

Anneal event targets from tolerant regions toward sharp peaks

Conditions

  • event labels have temporal tolerance but final predictions need precise peaks

Action

  • Proposed adaptation of source observation: Initialize distance-decaying event targets and gradually shrink noncentral support during training.

Check

  • Proposed verification: Compare peak localization and metric at fixed training budget against static targets.

Limits

  • The source asserts a sharpening mechanism; do not assume benefit under exact-point labels.

Find source links and value grades in the lesson atlas

Decode categorical event semantics into features

Conditions

  • an ordinal event-sequence dataset has very few raw columns

Action

  • Proposed conditional application: Investigate the meaning and classes of event codes to construct additional sequence features.

Check

  • Proposed check: Ablate semantic event groups on a sequence-respecting holdout against raw event IDs.

Limits

  • Feature recipe needs domain interpretation; rank attribution is not an ablation.

Find source links and value grades in the lesson atlas

Average overlapping frame predictions with boundary padding

Conditions

  • sound-event models produce frame outputs for overlapping chunks

Action

  • Proposed adaptation of source observation: Map frame predictions to global timestamps, average overlapping views, pad boundaries and remove padding before optional smoothing.

Check

  • Proposed verification: Check alignment and edge intervals and compare with center-only pooling.

Limits

  • The gain is source-reported; repeated contexts increase inference work and smoothing can suppress short calls.

Find source links and value grades in the lesson atlas

Tune candidate windows before event reranking

Conditions

  • a second-stage event model sees peak-centered candidate chunks

Action

  • Measure candidate recall and positive/negative balance as peak-centered window size and step size change.

Check

  • Audit OOF first-stage inputs and compare candidate recall, calibration and complete reranker runtime.

Limits

  • OOF handling is proposed because this packet does not document it; broad windows add negatives and compute.
  • JIT acceleration of incremental decoding updates is a separate implementation practice.

Find source links and value grades in the lesson atlas

Retest prediction smoothing as model quality improves

Conditions

  • a time-series ensemble is already relatively smooth

Action

  • Proposed conditional application: Reevaluate smoothing instead of assuming it remains helpful after ensemble improvements.

Check

  • Proposed check: Retest several smoothing strengths against no smoothing on blocked local holdouts after each model upgrade; inspect peaks.

Limits

  • Evidence is public-LB failure, not universal rejection of smoothing.
  • Smoothing can erase real transient peaks.

Find source links and value grades in the lesson atlas

Construct direct multi-horizon training windows

Conditions

  • spatial forecasting requires an entire future sequence

Action

  • Proposed: require enough input-plus-horizon frames and slice future targets immediately after each input window.

Check

  • Proposed: assert that every target begins after its input and that the output horizon matches the model head; split simulations before window creation.

Limits

  • This source shows an implementation, without an isolated gain, execution result, or confirmed final-submission provenance. Historical dependencies and dataset assumptions require local checks.

Find source links and value grades in the lesson atlas

Generate random trajectory prefixes on the fly

Conditions

  • prediction uses partial sequences but labels are available for complete sequences
  • precomputing every trajectory prefix would be too expensive

Action

  • Proposed adaptation of source observation: Sample prefixes dynamically during training with a cutoff distribution matching intended inference.
  • Proposed conditional application: Iterate through complete trips and dynamically generate one hundred random cuts per trip.

Check

  • Proposed verification: Validate held-out complete-trip groups at several prefix lengths and measure data-generation cost.
  • Proposed check: Compare sampled prefix distribution with inference lengths, ensure prefixes from one trip share a split, and measure loader throughput and memory.

Limits

  • Many cuts from one trip remain correlated; sampling/validation must keep trips separate.
  • One hundred cuts is a source setting; dynamic sampling must preserve trip independence and evaluation horizon distribution.

Find source links and value grades in the lesson atlas

Test traffic and hotspot covariates in air-quality forecasting

Conditions

  • air quality forecasts may depend on traffic or nearby hotspots

Action

  • Proposed recipe: compare a SARIMAX model using these external covariates with a model without them.

Check

  • Proposed check: Use rolling-origin forecasts with timestamped covariate availability, ablate each external source, and test missing-source fallback.

Limits

  • Future covariates or revised data can leak outcomes; source gives no split or publication-delay details.

Find source links and value grades in the lesson atlas

Use an equal-weight weekly forecast ensemble as a baseline

Conditions

  • several weekly forecasting models are available

Action

  • Proposed adaptation of source observation: Start with an equal-weight prediction average before introducing tuned blend weights.

Check

  • Proposed verification: Compare against each component and retain identical holiday postprocessing across candidates.

Limits

  • The packet does not enumerate all six components or isolate the average’s gain.

Find source links and value grades in the lesson atlas

Keep forecast members and aggregate forecasts as ensemble views

Conditions

  • numerical weather input contains multiple forecast members

Action

  • Proposed conditional application: Train one model per forecast member plus median and daily-sum views, using the four surrounding grid points and all five intraday values.

Check

  • Proposed check: Compare aggregate-only and member-plus-aggregate blends on contiguous held-out periods; measure training cost and member correlation.

Limits

  • Thirteen models increase cost; the source supplies no isolated member-view gain.

Find source links and value grades in the lesson atlas

Change forecasting strategy beyond the trained horizon

Conditions

  • long-horizon forecasts overfit while near-horizon models are usable

Action

  • Proposed conditional application: Train separate quantile/target/horizon models for one to fourteen days, then use a weekly-average flat continuation for the longer horizon.

Check

  • Proposed check: Backtest by horizon; compare learned long forecasts with flat and seasonal continuation using pinball loss.

Limits

  • Flat continuation misses regime shifts; source manual regional adjustments not reproducible.

Find source links and value grades in the lesson atlas

Represent a variable trajectory by informative endpoints

Conditions

  • a fixed-size destination predictor receives partial GPS sequences

Action

  • Proposed conditional application: Use the first five and last five known points plus learned categorical metadata embeddings as an MLP input.

Check

  • Proposed check: Compare endpoints with full-sequence baselines under identical trip splits, define short/empty-trip handling, and assess error by prefix length.

Limits

  • The source omits short/empty sequence padding policy; intermediate points may matter in other routing tasks.

Find source links and value grades in the lesson atlas

Bound correction from a second localization pass

Conditions

  • a refinement model may return invalid or unstable event times

Action

  • Proposed: validate the refined timestamp and blend a clipped time correction into the coarse estimate.

Check

  • Proposed: measure correction error against coarse estimates and stratify invalid outputs and large shifts.

Limits

  • Clipping can suppress a legitimate large correction; the source provides no isolated effectiveness measurement.

Find source links and value grades in the lesson atlas