Sub topic 3
Encoding categories, scaling, and handling missing values
This chapter assumes you can write PySpark DataFrame code and know what a training run and an inference run are. Models need numeric, complete input. Raw tables have text categories, columns on very different scales, and nulls. How you fix these shapes your features and decides whether training and serving agree.
Three common problems
| Problem | Typical technique | What to watch for |
|---|---|---|
| Text categories such as `country` | Index, then one-hot encode | Categories at inference time that training never saw |
| Columns on different scales | Standardize (mean 0, standard deviation 1) | The mean and deviation must come from training data only |
| Nulls | Impute, and add a missing-value flag | A null can carry meaning, for example "no orders yet" |
Fixed rules and fitted rules
Some transformations need no learning from data. coalesce(country, "unknown") is a fixed rule. Others learn parameters from the training data: the median used to fill nulls, the category-to-index map, and the scaling mean and deviation. These fitted rules are the usual source of training-serving skew. If you recompute them on scoring data, the same user gets different values.
A workable split is to put fixed rules in the feature table and keep fitted rules in a pipeline that is logged with the model.
Cleaning nulls in the feature table
from pyspark.sql import functions as F
users = spark.table("main.ml.user_profile") # user_id, country, age, avg_order_amount_90d
median_age = users.approxQuantile("age", [0.5], 0.01)[0]
features_df = (
users
.withColumn("age_missing", F.col("age").isNull().cast("int"))
.withColumn("country", F.coalesce(F.col("country"), F.lit("unknown")))
.fillna({"age": median_age, "avg_order_amount_90d": 0.0})
)The age_missing flag lets the model learn from the fact that a value was absent. Here a missing order average means no orders, so 0.0 is a sensible fill. A median is a better fill for age.
Encoding and scaling in a pipeline
from pyspark.ml import Pipeline
from pyspark.ml.feature import (
StringIndexer, OneHotEncoder, VectorAssembler, StandardScaler
)
indexer = StringIndexer(
inputCol="country", outputCol="country_idx", handleInvalid="keep"
)
encoder = OneHotEncoder(inputCols=["country_idx"], outputCols=["country_vec"])
assembler = VectorAssembler(
inputCols=["age", "avg_order_amount_90d"], outputCol="num_vec"
)
scaler = StandardScaler(
inputCol="num_vec", outputCol="num_scaled", withMean=True, withStd=True
)
pipeline = Pipeline(stages=[indexer, encoder, assembler, scaler])
pipeline_model = pipeline.fit(features_df)
encoded_df = pipeline_model.transform(features_df)fit learns the category map and the scaling statistics. transform applies them. Save pipeline_model with the model so scoring reuses the same values.
Why not store scaled values?
A scaled column depends on the training window. When the feature table is refreshed, stored scaled values would silently change meaning for every model that reads them. Store raw, cleaned values, such as age and age_missing, so many models can share the table. Each model then applies its own scaling.
Exercise
A feature table stores age already standardized using the mean and deviation of last month's users. Give one reason this is a problem for a second team that reads the same table.
Show answer
The stored values depend on last month's statistics, so they are tied to one training window. Another team cannot recover the raw age, and when the table is refreshed with new statistics, the values change meaning for models already trained on the old ones. Store the raw cleaned value instead and scale inside each model's own pipeline.