Sub topic 7
Assembling the training set end to end
This chapter combines the pieces from earlier chapters into one training-set build. It assumes you can read pandas and SQL window functions, and that you know the difference between event time, ingestion time and prediction time. It also assumes you know what an as-of join does. The goal is a single, repeatable procedure that turns a label table and a feature history into a validated, time-split training set.
The pipeline at a glance
Each stage has one job, and the checks sit between stages so a failure stops the build before a model is trained.
Step 1: Fix the label table
The label table is the spine of the training set. Each row is one training example and must have three things:
- An entity key, such as
customer_id. - A
prediction_ts, the moment at which the model would have made its prediction. - The label, such as
churned, which is the outcome observed afterprediction_ts.
The join below never adds or removes label rows, so the output has exactly the rows you put in. Decide the label rows first and treat them as fixed. If a customer should be scored every month, the label table needs one row per customer per month. Every feature value is chosen relative to that row's prediction_ts, not to the label's observation date.
Check the inputs before joining:
prediction_tshas no nulls.(customer_id, prediction_ts)is unique.- Both timestamp columns use the same type and time zone (preferably UTC).
merge_asof raises an error on mismatched key types, but mixing naive and time-zone-aware timestamps in your own preprocessing causes quiet shifts of hours. Normalize before the join.
Step 2: Prepare the feature history
The feature table must be a history, with one row per entity per time the value was computed. Its time column, here feature_ts, is the moment the value became valid. A table holding only the latest value per customer cannot be joined correctly, because every historical label would see today's value.
Sort the history by feature_ts. merge_asof requires both sides to be sorted on their time keys. It does not sort for you, and with unsorted input it either raises an error or returns wrong matches.
Step 3: Join with a tolerance
The as-of join takes each label row and finds the latest feature row for the same entity with feature_ts <= prediction_ts. The tolerance argument adds a lower bound. A feature older than the tolerance is treated as missing, because an old value is often worse than none. A customer's 30-day average spend from eight months ago says little about them today.
Here is a complete script with small data, so you can run it and read the result.
import pandas as pd
labels = pd.DataFrame({
"customer_id": [1, 1, 2, 3],
"prediction_ts": pd.to_datetime(
["2025-11-01", "2025-12-01", "2025-11-15", "2025-12-10"]
),
"churned": [0, 1, 0, 1],
})
features = pd.DataFrame({
"customer_id": [1, 1, 1, 2, 3],
"feature_ts": pd.to_datetime(
["2025-10-20", "2025-11-20", "2025-12-05", "2025-09-01", "2025-12-11"]
),
"avg_spend_30d": [40.0, 55.0, 12.0, 70.0, 33.0],
})
def build_training_set(labels, features, tolerance="30D"):
labels = labels.sort_values("prediction_ts")
features = features.sort_values("feature_ts")
train = pd.merge_asof(
labels,
features,
left_on="prediction_ts",
right_on="feature_ts",
by="customer_id",
direction="backward",
tolerance=pd.Timedelta(tolerance),
)
joined = train.dropna(subset=["feature_ts"])
assert (joined["feature_ts"] <= joined["prediction_ts"]).all()
assert not train.duplicated(["customer_id", "prediction_ts"]).any()
assert len(train) == len(labels)
return train.reset_index(drop=True)
train = build_training_set(labels, features)
print(train)Running it gives these results:
| customer_id | prediction_ts | feature_ts | avg_spend_30d | Why |
|---|---|---|---|---|
| 1 | 2025-11-01 | 2025-10-20 | 40.0 | Latest row at or before the prediction, 12 days old |
| 2 | 2025-11-15 | missing | NaN | Only row is 75 days old, outside the 30-day tolerance |
| 1 | 2025-12-01 | 2025-11-20 | 55.0 | The 2025-12-05 row is in the future and is skipped |
| 3 | 2025-12-10 | missing | NaN | The only row (2025-12-11) is after the prediction time |
Customer 1 on 2025-12-01 is the leakage case. A join on the latest value per customer would have used 12.0 from 2025-12-05, four days after the prediction. Customer 3 shows the other side of the rule: a row that exists but is later than the prediction time must not be used, even if no earlier row exists.
Step 4: Decide what to do with missing values
After the join, some rows have no feature. Do not hide this. Measure it first:
coverage = train["feature_ts"].notna().mean()
print(f"Feature coverage: {coverage:.0%}")In the example, coverage is 50%, which would be a problem in a real pipeline. You then have three options:
- Drop rows with no feature. This is simple, but the model never sees "cold" customers, and production will send it some.
- Keep the NaN and let a model that handles missing values (such as gradient-boosted trees) deal with it.
- Impute a default, and add a flag column such as
avg_spend_missing.
Whichever you choose, serving must do the same. If production fills missing values with 0 and training dropped those rows, the model meets a population it never trained on. Choose a tolerance that matches how fresh the feature is at serving time. If the online store holds values for at most 30 days, train with a 30-day tolerance.
You can also add feature_age_days = (prediction_ts - feature_ts).dt.days as a model input. Only do this if serving can compute the same age, because otherwise it creates a training-serving mismatch.
Step 5: Run the checks inside the build
The two assertions in build_training_set are the minimum:
- Every joined
feature_tsis at or beforeprediction_ts. This catches a wrong join direction or a wrong timestamp column. - The output has one row per
(customer_id, prediction_ts). This catches a fan-out, which happens if someone later swapsmerge_asoffor an ordinarymergeand the feature table has several rows per entity.
The len(train) == len(labels) check confirms no label row was lost. Later chapters build these into a fuller test suite. For now, keep them inside the function so no caller can skip them.
Step 6: Split by time
Once the table is built, split it by prediction_ts, not at random. A random split puts rows from the future into training and rows from the past into validation, which makes validation look easier than production.
cutoff = pd.Timestamp("2025-12-01")
train_df = train[train["prediction_ts"] < cutoff]
valid_df = train[train["prediction_ts"] >= cutoff]
assert train_df["prediction_ts"].max() < valid_df["prediction_ts"].min()Pick the cutoff so that the validation set covers a period like the one the model will face. If the label takes 30 days to observe, rows just before the cutoff have labels that were not known at the cutoff. Leave a gap of that length between the last training row and the first validation row, so you do not train on outcomes that were still unknown when validation began.
The same logic in SQL
If the history lives in a warehouse, run the join there. The ROW_NUMBER pattern selects the newest feature row at or before each prediction, and the extra join condition applies the tolerance. The interval syntax below is Postgres style, so adjust it for your engine.
WITH candidates AS (
SELECT
l.customer_id,
l.prediction_ts,
l.churned,
f.avg_spend_30d,
f.event_ts AS feature_ts,
ROW_NUMBER() OVER (
PARTITION BY l.customer_id, l.prediction_ts
ORDER BY f.event_ts DESC
) AS rn
FROM labels AS l
LEFT JOIN feature_history AS f
ON f.customer_id = l.customer_id
AND f.event_ts <= l.prediction_ts
AND f.event_ts >= l.prediction_ts - INTERVAL '30 days'
)
SELECT customer_id, prediction_ts, churned, avg_spend_30d, feature_ts
FROM candidates
WHERE rn = 1;Use a LEFT JOIN so labels with no qualifying feature stay in the result with NULL values, as the merge_asof version does. An inner join would drop them without any message, which is how coverage problems go unnoticed.
If events can share the same event_ts, add a tie-breaker to the ORDER BY, such as an ingestion timestamp. Without one, the chosen row can change between runs.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `merge_asof` raises a sorted-keys error | Input not sorted by the time key | Sort both tables on their time column before the join |
| Row count grows after the join | Used `merge` or a SQL join without `ROW_NUMBER` | Use an as-of join and assert one row per label key |
| Validation score is far higher than production | Random split, or `direction` not `"backward"` | Split on `prediction_ts`; fix the direction |
| Many NaN features | Tolerance too short, or the feature table starts late | Review coverage by month before changing anything |
| Results differ between runs | Ties on `event_ts` in SQL | Add a deterministic tie-breaker |
| Dtype error on the key columns | Timestamps differ in type or time zone | Convert both to UTC datetime64 before the join |
Exercise
In the example data, add a feature row for customer 2 with feature_ts of 2025-11-10 and avg_spend_30d of 65.0. Which value does the label row for customer 2 at 2025-11-15 receive, and why does the 70.0 row from 2025-09-01 no longer matter? Then, what happens to the result if you change the tolerance to "90D" without adding the new row?
Show answer
With the new row, the label receives 65.0. It is the latest row at or before 2025-11-15 (5 days old), and the as-of join takes only the single latest row, so older rows are never considered. Without the new row and with a 90-day tolerance, the 2025-09-01 row is 75 days old and falls inside the tolerance, so customer 2 receives 70.0 instead of NaN. Coverage rises, but the value is stale, so the tolerance should match how fresh the feature is at serving time.