Sub topic 3
Defining entities, labels, and the prediction timestamp
This chapter assumes you know basic supervised learning, SQL joins, pandas DataFrames, and the three clocks from the previous chapter (event time, ingestion time, prediction time). Here you design the table that every later step hangs on: the label table. The as-of join in the next chapter can only be as correct as this table is.
Why the label table comes first
A point-in-time correct training set starts from the question "what did we know, about whom, and at what moment?" The label table answers it. It has one row per training example, and each row carries three things:
- An entity key, which says who or what the example is about.
- A prediction timestamp, which says when the prediction would have been made.
- A label, which says what actually happened afterward.
Every feature lookup later uses the entity key to find rows and the prediction timestamp to decide which rows are allowed. If the timestamp is wrong or missing, no join logic can repair it.
Entities
An entity is the thing a model makes predictions about, such as a customer, a device, a loan application, or a driver. Features are stored per entity, and the entity key is what you join on.
Choose the entity by asking what the model will be handed at serving time. A churn model that scores customers has customer_id as its entity. A fraud model that scores payments has payment_id, but it probably also uses features of the card and the merchant. Those are separate entities with their own feature histories, and the label table needs a key column for each one you join.
Common mistakes with entities:
- Keys that change meaning over time. If
customer_idis reused after account deletion, or two accounts merge, history for one key can belong to different people. Use stable surrogate keys and keep a mapping table for merges. - Joining on a key that only exists after the event. A
policy_idassigned after an application is approved cannot be used to look up features for the application stage. - Mixed grains. If some rows are per customer and others per account, a join on
customer_idmultiplies rows.
The prediction timestamp
The prediction timestamp (prediction_ts) is the moment the model would have produced its score if it had been running. It is the cutoff for information: a feature value may be used only if it was known at or before this moment.
It is not the same as the label's timestamp, and it is not simply "the row's date". The way you choose it depends on how the model is used.
| Usage pattern | What `prediction_ts` is | Example |
|---|---|---|
| Event-triggered | The time of the triggering event | Score each card payment when it is authorized |
| Scheduled batch | The scheduled run time | Score all customers at 06:00 every Monday |
| Snapshot sampling | A grid of dates you choose for training | The first day of each month for every active customer |
For event-triggered models, prediction_ts comes from the data itself. For batch models, it must match the real schedule, including the lag. If the production job runs at 06:00 on data that finishes loading at 05:30, the training rows should use 06:00, not midnight, and the features available are those that had landed by then.
For snapshot sampling, you create the timestamps. Taking one row per entity per month is common because it avoids over-weighting entities that generate many events. The snapshot interval is a modeling choice: closer snapshots give more rows, but neighboring rows from the same entity are highly correlated, which matters when you split the data.
The label window
Most labels are defined over a period after the prediction time. For example, "churned" can mean "placed no order in the 30 days after prediction_ts". That gives each example two windows:
- The observation side, which is everything at or before
prediction_ts. Features come only from here. - The label window, the interval after
prediction_tsover which the outcome is measured. Only the label may use it.
Write the horizon down as a number and keep it in one place in your code. The same value defines the label, the maturity cutoff, and often the gap you leave when splitting by time.
Label maturity and censoring
A label is mature when its whole window has elapsed and its data has arrived. A row with prediction_ts on March 1 and a 30-day window is not mature until March 31. If you build the training set on March 25, that row has an incomplete window. Treating "no order seen yet" as "churned" would label many active customers as churned, and the model would learn from wrong labels. Rows that cannot yet be labeled are censored, and you must drop them (or handle them with a method designed for censored data, such as survival analysis).
Also consider arrival delay. If orders reach your warehouse two days late, a window that closed yesterday is not fully visible yet. Set the maturity cutoff to the window end plus the typical delay, and apply the same rule every time you rebuild.
Building the label table in pandas
The following script builds a churn label table from raw orders. It creates a monthly grid of prediction timestamps, keeps only customers who had signed up by each timestamp, derives the label from the window after the timestamp, and drops immature rows.
import pandas as pd
HORIZON = pd.Timedelta("30D")
DATA_END = pd.Timestamp("2026-03-25") # latest data we trust
customers = pd.DataFrame({
"customer_id": ["a", "b", "c"],
"signup_ts": pd.to_datetime(["2025-12-01", "2025-12-15", "2026-01-20"]),
})
orders = pd.DataFrame({
"customer_id": ["a", "a", "a", "b", "b", "c"],
"order_ts": pd.to_datetime([
"2026-01-05", "2026-02-10", "2026-03-20",
"2026-01-12", "2026-01-28", "2026-02-02",
]),
})
# 1. Grid of prediction timestamps (first day of each month).
grid = pd.DataFrame({"prediction_ts": pd.date_range("2026-01-01", "2026-03-01", freq="MS")})
# 2. One candidate row per customer per timestamp, only if the customer existed then.
rows = customers.merge(grid, how="cross")
rows = rows[rows["signup_ts"] <= rows["prediction_ts"]]
# 3. Label: any order in (prediction_ts, prediction_ts + HORIZON]?
cand = rows.merge(orders, on="customer_id", how="left")
cand["in_window"] = (
(cand["order_ts"] > cand["prediction_ts"])
& (cand["order_ts"] <= cand["prediction_ts"] + HORIZON)
)
labels = cand.groupby(["customer_id", "prediction_ts"], as_index=False)["in_window"].any()
labels["churned"] = (~labels["in_window"]).astype(int)
# 4. Drop immature rows: the label window must end before DATA_END.
labels["label_end_ts"] = labels["prediction_ts"] + HORIZON
labels = labels[labels["label_end_ts"] <= DATA_END].drop(columns="in_window")
# 5. Guard the grain: exactly one row per (customer, prediction time).
assert not labels.duplicated(["customer_id", "prediction_ts"]).any()
print(labels.to_string(index=False))This produces five rows. The March 1 rows are dropped because their windows end on March 31, after DATA_END. Only customer b at 2026-02-01 has churned = 1, because neither of b's orders falls in the 30 days after that date. Customer c has no row for January 1 because c had not signed up yet.
The window is open on the left and closed on the right: an order exactly at prediction_ts belongs to the observation side, not the label window. Pick one convention and use it everywhere. A mismatch of one boundary is a small but real source of leakage, because an event at the exact prediction instant would be both a feature and the label.
Keep label_end_ts in the table. It costs one column, and later it lets you split by time without letting label windows straddle the boundary.
Label leakage through the definition itself
Leakage can come from how the label is defined, not only from feature joins. Watch for these:
- Features derived from the label's source. If the label is "refund issued within 14 days" and a feature is "support tickets in the last 30 days", check that tickets opened after
prediction_tsare not counted. - Status columns that are overwritten. A column such as
account_statusthat holds only the current value will say "closed" for customers who closed after the prediction time. This is why the next chapters store history rather than the latest value. - Eligibility filters that use the future. Selecting "customers who were active for at least 90 days" using today's data removes customers who churned early, and the sample no longer represents the population you would score in production. Define eligibility with information available at
prediction_ts, as thesignup_ts <= prediction_tsfilter above does.
Checks to run on the label table
Run these on every build, before any feature joins:
- The grain is unique: one row per entity key and
prediction_ts. - No
prediction_tsis later than the data cutoff, and everylabel_end_tsis at or before it. - The label distribution per month looks plausible. A sharp drop in positive rate in the most recent months usually means immature labels were not dropped.
- Every entity was eligible at its
prediction_ts, for examplesignup_ts <= prediction_ts.
What comes next
With a clean label table, each row states who, when, and what happened afterward. The next chapters build the feature side: how to store history, and how to join it so each row sees only what was known at its prediction_ts.
Exercise
A team builds a 7-day "will the user cancel" label on the morning of 2026-06-10. Their prediction timestamps include every day from 2026-06-01 to 2026-06-09, and they label a user "retained" if no cancellation appears in the 7 days after each timestamp. Which rows should be dropped, and what happens to the model if they are not?
Show answer
A row is mature only if predictionts + 7 days is at or before the data cutoff (2026-06-10, plus any arrival delay). So rows with predictionts after 2026-06-03 are immature and must be dropped. If kept, users who cancel later in the window are labeled "retained", so the most recent rows have too few positives and wrong labels. The model learns from mislabeled examples, and the recent positive rate looks falsely low.
Exercise
A batch model runs every day at 06:00, but the warehouse finishes loading the previous day's data at 05:30. A colleague sets predictionts to midnight for every training row. Why is that a problem, and what should predictionts be?
Show answer
Midnight does not match production. At serving time the model sees data that arrived by 06:00, including events between midnight and 05:30, so training would exclude information the live model has (or, with sloppy joins, mix in data in ways production does not). The prediction timestamp should be the actual run time, 06:00, and features should be limited to what had landed by then, so that training matches serving.