Sub topic 3
Encoding categories, scaling, and handling missing values
This chapter assumes you can write PySpark DataFrame transformations and train a scikit-learn model. It also assumes you know what a Unity Catalog feature table is, from the earlier chapters. Raw columns rarely reach a model unchanged. Strings must become numbers, numeric ranges may need aligning, and nulls need a deliberate policy. The main decision is where each step runs: when you compute the feature table, or inside the model.
Where each step belongs
A feature table is shared by many models. A step that changes what a column means belongs in the table. A step that depends on statistics learned from one training set belongs in the model pipeline.
| Step | Put it in the feature table when | Put it in the model pipeline when |
|---|---|---|
| Cleaning strings (trim, case) | Always. Every consumer needs the same labels. | Never. |
| Missing-value sentinel for categories | The meaning of "unknown" is universal. | Rarely. |
| Numeric imputation | The null has a business meaning, such as zero orders. | The fill value is a statistic like the median. |
| One-hot encoding | Rarely. It widens the table and couples it to one model type. | Usually. |
| Scaling | Rarely. | Usually, because the mean and standard deviation come from training data. |
Encoding categorical columns
Most algorithms need numeric input. Three encodings cover most cases.
- One-hot encoding creates one 0/1 column per category. It suits low-cardinality columns such as country or plan type.
- Ordinal (index) encoding maps each category to an integer. It is compact, and tree models handle it well. Linear models read the integers as an order, which is wrong for unordered categories.
- Frequency or target encoding replaces a category with a count or a label statistic. It handles high-cardinality columns such as ZIP code. Target encoding uses the label, so it leaks information unless you compute it only on training folds.
Whichever you choose, plan for categories the model has never seen. A new country will appear in production. In scikit-learn, set handle_unknown="ignore" on OneHotEncoder. In Spark ML, set handleInvalid="keep" on StringIndexer. Without this, scoring fails on the first unseen value.
Handling missing values
A null can mean several things: the data was not collected, the event never happened, or an upstream join failed. Pick the fill by meaning, not by habit.
- A user with no orders in 90 days has an order count of 0. That is a true zero, so fill it with 0.
- A user with no orders has no average order amount. Zero would claim they spend nothing per order. Leave it null and let the model pipeline impute it, with a flag column.
- A missing country is a category in itself. Label it
unknown.
The following code cleans and fills at the feature-table level. It assumes tables main.sales.users (with user_id and country) and main.sales.orders.
from pyspark.sql import functions as F
users = spark.table("main.sales.users")
orders = spark.table("main.sales.orders")
orders_agg = (
orders
.filter(F.col("order_ts") >= F.date_sub(F.current_date(), 90))
.groupBy("user_id")
.agg(
F.count("*").alias("order_count_90d"),
F.avg("amount").alias("avg_order_amount_90d"),
)
)
country_clean = (
F.when(F.col("country").isNull() | (F.trim(F.col("country")) == ""), F.lit("unknown"))
.otherwise(F.upper(F.trim(F.col("country"))))
.alias("country")
)
user_features_df = (
users.select("user_id", country_clean)
.join(orders_agg, "user_id", "left")
# No orders means a true count of zero. The average stays null on purpose.
.withColumn("order_count_90d", F.coalesce(F.col("order_count_90d"), F.lit(0)))
)The left join keeps users with no recent orders. An inner join would drop them, and the model would never learn what inactive users look like.
Scaling numeric columns
Scaling puts columns on comparable ranges. StandardScaler subtracts the mean and divides by the standard deviation. Whether you need it depends on the model.
- Linear models, logistic regression, k-nearest neighbors, SVMs, and neural networks are sensitive to feature scale. Scale for these.
- Tree ensembles such as random forests and gradient boosting split on thresholds and are unaffected by monotonic rescaling. Scaling does no harm but adds nothing.
The mean and standard deviation are learned parameters. If you scale the feature table itself, the stored values are tied to one snapshot. They silently go stale when you refresh the table, and any model trained earlier now sees shifted inputs. Keep raw values in the table.
Putting the steps inside the model
A scikit-learn Pipeline bundles preprocessing and the estimator into one object. The fitted medians, category lists, and scaling constants travel with the model when you log it. This code assumes training_set and training_df from the training-set chapter, with the lookups returning order_count_90d, avg_order_amount_90d, and country.
import mlflow
from databricks.feature_engineering import FeatureEngineeringClient
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import RandomForestClassifier
from sklearn.impute import SimpleImputer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
fe = FeatureEngineeringClient()
numeric_cols = ["order_count_90d", "avg_order_amount_90d"]
categorical_cols = ["country"]
preprocess = ColumnTransformer([
(
"num",
Pipeline([
("impute", SimpleImputer(strategy="median", add_indicator=True)),
("scale", StandardScaler()),
]),
numeric_cols,
),
("cat", OneHotEncoder(handle_unknown="ignore"), categorical_cols),
])
pipeline = Pipeline([
("prep", preprocess),
("clf", RandomForestClassifier(n_estimators=100, random_state=42)),
])
train_pdf = training_df.toPandas()
X = train_pdf.drop(columns=["label"])
y = train_pdf["label"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
# Medians, categories, and scaling constants come from X_train only.
pipeline.fit(X_train, y_train)
print("Test accuracy:", pipeline.score(X_test, y_test))
mlflow.set_registry_uri("databricks-uc")
fe.log_model(
model=pipeline,
artifact_path="model",
flavor=mlflow.sklearn,
training_set=training_set,
registered_model_name="main.ml.churn_model",
)add_indicator=True appends a 0/1 column for each numeric column that had nulls during fitting. The model can then tell an imputed value from a real one, which helps when missingness itself predicts churn.
At batch scoring, fe.score_batch looks up the raw feature values and passes them to the logged pipeline. The same imputer, encoder, and scaler run on them, so training and serving transform data identically. This is how pipeline-based preprocessing reduces training-serving skew.
Common errors
- Fitting preprocessing before splitting. The test set then influences the medians and scaling constants, and your evaluation looks better than production will.
- Dropping the unknown-category setting. The model works in testing and fails at scoring when a new category appears.
- Changing the sentinel. If one pipeline writes
unknownand another writesUNKNOWNorN/A, the encoder treats them as different categories. Define the cleaning once in the feature pipeline. - Filling real signal with zeros. Zero-filling an average hides the difference between "spends nothing" and "never bought".
- Keeping scaled or one-hot columns in the shared table. Each refresh can change the values, and other teams cannot reuse the columns.
- Reading integer columns with nulls through
toPandas(). Pandas converts them to floats withNaN. This is harmless for the pipeline above, but check dtypes if you add custom steps.
Exercise
A teammate computes the mean of avg_order_amount_90d over the full feature table, fills nulls with it in the feature pipeline, and writes the result back. Name two problems with this approach and where you would move the fix.
Show answer
First, the mean includes rows that later fall into the test set, so every model trained on the table leaks test information. Second, the fill value changes at each refresh, and it hides the difference between real and missing values. Keep the nulls in the feature table, and impute inside the model pipeline with SimpleImputer(strategy="median", add_indicator=True), fitted on training rows only.
Exercise
Why is OneHotEncoder(handle_unknown="ignore") important for a model used in batch scoring?
Show answer
New category values, such as a country that did not appear in training, will show up in scoring data. With the default setting the encoder raises an error. With "ignore" it encodes the unseen value as all zeros, so scoring continues.