Sub topic 10
Building a training set with get_historical_features
This chapter assumes you have a Feast repository with the driver entity, the driver_hourly_stats feature view and the driver_activity_v1 feature service from earlier chapters. You should have run feast apply. You should also be comfortable with pandas DataFrames and with the idea of labeled training rows.
What the call does
FeatureStore.get_historical_features builds a training set. You give it a table of rows you want to learn from, called the entity dataframe, and a list of features. Feast reads the offline store and attaches to each row the feature values that were known at that row's timestamp. It does not use the latest values.
The call returns a RetrievalJob. The job is lazy, so the join runs when you call .to_df() or .to_arrow(). With some offline stores, such as BigQuery, Snowflake or Redshift, the join runs inside the warehouse, so large training sets do not have to pass through your Python process.
The entity dataframe
The entity dataframe is the left side of the join. It needs two kinds of columns:
- Join keys. One column per entity join key. For the
driverentity this isdriver_id. event_timestamp. The moment each row's prediction would have been made, or the moment its label was observed. Feast uses this column for the point-in-time logic.
Any other columns, such as labels, pass through unchanged. This is the usual way to keep labels attached to their features.
from datetime import datetime, timezone
import pandas as pd
from feast import FeatureStore
store = FeatureStore(repo_path=".")
entity_df = pd.DataFrame(
{
"driver_id": [1001, 1002, 1001],
"event_timestamp": [
datetime(2025, 1, 1, 12, 0, tzinfo=timezone.utc),
datetime(2025, 1, 1, 13, 0, tzinfo=timezone.utc),
datetime(2025, 1, 2, 9, 30, tzinfo=timezone.utc),
],
"trip_completed": [1, 0, 1],
}
)
training_df = store.get_historical_features(
entity_df=entity_df,
features=[
"driver_hourly_stats:conv_rate",
"driver_hourly_stats:acc_rate",
"driver_hourly_stats:avg_daily_trips",
],
).to_df()
print(training_df.head())
print(training_df.dtypes)Driver 1001 appears twice with different timestamps. Each row gets its own feature values, because each row is joined separately. The output has the original columns plus conv_rate, acc_rate and avg_daily_trips.
Use timezone-aware UTC timestamps. Mixing naive and aware timestamps, or local time zones, is a common source of silently shifted joins.
How the join picks a value
For each entity row, Feast looks at the feature view's source rows for the same join key. It keeps only source rows where source.event_timestamp <= entity_row.event_timestamp. If the feature view has a TTL, it also requires source.event_timestamp >= entity_row.event_timestamp - ttl. Among the remaining candidates it takes the one with the latest event_timestamp. If two candidates share that timestamp, it uses the larger created value. That is what created_timestamp_column is for.
Suppose driver 1001 has these source rows, with a feature view TTL of one day:
| Source event_timestamp | conv_rate |
|---|---|
| 2025-01-01 08:00 | 0.41 |
| 2025-01-01 11:00 | 0.47 |
| 2025-01-01 14:00 | 0.52 |
| 2025-01-03 10:00 | 0.60 |
The result for each entity row is:
| Entity event_timestamp | Value returned | Reason |
|---|---|---|
| 2025-01-01 12:00 | 0.47 | Latest value at or before noon. The 14:00 row is in the future, so it is excluded. |
| 2025-01-02 09:30 | 0.52 | The 14:00 row on Jan 1 is 19.5 hours old, inside the TTL. |
| 2025-01-02 15:00 | null | The newest earlier value is older than one day, so the TTL excludes it. |
This rule is what prevents label leakage. If the join used the newest value regardless of time, a row from January 1 could be trained on a value computed on January 3. The model would then see information that does not exist at serving time.
Choosing features
The features argument accepts three forms.
- A list of
"view_name:feature_name"strings, as above. - A list of feature references pulled from a feature view object.
- A
FeatureService, which gives you a named, versioned selection.
Using the feature service from earlier chapters:
service = store.get_feature_service("driver_activity_v1")
training_df = store.get_historical_features(
entity_df=entity_df,
features=service,
).to_df()This returns only conv_rate and acc_rate. Training from a feature service means the training set and the serving call can reference the same name, which reduces the chance that the two drift apart.
If two feature views have a feature with the same name, pass full_feature_names=True. Columns are then named driver_hourly_stats__conv_rate, with a double underscore between view and feature. Many teams turn this on by default so column names never change when a second view is added.
Joining several feature views
When your features come from different views, Feast performs a separate point-in-time join per view. Each view may use a different TTL and a different source. The views may also be keyed on different entities. In that case the entity dataframe must contain a join key column for every entity involved. For example, a view keyed on customer_id and one keyed on driver_id both need their key columns present in the entity dataframe.
Edge cases
- Missing values are normal. A row with no qualifying source record gets null (NaN in pandas). This happens when the entity has no history before that timestamp, or when the TTL has expired. Decide on imputation deliberately and apply the same rule at serving time.
- Row order is not a contract. Do not assume the output order matches the input. Match rows on the join key and
event_timestamp, or carry an explicit row id column in the entity dataframe. - A
NoneTTL, or a TTL of zero, changes the window. With no TTL limit, any earlier value qualifies however old it is. That can be right for slowly changing attributes, but it hides staleness. Check how your Feast version treats a zero TTL before relying on it. - Timestamp column name. The entity dataframe column must be called
event_timestamp. The source's own timestamp column can have any name, set withtimestamp_field. - Duplicate entity rows. Identical key and timestamp pairs are allowed, but they return identical values. Deduplicate first if you do not want repeated training examples.
- Some offline stores accept a SQL string. Warehouse-based offline stores let
entity_dfbe a query, so the entity table never leaves the warehouse. The file offline store used in this tutorial needs a DataFrame.
Common errors
| Symptom | Likely cause |
|---|---|
| All feature columns are null | Entity timestamps are earlier than any source data, or the TTL is shorter than the gap between updates. |
| Error about a missing join key | The entity dataframe lacks the column named in the entity's `join_keys`. |
| Error about the timestamp column | The `event_timestamp` column is missing or is not a datetime type. |
| Feature not found | The reference is misspelled, or `feast apply` was not run after you changed the definition. |
| Offline model scores far better than online | The entity timestamps were set to the current time, or to a time after the label was known. Use the time the prediction would have been made. |
Exercise
A feature view has a TTL of 6 hours. Driver 2001 has source rows at 2025-03-01 06:00 (accrate 0.80) and 2025-03-01 10:00 (accrate 0.85). What does gethistoricalfeatures return for accrate on entity rows with eventtimestamp 09:00, 11:00 and 17:00 on that day?
Show answer
At 09:00 it returns 0.80, because the 06:00 row is the latest at or before 09:00 and is 3 hours old, inside the TTL. The 10:00 row is in the future, so it is excluded. At 11:00 it returns 0.85, because the 10:00 row is 1 hour old. At 17:00 it returns null, because the newest earlier row (10:00) is 7 hours old, which exceeds the 6 hour TTL.