Preprocessing pipelines
Prepare features without learning from the future
A preprocessing pipeline is an ordered sequence of data transformations followed, in a supervised task, by a fitted predictor. It converts raw records into a consistent representation. Imagine predicting packing time from package weight and packaging type. Weight may be missing; packaging type is a category, not a number with a natural distance. A model must receive the same feature definitions at training and inference. The training subset determines any learned parameters; validation and test records only pass through the frozen transformation. This extends the earlier leakage lesson: a transform can leak information even without reading a target.
Fit numeric statistics once
Fit means estimating parameters from examples. Transform means applying already estimated parameters. For training weights [2, 6, missing, 4], the observed mean is 4 kg. Mean imputation fills the missing weight with 4, producing [2, 6, 4, 4]. The population variance of these filled values is 2 kg²; the scale is sqrt(2) kg. A new weight of 10 becomes (10−4)/sqrt(2) ≈ 4.243, not zero. A missing new weight becomes zero after centering, because it is imputed to the fitted mean. The code chooses scale 1 for constant features and rejects an entirely missing training column; these are explicit toy policies. Inputs are finite numeric values or None. The statistics are computed after imputation, not on the observed-only subset. Standardization changes units, not the distribution shape; it does not guarantee a Gaussian feature. Imputation may hide useful missingness information, so consider an additional indicator or a model that handles missing values.
def fit_numeric(train): observed = [x for x in train if x is not None] if not observed: raise ValueError("Need at least one observed training value") mean = sum(observed) / len(observed) filled = [mean if x is None else x for x in train] scale = (sum((x - mean) ** 2 for x in filled) / len(filled)) ** 0.5 return mean, scale or 1.0
def transform_numeric(values, fitted): mean, scale = fitted return [((mean if x is None else x) - mean) / scale for x in values]
fitted = fit_numeric([2, 6, None, 4])print(fitted[0])print([round(x, 3) for x in transform_numeric([10, None, 2], fitted)])Encode categories with a fixed vocabulary
One-hot encoding represents each known category with a separate binary coordinate. A training vocabulary sorted as [bag, box] gives bag [1,0] and box [0,1]. The toy encoder maps an unseen crate to [0,0]; it never expands the feature vector during inference. This is an explicit policy, not a universal default. In production, consider an unknown bucket, rejection, or monitoring the unseen-category rate. If a reference category is dropped, an all-zero row may also represent that reference, so interpretation changes. Integer codes such as bag=1 and box=2 imply artificial order and distance for many models. Ordinal encoding is appropriate only when its meaning and estimator behavior fit the problem. Input categories here are strings; an empty vocabulary yields empty rows.
def fit_categories(train): return sorted(set(train))
def encode_categories(values, categories): return [[int(x == category) for category in categories] for x in values]
categories = fit_categories(["box", "bag", "box"])print(categories)print(encode_categories(["bag", "crate", "box"], categories))Compose transformations and feature extraction
Numeric and categorical columns may need different steps. A practical order is split by the real prediction unit, fit imputers and encoders on training only, fit scaling on imputed training numbers, concatenate features in a recorded order, and fit the predictor. At validation time apply the same stored vocabulary and numeric statistics. Feature extraction creates new representations such as a package volume from three measurements, but check that each measurement exists at prediction time and units agree. A logarithm may reduce the influence of a long right tail for positive data; zeros and negatives need a deliberate domain policy. Tree splits often need less scaling than distance-based models, but missing-value and category handling still matter. Avoid blindly scaling identifiers or fitting a feature selector before splitting. Keep the fitted transformation and model version together.
Library mapping and common failures
In scikit-learn, a Pipeline can combine transformers and an estimator; ColumnTransformer can assign separate transformations to numeric and categorical columns. SimpleImputer, StandardScaler and OneHotEncoder are examples of transformers. Each validation fold must fit its own complete pipeline using only that fold’s training partition. Do not run fit_transform on a held-out subset or encode every row before cross-validation. A pipeline cannot repair a target-derived feature, duplicated entities across folds, or a split that leaks future information. The local examples are deliberately small Python teaching functions, not replacements for the library. A pinned and reviewed scikit-learn lab remains optional and unexecuted. See the source-evidence register for official documentation.
Practice and recap
Change the training list to [5,5,None] and predict the transformed values [5,7,None]. The scale fallback is 1, so the result is [0,2,0]. Encode crate without changing the vocabulary. Explain why a training artifact must store the column order, units, mean and scale. In the next lesson, fit the entire pipeline separately inside each validation fold.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Preprocessing pipelines quiz
Apply feature preparation and generalization concepts.
Which fitted mean is subtracted from a held-out weight of 10 when training weights are [2, 6, None, 4]?
How should a fitted preprocessing pipeline handle a held-out validation partition?
With fixed vocabulary [bag, box], which vector represents crate under the lesson encoder policy?
What happens to [5,7,None] after fitting [5,5,None] in the numeric example?
When predicting packing duration before packing starts, which candidate feature leaks the outcome?