Sub topic 7
Assembling the Training Set End to End
This chapter assumes basic supervised machine learning, SQL joins and window functions, pandas DataFrames, and timestamps with time zones. The goal is to turn label rows and historical features into one training table without using information that was unavailable when each prediction would have been made.
Start with a dataset contract
A training row represents one prediction for one entity at one moment. Define that meaning before writing the join.
For a churn model, the entity might be a customer. The prediction timestamp is when the system would score that customer. The label is the outcome observed after a fixed period, such as whether the customer churned within 30 days.
Every feature row needs at least:
- An entity key, such as
customer_id - An event timestamp, describing when the measurement was true
- The feature value
- An ingestion timestamp, describing when the value became available to the data system
The label table needs one row for each prediction event.
| Table | Important columns | Meaning |
|---|---|---|
| `labels` | `customer_id`, `prediction_ts`, `churned` | One supervised learning example |
| `feature_history` | `customer_id`, `event_ts`, `ingested_ts`, `avg_spend_30d` | Values recorded over time |
Build the point-in-time join
For each label row, choose the newest feature row for the same customer whose event time is at or before the prediction time. A tolerance prevents an old feature from being treated as current.
The following example creates a small, complete training table:
import pandas as pd
labels = pd.DataFrame(
{
"customer_id": ["c1", "c1", "c2"],
"prediction_ts": [
"2026-01-10T00:00:00Z",
"2026-01-20T00:00:00Z",
"2026-01-15T00:00:00Z",
],
"churned": [1, 0, 1],
}
)
features = pd.DataFrame(
{
"customer_id": ["c1", "c1", "c2", "c2"],
"event_ts": [
"2026-01-01T00:00:00Z",
"2026-01-12T00:00:00Z",
"2026-01-01T00:00:00Z",
"2026-01-14T00:00:00Z",
],
"ingested_ts": [
"2026-01-01T01:00:00Z",
"2026-01-12T01:00:00Z",
"2026-01-01T01:00:00Z",
"2026-01-14T02:00:00Z",
],
"avg_spend_30d": [40.0, 55.0, 20.0, 25.0],
}
)
labels["prediction_ts"] = pd.to_datetime(labels["prediction_ts"], utc=True)
features["event_ts"] = pd.to_datetime(features["event_ts"], utc=True)
features["ingested_ts"] = pd.to_datetime(features["ingested_ts"], utc=True)
labels = labels.sort_values("prediction_ts")
features = features.sort_values("event_ts")
train = pd.merge_asof(
labels,
features,
left_on="prediction_ts",
right_on="event_ts",
by="customer_id",
direction="backward",
tolerance=pd.Timedelta("30D"),
)
# Do not use a value that arrived after the prediction moment.
available = train["ingested_ts"].isna() | (
train["ingested_ts"] <= train["prediction_ts"]
)
train.loc[~available, "avg_spend_30d"] = pd.NA
print(train)direction="backward" prevents a future event from matching a label. The tolerance leaves the feature missing when the newest eligible value is more than 30 days old. A missing value is safer than silently using stale information.
For a feature whose newest event was ingested late, masking after the join can discard an older eligible event. A production bitemporal query should filter ingested_ts <= prediction_ts before selecting the newest eligible event. In SQL, this usually means placing both timestamp conditions in the join and using ROW_NUMBER() ordered by event time descending.
Validate the assembled table
Validation checks should run immediately after the join and before model training.
joined = train.dropna(subset=["event_ts"])
assert (joined["event_ts"] <= joined["prediction_ts"]).all()
assert (
joined["ingested_ts"].isna()
| (joined["ingested_ts"] <= joined["prediction_ts"])
).all()
assert not train.duplicated(["customer_id", "prediction_ts"]).any()The first assertion catches event-time leakage. The second catches data that had not arrived yet. The third catches a many-to-many join that duplicated labels.
Create a realistic validation split
Random splitting lets nearly identical time periods appear in both training and validation. Instead, choose a cutoff date. Train on earlier predictions and validate on later predictions.
cutoff = pd.Timestamp("2026-01-15", tz="UTC")
train_df = train[train["prediction_ts"] < cutoff]
valid_df = train[train["prediction_ts"] >= cutoff]This split approximates production, where the model learns from the past and predicts the future.
Exercise
A feature event occurred on January 8, but the event was ingested on January 12. Can it be used for a prediction made on January 10?
Show answer
No. The event existed in the outside world, but the model-serving system could not have known it on January 10. Filter it using ingestion time.