internalsGet Pro

Module 01 · Lesson 9 of 10Free

Data, features and labels

Level
Beginner
Topic
Machine learning fundamentals
Reading time
14 min

When you finish this page you can

  1. Turn an event table, such as orders, into a training table with one row per prediction.
  2. Compute features using only what was known at the snapshot date.
  3. Define a label precisely and weigh how its window changes speed and correctness.
  4. Spot columns that hold today’s values and would leak the answer into old rows.

Builds on 2 lessons

Start with lesson 314 min
  1. Supervised, unsupervised and reinforcement learning14 min
  2. Framing a business problem as an ML problem14 min
0:00 / 4:57
Show transcript

0:00 Meet Farah, an ML engineer at Kartly, our example online store. Joseph leads the growth team. Every Monday he sends a voucher to customers who might stop buying. That is churn. Farah has a big table of orders to work from, and she has a model, the program that makes the predictions. Joseph asks a fair question. Why not just give the orders table to the model? Here is the puzzle. The orders table has one million rows. Farah builds a training table from it, for a past date. About how many rows does it end up with? The answer is about two hundred thousand. That is a row per customer, not a row per order. This lesson shows why, and what decides whether that table tells the truth.

0:37 A training table is made of examples. Each example holds features and a label. Features are the values the model reads. The label is the answer it learns to predict. The orders table has neither. Its rows are events, one order on one day. But the model’s question is about a customer at a moment. So each example is one customer on one past date. We call that date the snapshot date. Farah picks the first of March. Take two made-up customers. Asha ordered fourteen days before the snapshot. She also ordered again soon after it, so her label is no: she stayed. Ravi’s last order was a hundred and twenty days back, and he ordered nothing after. His label is yes: he left. Orders before the snapshot become the feature columns. Orders after it decide only the label. On Monday, Farah runs the same code with the snapshot date set to today. She gets the same columns, but no label. The model fills in the label for those rows. So a row is a prediction you could have made: one customer, on one date. It is the same question Kartly asks every Monday. So what should one row be? One row per order? Then a customer with forty orders counts forty times, and the model mostly learns about loyal customers. One row per customer, built from all their orders? That is easy to build, but the features use the orders that decide the label, so the model reads the answer. One row per customer per snapshot date matches Monday exactly. The row copies the moment the prediction is used.

1:54 Now the rule as a timeline. Features look back from the snapshot date. The label looks forward, sixty days ahead. Orders before the snapshot may feed features. Orders after it may only decide the label. And the newest rows cannot be labelled yet, because their window is still open. The harder half is other tables that hold only today’s values. Kartly’s customers table has an account status column. When a customer closes their account in April, that row changes to closed. Farah joins the table onto her March rows. Now everyone who closed in April carries closed, and all of them are labelled left. On old data, the model’s score jumps. On the first real Monday, it barely beats the rule. Why? On the snapshot date, that column read active for almost everyone. The model learned from a fact that did not exist yet. That is data leakage: the answer leaks into the features. The fix is to read each value as it was on the snapshot date. That needs history, like an event log, or dated copies of the table.

2:49 Nothing in Kartly’s data says left. Customers do not announce it. So Farah defines it from what she can observe: no order in the sixty days after the snapshot. That is a proxy label. Joseph cares about lost profit. Profit is hard to measure for each customer. So she predicts something close to it that the order history records exactly. Take a regular customer who orders every forty-five days. Give the label a thirty-day window. She places no order in it, so the label says left. That is wrong. She is loyal. Now give it the longer window Farah chose. The customer’s next order lands inside it. The label says stayed. That is right. The window length is the choice that matters. A longer window makes labels more correct, but slower to arrive. That wait is label delay. It sets how fast Farah can retrain and check her model. So she checks the choice in the data: how long customers usually go between orders. Even then, some labels stay wrong. A customer who is gone for good but buys once in a festival sale counts as stayed. A few wrong labels are normal. Many of them limit how good any model can be.

3:50 Three traps show up in Farah’s table. A feature that knows the future, like account status. A value that is missing, like a city left blank by customers who never saved an address. And a feature computed two ways. The Monday job counts cancelled orders, and the training code does not. That gap is called training-serving skew. Missing values and skew each get their own lesson later. But one habit prevents the skew now. Build the training rows and the Monday rows with one function, changing only the snapshot date. Then training and Monday see the same features.

4:22 Here is the recap. One: a row is one customer on one snapshot date, the same question Kartly asks every Monday. Two: features use only what was known on that date, so tables of today’s values must be read as they were. Three: the label is a definition, and its window trades correct labels against slow ones. Four: the newest rows cannot be labelled yet. Five: one function builds both training rows and Monday rows. Churn labels take sixty days. In the next lesson, the label arrives the moment a ride ends, and the features must be ready the moment it is booked. That is Design: predicting trip times for a ride app.

A million orders and not one example

is our example online store. Farah, an ML engineer, works on a sample of its data that fits in a free notebook: about 1 million orders from 200,000 customers, across 50,000 products. The prediction in this lesson is : will a customer place no order in the next 60 days?

Joseph, who leads the growth team, uses that prediction every Monday. Kartly scores all 200,000 customers and sends a ₹100 voucher to the top 20,000. He asks Farah why she can’t “just give the orders table to the model”.

The orders table looks like this: one row per order, with a customer id, a date and an amount. A churn model needs something else.

Check yourselfAnswer in your head first, then reveal
The orders table has 1 million rows. Farah builds a churn training table from it for one past date. About how many rows does that table have?Show answerHide answer
About 200,000, one per customer, not 1 million. A row is one prediction Farah could have made: this customer, on this date, will they leave? Each customer’s orders get squeezed into a few numbers on that one row.

So the question this lesson answers is: how does Farah turn raw orders into a table a model can learn from, and what decides whether that table tells the truth?

One row is one prediction you could have made

A dataset for supervised learning is made of examples. Each example holds features and a label.1 The are the values the model reads. The is the answer it learns to predict.1

The orders table has neither. Its rows are events. The model’s question is about a customer at a moment, so each example is one customer on one past date, called the snapshot date. Farah picks 1 March.

Orders before the snapshot become feature columns. Orders in the 60 days after it decide only the label.

Every row in the training table has the same columns. Two kinds of features appear:

Feature Kind Computed from
Days since last order Number Latest order before 1 March
Orders in the last 90 days Number Orders from 1 December to 28 February
Average basket Number Mean amount of orders before 1 March
City Category The customer’s city on 1 March

A model reads numbers. A category such as a city has to be turned into numbers first, which Encoding categories as numbers covers.

On Monday, Farah runs the same code with the snapshot date set to today. She gets the same columns, with no label. The trained model then predicts the label for those rows.1

What should one row of the churn training table be?

One row per order, with the customer’s label copied onto each.

A customer with 40 orders counts 40 times and a customer with 1 order counts once. And “will this order’s customer leave” is asked on 40 different dates for the same person.

One row per customer, built from all their orders.

Easy to build, but there is no fixed moment. Features use the whole history, including the orders that decide the label, so the model reads the answer.

Why this choice

The row should copy the moment the prediction is used. On Monday, Kartly asks one question per customer, knowing only the past. A training row built the same way teaches the model that exact task.

The choice changes when the prediction changes. A fraud check scores each payment, so its row is one payment. Next lesson’s trip-time model scores each ride request, so its row is one request.

Picking the row was the easy part. The line between features and label is where most mistakes happen.

Features stop at the snapshot date

Supervised, unsupervised and reinforcement learning drew the rule as a timeline. Features look back from the snapshot date. The label looks forward.

Features look back from the snapshot date. The label looks 60 days ahead, so the newest labelled example is always 60 days old.

Filtering orders by date is the easy half. The harder half is other tables that hold only today’s values.

Kartly’s customers table has a column account_status. When a customer closes their account in April, the row changes to closed. Farah joins that table onto her 1 March rows. Every customer who closed an account in April now carries closed, and every one of them is labelled “left”.

Check yourselfAnswer in your head first, then reveal
With account_status joined in, the model’s held-out score jumps far above the 60-day rule. On the first real Monday it barely beats the rule. Why?Show answerHide answer
On 1 March the column read “active” for almost everyone. The join wrote April’s value onto March rows, so the model learned from a fact that didn’t exist yet. On Monday, nobody about to close their account has “closed” written yet.

Google’s rules warn about exactly this: a table you join may change between when you build training data and when you serve, so the same row can get different values.2 The fix is to read each value as it was on the snapshot date. That needs history: an event log or dated copies of the table. This is by the time travel route. Time-based features without looking ahead shows how to build features safely.

The features are now honest. The label still needs one more decision.

The label is a definition you choose

Nothing in Kartly’s data says “left”. Customers don’t announce it. Farah has to define it from what she can observe: no order in the 60 days after the snapshot.

That is a proxy label. Joseph cares about lost profit. Lost profit is hard to measure per customer, so Farah predicts something close to it that the order history records exactly. Google’s rules recommend this for a first model: a simple, observable objective that stands in for the true one.2

The window length is the choice that matters. Take a made-up regular customer who orders every 45 days.

A 30-day window calls a customer who orders every 45 days a leaver. A 60-day window sees their next order.

How long should the churn label window be?

30 days.

Labels arrive after 30 days, so the model learns from fresher data. But regulars who order every 45 days get labelled “left”, so the model learns to flag loyal customers.

120 days.

Fewer wrong “left” labels. But the newest labelled row is four months old, and a customer gone for 90 days still counts as stayed if they buy once at day 110.

Why this choice

A longer window makes the label more correct and slower to arrive. That wait is , and it sets how fast Farah can retrain and check her model.

Farah checks the choice in the data, not by feel. She measures the usual gap between orders. If most customers reorder within 60 days, a 60-day silence is a real signal. If Kartly started selling furniture, bought once a year, 60 days would label nearly every buyer “left”, and the window would have to grow.

Labels can also be wrong after the window closes. A customer who is gone for good but buys once in the festival sale counts as “stayed”. Some wrong labels are normal. Many of them limit how good any model can be.

The table fits in a notebook

Farah estimates the sizes before writing any code. Each number is 8 bytes.

Orders table

1,000,000 rows × 15 columns × 8 bytes ≈ 120 MB

Large for a spreadsheet, small for a notebook.

Training table, one snapshot

200,000 rows × 10 features × 8 bytes = 16 MB

One row per customer is far smaller than one per order.

Estimates for the notebook sample. Free notebooks don’t publish a memory figure, so keep tables well under it.

Try it yourself

This runs in a free Colab or Kaggle notebook in under a minute. It makes up 1 million Kartly orders, then builds the training table for 1 March. The orders are random, so the table has the right shape but no real pattern to learn.

Python
import numpy as np
import pandas as pd

rng = np.random.default_rng(42)
n_orders, n_customers = 1_000_000, 200_000  # Kartly's notebook sample (made-up)

first_day = pd.Timestamp("2025-09-01")
days = rng.integers(0, 241, size=n_orders)  # 1 Sep 2025 to 29 Apr 2026
orders = pd.DataFrame({
    "customer_id": rng.integers(0, n_customers, size=n_orders),
    "order_date": first_day + pd.to_timedelta(days, unit="D"),
    "amount": rng.gamma(shape=2.0, scale=400.0, size=n_orders).round(),
})

snapshot = pd.Timestamp("2026-03-01")
window_end = snapshot + pd.Timedelta(days=60)

# Features: only orders before the snapshot.
past = orders[orders["order_date"] < snapshot]
past = past.assign(recent=past["order_date"] >= snapshot - pd.Timedelta(days=90))
table = past.groupby("customer_id").agg(
    last_order=("order_date", "max"),
    orders_90d=("recent", "sum"),
    avg_basket=("amount", "mean"),
)
table["days_since_last_order"] = (snapshot - table["last_order"]).dt.days
table = table.drop(columns="last_order")

# Label: 1 if the customer placed no order in the 60 days after the snapshot.
future = orders[(orders["order_date"] >= snapshot) & (orders["order_date"] < window_end)]
table["left_60d"] = (~table.index.isin(future["customer_id"])).astype(int)

print(len(orders), "orders ->", len(table), "rows")
print(table.head())
print(round(table.memory_usage(deep=True).sum() / 1e6, 1), "MB")

What to look for:

  • agg with name=(column, function) names each output column, and the group keys become the index.3 So each customer id appears once.
  • Expect about 195,000 rows, not 200,000. About 2% of made-up customers have no order before 1 March, so they have no row. This is worked out from how the data was made, not a measured result.
  • Change snapshot to "2026-04-01". The window now runs past the last day of data, so missing April and May orders make far too many rows look like leavers. That is why recent rows can’t be labelled yet.

Where the table goes wrong

Each of these has its own lesson in Module 11. Here is what each looks like in Farah’s table.

Problem In the churn table Covered in
A feature knows the future account_status joined with today’s value Data leakage
A value is missing City is blank for customers who never saved an address Missing values
Training and Monday compute a feature differently The Monday job counts cancelled orders; training code doesn’t Feature stores

The last row is the from The ML lifecycle. Building training rows and Monday rows with one function, changing only the snapshot date, removes that gap. Google’s rules give the same advice: reuse code between training and serving.2

More than one snapshot date

One snapshot gives about 200,000 rows, all from one season. Farah can stack several: 1 November, 1 December, 1 January, and so on. Each date adds about 200,000 rows and shows the model more than one season.

Two things change. The same customer now appears on several rows, which are not independent. And the test rows must come from later dates than the training rows, not a random share. Google’s rules say to train on data up to one date and test on data after it.2 Train, validation and test sets covers how to split.

Where this shows up

Churn labels take 60 days. The next lesson, Design: predicting trip times like Uber, has a label that arrives the moment a ride ends, and features that must be ready the moment it is booked.

Common mistakes

  • One row per event. The row is the prediction, not the raw record.
  • Joining today’s table onto old rows. Any column that is overwritten needs its value as of the snapshot date.
  • Treating the label as a given. It is a definition. Check its window against how often customers really buy.
  • Labelling rows whose window hasn’t closed. A customer from last week looks like a leaver only because their window is still open.
  • Two copies of the feature code. Training rows and Monday rows should come from one function.

Check your understanding

Check yourselfAnswer in your head first, then reveal
Farah builds one row per order and copies the customer’s label onto each. Which customers does the model learn most from?Show answerHide answer
Customers with many orders, who are mostly the loyal ones. A customer with 40 orders counts 40 times, so the model learns little about one-order customers, who are the ones most likely to leave.
Check yourselfAnswer in your head first, then reveal
Joseph asks for a 14-day label window so the model can retrain every two weeks. What goes wrong?Show answerHide answer
Most regular customers go more than 14 days between orders, so many loyal customers get labelled “left”. The labels arrive faster but are mostly wrong, and the model learns to flag regulars.
Check yourselfAnswer in your head first, then reveal
A feature reads loyalty_tier from the customers table, which is recomputed every night. Is it safe for 1 March rows?Show answerHide answer
Not as it is. The nightly job overwrites the tier, so a 1 March row gets today’s tier, which may reflect orders after 1 March. Farah needs the tier as it was on 1 March, from a dated copy or a history table.
Check yourselfAnswer in your head first, then reveal
Farah’s Try it yourself table has about 195,000 rows, not 200,000. Should she add the missing customers with zeros?Show answerHide answer
No. Those customers had no order before 1 March, so on that date Kartly had nothing to predict from. A churn model for existing customers shouldn’t learn from them; brand-new customers need their own approach.

Summary

  1. Farah turns raw orders into a training table with one row per customer per snapshot date: the same question Kartly asks every Monday.
  2. Features use only what was known at the snapshot date. A table that holds today’s values must be read as it was then, or the answer leaks in.
  3. The label is a definition, often a proxy: no order in the 60 days after the snapshot. Its window trades correct labels against how fast they arrive.
  4. Rows whose label window hasn’t closed can’t be labelled, so the newest training row is always 60 days old.
  5. One function builds both training rows and Monday rows, changing only the snapshot date, so training and serving see the same features.

Report a mistake

Tell us what’s wrong in this lesson and we’ll fix it.