Sub topic 10
Building training sets from labels and features
A training set joins a labeled DataFrame to features stored in feature tables. This chapter assumes you can write PySpark, know the feature table and lookup concepts from earlier chapters, and understand the basic training and evaluation workflow.
The working model
You supply a DataFrame of labels and lookup keys. Each FeatureLookup names a feature table, the features to read, and the key to match on. create_training_set combines them into a TrainingSet object. Calling load_df() on that object runs the join and returns a normal Spark DataFrame.
The training set also records which tables and features it used. Later, when you log a model, that record travels with the model.
Building one
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()Here is what each argument does:
dfis the labeled DataFrame. It must contain the lookup key columns.feature_lookupslists where the features come from. You can pass several lookups against different tables.labelnames the label column, so the model knows what it predicts.exclude_columnsdrops columns from the result. Keys such asuser_idare identifiers, not signals, so removing them keeps the model from memorizing them.
If you omit feature_names, the lookup returns every non-key column in the table.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Error that a lookup key is missing | The labeled DataFrame has no column matching `lookup_key` | Rename or add the column before calling `create_training_set` |
| Many null features | Labeled keys have no matching row in the feature table | Check key coverage, then decide on imputation |
| Name collisions between tables | Two tables share a feature name | Use `rename_outputs` in the lookup to give each a unique name |
| Permission error | You lack `SELECT` on a feature table | Ask for access in Unity Catalog |
Exercise
Your labeled DataFrame has columns user_id, event_ts, and label. You want only avg_order_amount_90d from main.ml.user_features, and you do not want user_id in the model's input. Which arguments of FeatureLookup and create_training_set do you set?
Show answer
In FeatureLookup, set table_name="main.ml.user_features", feature_names=["avg_order_amount_90d"], and lookup_key="user_id". In create_training_set, pass the labeled DataFrame as df, the lookup list as feature_lookups, label="label", and exclude_columns=["user_id"]. You may also exclude event_ts if it is not a model input.