Sub topic 1
What feature engineering is and why it matters
Prerequisites
This chapter assumes you already have the following:
- Basic Python and PySpark DataFrame operations (select, filter, groupBy, agg).
- Familiarity with Delta tables and Databricks notebooks.
- The basic machine learning workflow: training, evaluation, and inference.
- Awareness of Unity Catalog's
catalog.schema.tablenaming, such asmain.ml.user_features.
No Databricks feature APIs are used yet. This chapter builds the working model that the later chapters fill in.
What a feature is
A feature is a numeric or categorical input value that a model uses to make a prediction. Raw data rarely arrives in that form. An orders table holds one row per purchase, but a churn model needs one row per user with values such as "orders in the last 90 days" or "average order amount."
Feature engineering is the work of turning raw data into those model-ready values. It usually includes four kinds of steps:
- Aggregation. Summarize many rows into one, for example counts, sums, averages, and most-recent timestamps per user.
- Encoding. Convert categories such as
countryorplan_typeinto numbers a model can consume. - Scaling. Put numeric columns on comparable ranges when the algorithm is sensitive to magnitude.
- Missing-value handling. Decide what a null means and replace or flag it.
Later chapters cover Spark aggregation and encoding in detail. Here the goal is to understand why the work matters and where it goes wrong.
Why it matters
For tabular problems, the quality of the features usually limits the quality of the model more than the choice of algorithm does. A simple model with well-designed features often beats a complex model fed raw columns. Features also carry business knowledge. "Days since last order" encodes a hypothesis about churn that no algorithm will discover from a timestamp column alone.
Features matter operationally for a second reason. A model is only as reliable as the features it receives at prediction time. If those values differ from the ones used in training, accuracy drops even though nothing in the model has changed.
The working model: features are a pipeline, not a step
It helps to think of features as a pipeline with a lifecycle, not as a one-off notebook cell.
Each stage has its own failure modes:
- Raw tables change as upstream systems change. A renamed column or a new null pattern silently alters your features.
- Feature code encodes definitions. If two people write "active user" differently, two models disagree about who is active.
- The feature table is where computed values are stored for reuse. Without storage, every team recomputes the same features.
- The training set joins features to labels. The join must respect time, or the model sees information from the future.
- Scoring needs the same feature definitions as training, applied to fresh data.
The rest of this tutorial maps onto this lifecycle. Feature tables in Unity Catalog address stages 3 to 5.
A small example
The following code computes per-user features from a few order rows. It runs anywhere pandas is installed.
import pandas as pd
orders = pd.DataFrame(
{
"user_id": [1, 1, 2],
"amount": [20.0, 40.0, 15.0],
}
)
features = (
orders.groupby("user_id")["amount"]
.agg(order_count="count", avg_order_amount="mean")
.reset_index()
)
print(features)The output has one row per user_id:
| user_id | order_count | avg_order_amount |
|---|---|---|
| 1 | 2 | 30.0 |
| 2 | 1 | 15.0 |
The raw table had three rows and the feature table has two. This change in grain, from one row per event to one row per entity, is the core of most feature engineering. The entity here is the user, and user_id becomes the key that identifies each row. Chapter by chapter, that key grows in importance, because it is how features are joined to labels and looked up at scoring time.
Common errors
Training-serving skew
Training-serving skew means the features a model sees at serving time are computed differently from the features it trained on. A typical cause is two code paths. A data scientist writes pandas code for training, and an engineer later rewrites it in SQL or another language for production. Small differences accumulate: a different null default, a 30-day window instead of 90, a different rounding rule. The model keeps running and returns plausible numbers, which makes this failure hard to detect.
The fix is to define each feature once, store it, and retrieve it the same way in both phases. That is the main reason feature tables exist.
Label leakage
Label leakage happens when a feature contains information that would not have been available at the moment of prediction. Suppose you predict whether a user churns on June 1, and your "order count" feature is computed on July 1. Users who churned stopped ordering, so the feature quietly reveals the answer. Offline metrics look excellent and production results disappoint.
Leakage is a time problem. Any feature that changes over time needs a clear answer to "as of when?" The time series and point-in-time chapters return to this.
Duplicated and inconsistent definitions
When features live inside individual notebooks, teams rebuild them repeatedly. The copies drift. One notebook filters out test accounts and another does not. Reuse through a governed, shared table removes that duplication.
Silent null handling
Aggregations over missing data produce nulls or zeros that mean different things. A user with no orders in 90 days has a null average, but a count of zero is a legitimate value. Decide per feature whether to fill, flag, or exclude, and apply the rule in one place.
Where Databricks fits
Databricks addresses these problems with Unity Catalog feature tables. A feature table is a Delta table with a primary key, stored under a governed catalog.schema.table name. You compute features once with Spark, write them to the table, and build training sets by looking features up by key. When you log a model with its feature lookups, the same lookups run at batch scoring and online serving, which reduces skew by construction. Unity Catalog adds permissions and lineage, so you can see who owns a feature and which models depend on it.
The following table summarizes how each problem from the previous section maps to a capability covered later.
| Problem | Capability | Covered in |
|---|---|---|
| Training-serving skew | Model logged with feature lookups | Model packaging, batch scoring |
| Label leakage | Point-in-time lookups with time series columns | Point-in-time correctness |
| Duplicated definitions | Shared, governed feature tables | Feature tables, discovery |
| Stale values | Scheduled feature pipelines | Feature pipelines |
What to carry forward
- A feature is a model-ready value, and feature engineering changes the grain of data from events to entities.
- Feature quality, consistency, and timing determine production accuracy as much as the model does.
- Skew and leakage are the two failures to design against from the start.
- Storing features once, keyed by entity, is the foundation for everything that follows.
Exercise
A team trains a churn model with pandas code that counts a user's orders over 90 days. The production job, written separately in SQL, counts orders over 30 days. Offline accuracy is 0.91, but production accuracy is much lower. Name the problem and describe the structural fix.
Show answer
This is training-serving skew: the same feature name is computed differently in training and serving. The structural fix is to define the feature once, store it in a shared feature table keyed by the entity (here user_id), and retrieve it through the same lookup in both training and scoring, instead of keeping two separate implementations.
Exercise
You build a "total orders" feature on July 1 and join it to churn labels dated June 1. Why is the model likely to look better offline than it will perform in production?
Show answer
The feature includes orders placed after the prediction date, and users who churned stopped ordering, so the feature leaks information about the label. This is label leakage. The feature must be computed as of each label's timestamp, which later chapters handle with time series columns and point-in-time lookups.