Sub topic 10
Building training sets from labels and features
This chapter covers how to turn a labeled DataFrame and a set of feature tables into a training DataFrame. It assumes you can create and write a feature table with a primary key, and that you know the FeatureLookup idea from the previous chapter. It also assumes you are comfortable with PySpark joins and the basic train and evaluate workflow.
What a training set is
A training set is a recipe. It pairs a labeled DataFrame with a list of feature lookups. The labeled DataFrame holds the rows you want to learn from, and the lookups say which feature columns to attach to each row.
The labeled DataFrame needs three things:
- A label column, such as
label. - One or more lookup key columns, such as
user_id, that match the primary key of a feature table. - A timestamp column, if you use point-in-time lookups (the next chapter covers this).
The feature columns do not belong in the labeled DataFrame. They come from the feature tables when you materialize the training set.
Creating a training set
The example below uses the feature table built earlier in this tutorial.
from databricks.feature_engineering import FeatureEngineeringClient, FeatureLookup
fe = FeatureEngineeringClient()
labels_df = spark.table("main.ml.churn_labels") # user_id, label
feature_lookups = [
FeatureLookup(
table_name="main.ml.user_features",
feature_names=["order_count_90d", "avg_order_amount_90d"],
lookup_key="user_id",
)
]
training_set = fe.create_training_set(
df=labels_df,
feature_lookups=feature_lookups,
label="label",
exclude_columns=["user_id"],
)
training_df = training_set.load_df()Three details are worth knowing.
create_training_setis lazy. It validates the lookups and records them, but the join runs when you callload_df()and then act on the result.load_df()returns a Spark DataFrame. The columns are the labeled DataFrame's columns, plus the looked-up features, minus anything inexclude_columns.- Excluding
user_idkeeps an identifier from becoming a model input. An ID column can let a tree model memorize individual users, so exclude it unless you have a reason not to.
How the join behaves
The lookup is a left join from the labeled DataFrame to the feature table. Every labeled row stays in the output. If a key has no match in the feature table, its feature values are null. The row count does not change, and nothing warns you.
This is a common source of silent quality problems. A new user who has no orders yet may exist in churn_labels but not in user_features. The model then trains on rows full of nulls. Check for this after loading:
from pyspark.sql import functions as F
null_rates = training_df.select(
[F.avg(F.col(c).isNull().cast("int")).alias(c) for c in training_df.columns]
)
null_rates.show()If a feature's null rate is higher than you expect, compare the keys in the labeled DataFrame against the feature table. Then decide whether to fix the feature pipeline or to impute explicitly. Use the approach from the encoding chapter, and make sure scoring uses the same one.
Selecting and naming features
If you leave out feature_names, the lookup returns every non-key column in the table. That is convenient for exploration. For production models, list the features explicitly. A new column added to the table later then cannot change what your model trains on.
Name collisions are the most common error when you build a training set. Two situations cause them:
- A feature has the same name as a column in the labeled DataFrame.
- Two lookups return columns with the same name, for example when you look up the same table twice with different keys.
Use rename_outputs to resolve both:
lookups = [
FeatureLookup(
table_name="main.ml.user_features",
feature_names=["order_count_90d"],
lookup_key="buyer_id",
rename_outputs={"order_count_90d": "buyer_order_count_90d"},
),
FeatureLookup(
table_name="main.ml.user_features",
feature_names=["order_count_90d"],
lookup_key="seller_id",
rename_outputs={"order_count_90d": "seller_order_count_90d"},
),
]Here the labeled DataFrame has two key columns, buyer_id and seller_id, and both look up into the same table. The renamed output columns are the names the model sees, and they are also the names the logged model expects at scoring time.
Lookup keys with different names or several columns
lookup_key names a column in the labeled DataFrame. It does not have to match the primary key name in the feature table, and the key columns are matched to the table's primary keys by position. For a composite primary key, pass a list:
FeatureLookup(
table_name="main.ml.store_product_features",
lookup_key=["store_id", "product_id"],
)List the keys in the same order as the table's primary keys. A swapped order produces a join that matches the wrong rows or none at all, and again you get nulls instead of an error.
Combining several feature tables
A training set can mix lookups from many tables, such as user features, product features, and a time series table. Each lookup is a separate left join, so the cost grows with the number of tables. Keep these points in mind:
- Each feature table should have a primary key that is unique per row. If the key is not unique, the join multiplies labeled rows. Unity Catalog primary key constraints are informational and not enforced, so a bad write can create duplicates. Check uniqueness after writes.
- Join order does not change the result, because every join starts from the labeled DataFrame.
- You need
SELECTpermission on every feature table in the training set, andUSE CATALOGandUSE SCHEMAon the parents.
Splitting data and training
Split the data after you load the training DataFrame, not before you create the training set. The training set only describes the join. Then convert to pandas if the data fits in driver memory:
train_df, test_df = training_df.randomSplit([0.8, 0.2], seed=42)
train_pdf = train_df.toPandas()
X_train = train_pdf.drop(columns=["label"])
y_train = train_pdf["label"]For data with a time order, a random split can leak information from the future into training. Split by time on the event timestamp instead.
You must keep the original training_set object, not only the loaded DataFrame. Pass it to fe.log_model in the next chapter. It carries the lookup definitions that let the model retrieve the same features later.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Error about duplicate column names | A feature name matches a column in the labeled DataFrame, or two lookups return the same name | Use `rename_outputs` or drop the column from the labeled DataFrame |
| Many null features | Keys missing from the feature table, wrong key order, or mismatched data types | Compare key sets and types, then fix the pipeline or impute |
| More rows than labels | Duplicate primary keys in the feature table | Deduplicate the table and rewrite with `merge` |
| Permission denied | No `SELECT` on a feature table | Grant access on the table and `USE` on its catalog and schema |
| Label appears as a feature | `label` omitted or passed incorrectly | Set `label="label"` so it is separated from the inputs |
Exercise
A labeled DataFrame has 10,000 rows. After create_training_set(...).load_df() it has 10,000 rows, but order_count_90d is null in 1,200 of them. What most likely happened, and why did no error appear?
Show answer
Those 1,200 user_ids have no matching row in the feature table. The lookup is a left join, so unmatched labeled rows are kept and their features are null. Nothing fails because a missing key is valid for a left join. Check the key sets, then either add the missing users to the feature pipeline or impute explicitly, and apply the same handling at scoring time.