Python Master Course V2 — 132. Preprocessing Pipelines and Feature Engineering
Purpose and learning outcomes
Real tables mix measurements, categories, and missing entries. A reliable predictor must transform all of them consistently, including rows arriving tomorrow. This lesson builds a single fitted object that remembers numeric medians, scaling statistics, category vocabulary, and the classifier. The goal is to make a leakage-safe transformation contract easy to test.
- Fit transformations using training data only
- Combine numeric and categorical preprocessing with ColumnTransformer
- Validate schemas and handle unseen categories deliberately
Prerequisites: 124: cleaning and leakage; 131: scikit-learn workflow.
Environment and run order
Use a dedicated Python 3.11 or 3.12 virtual environment. These exercises use local synthetic or bundled data; no account, API key, or dataset download is needed. The shell commands install free packages. Run the Python blocks in order in one lesson file; worked solutions continue from that file unless stated otherwise.
Shell
python -m venv .venv
# macOS/Linux: source .venv/bin/activate
# Windows PowerShell: .venv\Scripts\Activate.ps1
python -m pip install numpy pandas scikit-learn matplotlib joblib
python -m pip freeze > requirements-observed.txt
Understand the model and the evidence
Learned transformations belong inside the experiment
Replacing an impossible negative age according to a documented business rule is different from learning a median from observations. The latter uses the dataset and must see training rows only. StandardScaler likewise learns a mean and scale for each numeric column. Even a transform that never reads y can leak information if it learns from validation or test rows. The pipeline places these operations inside fit and reuses their learned state during predict.
Two branches, one feature matrix
ColumnTransformer sends named columns to different transformer branches, then joins their results. The numeric branch imputes medians and scales values; the category branch imputes a missing marker and creates one indicator per observed category. One-hot encoding avoids inventing an order such as red < blue < green. Dense output is convenient for this tiny demonstration, while high-cardinality categories can make a dense representation impractically large.
What happens to an unseen category
handle_unknown="ignore" produces zeros for the unseen category’s indicator block rather than crashing. That behavior is a fallback, not an assertion that an unknown region is harmless. Monitor how frequently it happens and decide whether a real application should reject, flag, or retrain. Missing categories receive a deliberate token, separating missingness from a legitimate named region.
Feature engineering has a clock
A feature is legitimate only if its value exists when the prediction would be made. A ratio of two available measurements may be useful; a refund outcome recorded after the target event is leakage. Schema checks enforce column names, but cannot prove temporal availability. Write down feature meaning, units, permitted missingness, and whether the feature is entered by a person or generated automatically.
Incremental worked example
1. Generate a mixed-type table and reserve rows
The synthetic late-delivery label depends on distance, item count, region, and noise. We deliberately hide some distances only after generating labels. This mimics unavailable measurements without deriving the label from an imputed value. The random generator is local to the experiment.
Python
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression
rng = np.random.default_rng(32)
n = 360
distance = rng.uniform(1, 50, n)
items = rng.integers(1, 8, n)
region = rng.choice(["north", "south", "west"], n)
y = (distance + 3 * items + 9 * (region == "west")
+ rng.normal(0, 8, n) > 43).astype(int)
X = pd.DataFrame({"distance": distance, "items": items, "region": region})
X.loc[rng.choice(n, 30, replace=False), "distance"] = np.nan
X_train, X_valid, y_train, y_valid = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=32)
assert X.columns.tolist() == ["distance", "items", "region"]
2. Build, fit, and probe the complete pipeline
The double-underscore names in later lessons address nested parameters. Here named branches make the learned feature names inspectable. Cross-validation receives the unfitted pipeline specification, so it fits fresh imputation and scaling within each training fold rather than reusing full-data statistics.
Python
numeric = Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler())])
categorical = Pipeline([
("impute", SimpleImputer(strategy="constant", fill_value="missing")),
("encode", OneHotEncoder(handle_unknown="ignore", sparse_output=False))])
features = ColumnTransformer([
("numeric", numeric, ["distance", "items"]),
("category", categorical, ["region"])])
model = Pipeline([("features", features),
("classifier", LogisticRegression(max_iter=500))])
fold_scores = cross_val_score(model, X_train, y_train, cv=3,
scoring="balanced_accuracy")
model.fit(X_train, y_train)
probe = pd.DataFrame({"distance": [np.nan], "items": [2], "region": ["east"]})
print("fold scores", fold_scores)
print("feature names", model.named_steps["features"].get_feature_names_out())
print("unseen-region prediction", model.predict(probe))
print("validation accuracy", model.score(X_valid, y_valid))
Expected output / interpretation
Fold scores and validation accuracy are runtime measurements, not fixed targets.
The numeric branch contributes two columns; the category branch contributes one per training category.
The unseen east region is accepted and produces exactly one prediction.
Guided lab and acceptance criteria
- Before running, draw the two transformation branches and annotate what each fit step learns. Then inspect the fitted imputer statistics and encoder categories and connect them to your drawing.
- Create three inference rows: an ordinary complete row, a row with missing distance, and a row with an unseen region. Confirm that the transformed matrices have identical feature counts. Print the unseen row’s category block and explain its all-zero encoding.
- Add a schema-checking function that rejects missing required columns and impossible item counts before calling predict. Test it on a deliberately broken table. Keep the validation set out of rule discovery if the rule is a learned cutoff rather than a known domain constraint.
- Deliver the pipeline, probe cases, fold scores, and a feature dictionary. A passing result handles valid missingness consistently, rejects invalid schema clearly, and never fits preprocessing outside a training fold. There is no minimum accuracy requirement.
Common mistakes and repairs
- Calling fit_transform on validation: use transform or the complete pipeline’s predict so training statistics are reused.
- Passing raw strings to LogisticRegression: numeric estimators require a numeric representation; encoding defines one without claiming categories have a natural order.
- Silently ignoring unexpected input columns: document whether extra fields are allowed and explicitly check required names. Column selection alone is not a complete data contract.
Questions that test understanding
Why not fill missing distances with the global median first?
The global median depends on held-out inputs. This can make evaluation reflect knowledge unavailable when training on earlier observations. Putting SimpleImputer inside the pipeline makes every fold calculate its own training median and apply it unchanged to that fold’s validation rows.
Does StandardScaler make every feature normally distributed?
No. It changes location and scale; skewness, multimodality, and extreme observations remain. Scaling helps some optimization and distance calculations, but is not a distributional repair. Inspect the original measurements when deciding whether a transform or a robust alternative is appropriate.
Why not encode north, south, west as 0, 1, 2?
A linear model would treat those numbers as a meaningful ordered distance. One-hot features allow separate category contributions. An ordinal code is defensible only when the ordering and its numerical interpretation are appropriate for the problem, not merely because a library needs numbers.
Is an unknown category the same as missing?
No. Missing means the field was not observed; unknown means a value appeared that was absent from the training vocabulary. The example imputes missing category values explicitly, while unknown values produce a zero indicator block. Their operational causes and monitoring rules can differ.
Why cross-validate the pipeline rather than its transformed array?
The array would usually already contain transformations learned from all rows supplied before cross-validation. A pipeline specification lets each fold fit every learned step only on its training portion. This also evaluates the complete procedure that will be used on new raw records.
Can a perfectly implemented pipeline still leak?
Yes. If distance were secretly replaced by a post-delivery measurement, the feature itself would reveal future information. Pipelines prevent a common mechanical error, not every conceptual error. Feature availability, repeated subjects, and target definition still need a human-readable audit.
Exercises with worked solutions
Exercise 1: Inspect fitted medians safely
Reveal the worked solution and reasoning
The fitted numeric branch is nested inside the ColumnTransformer. Reading its statistics does not refit anything. Compare with X_train medians rather than full-table medians to verify the intended boundary.
Python
fitted_numeric = model.named_steps["features"].named_transformers_["numeric"]
print(fitted_numeric.named_steps["impute"].statistics_)
print(X_train[["distance", "items"]].median().to_numpy())
Exercise 2: Check prediction schema
Reveal the worked solution and reasoning
Reject missing fields before entering the model so the error explains the contract. Select an intentional order and leave imputation to the fitted pipeline. Do not replace validation-specific missing values with a new median during inference.
Python
def predict_checked(frame):
required = ["distance", "items", "region"]
missing = set(required) - set(frame.columns)
if missing:
raise ValueError(f"Missing columns: {sorted(missing)}")
if (frame["items"] < 1).any():
raise ValueError("items must be at least one")
return model.predict(frame[required])
assert predict_checked(probe).shape == (1,)
Recap and next step
Keep feature meaning and transformation state together. A ColumnTransformer describes branches, a Pipeline makes their fitting order explicit, and inference checks protect the input contract. In the next lesson the same discipline supports regression and meaningful comparisons among regularized models.
Official references
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.