Part IV — Expert Production Engineering · Chapter 19 · Lesson 1 of 7 · 8 min read
Lesson 1: Seeded Splits, Preprocessing, Scaling, Imputation, and Encoding
Lesson level: Advanced
Purpose: Prepare tabular data for learning so that evaluation is honest, results are reproducible, and the same transformations can be applied identically in training and in production.
Learning objectives
By the end of this lesson you will be able to:
- distinguish features, target, training data, validation data, and test data
- create seeded, reproducible splits, including stratified and group-aware splits
- explain why preprocessing must be fitted on training data only
- scale numeric features with standardization and min-max scaling
- impute missing values and record that they were missing
- encode categorical features with one-hot and ordinal encoding and handle unseen categories
1.1 The supervised-learning setup
A supervised dataset is a table in which each row is an example, most columns are features (inputs), and one column is the target (the answer to be predicted). When the target is a number — hours, revenue, price — the task is regression. When it is a category — churn or stay, low, medium, or high risk — the task is classification.
Before touching a model, write a one-paragraph problem statement: the decision the prediction supports, the moment at which the prediction is made, the target definition, and the features that will genuinely be available at that moment. That last point prevents target leakage: a feature such as "account closed date" will predict churn perfectly in history and be unavailable when the prediction is actually needed.
1.2 Three datasets, three jobs
| Set | Used for | Rule |
|---|---|---|
| Training | Fitting preprocessing and model parameters | The only data a fit step may see |
| Validation | Comparing models and choosing settings | May be reused during development, or replaced by cross-validation (Lesson 4) |
| Test | Final, one-time estimate of performance | Touched once, after all choices are frozen |
Every time a decision is made by looking at a dataset, that dataset stops being an unbiased judge. The test set is valuable precisely because nobody has tuned anything against it. Lock it away at the start of the project and report it once.
1.3 Seeded, reproducible splits
Random splits must be seeded: a fixed seed makes the same rows land in the same sets on every run, so results can be reproduced, compared, and audited. Record the seed with the experiment, just like a code version.
Illustrative listing.
from pealang.data import read
from pealang.ml import train_test_split
df = read("customers.csv")
X = df.drop(["churned"])
y = df.column("churned")
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, seed=42, stratify=y)
print(X_train.height, X_test.height)
print(y_train.mean(), y_test.mean()) # class balance should match
Stratification keeps the class proportions the same in each split. It matters when one class is rare: with 3% churners, an unstratified 20% test split of 1,000 rows could contain 3 or 12 churners by chance, and every metric computed on it would be unstable.
Group-aware splits keep all rows that belong to one entity in the same split. If a customer appears in many rows, putting some in training and some in test lets the model memorize that customer and look better than it is. Split by customer ID, and stratify at the group level where possible.
Time-aware splits apply whenever the prediction will be made about the future, as in Chapter 18: train on the past, test on the later period. A random split of time-ordered data repeats the leakage problem of Chapter 18, Lesson 4.
1.4 Fit on training data, transform everything
Every preprocessing step that learns something from data — a mean for scaling, a median for imputation, the list of categories for encoding — has two phases. Fit learns the parameters; transform applies them. Fit only on the training set, then transform the training, validation, test, and production data with the same fitted parameters.
Fitting a scaler on the full dataset before splitting leaks information about the test set into training. The effect is often small for scaling and large for target-based encodings, but the rule has no exceptions: if a step can learn, it learns from training data only. Lesson 6 shows how pipelines enforce this automatically.
1.5 Scaling numeric features
Features measured in different units — age in years, income in rupees, tenure in days — have very different ranges. Many algorithms, including regularized linear models and anything distance-based, behave better when features are on comparable scales.
| Scaler | Formula | Use when |
|---|---|---|
| Standardization | (x − mean) / standard deviation | Default for linear and logistic models |
| Min-max | (x − min) / (max − min) | A bounded 0–1 range is required |
| Robust | (x − median) / interquartile range | Heavy outliers distort the mean and standard deviation |
Guard against a zero standard deviation or zero range: a constant feature carries no information and should be dropped or left unscaled. Values in production can fall outside the training range, so min-max-scaled features may be below 0 or above 1; decide whether to clip them and record the choice.
1.6 Imputing missing values
Most models cannot use null values directly. Imputation replaces them with a learned value: the training mean or median for numbers, the most frequent value or an explicit "missing" category for categories.
Missingness is often informative — a customer who never filled in a phone number may behave differently from one who did. Add a boolean was_missing indicator column for features where that is plausible, so the model can use the fact of missingness rather than only the filled value. Above all, investigate why data is missing; imputation repairs the symptom, not the cause.
Illustrative listing.
from pealang.ml import SimpleImputer, StandardScaler
imputer = SimpleImputer(strategy="median", add_indicator=True)
scaler = StandardScaler()
num_cols = ["age", "tenure_days", "monthly_spend"]
Xn_train = scaler.fit_transform(imputer.fit_transform(X_train.select(num_cols)))
Xn_test = scaler.transform(imputer.transform(X_test.select(num_cols)))
Note the asymmetry: fit_transform on training data, transform only on test data.
1.7 Encoding categorical features
- One-hot encoding creates one 0/1 column per category. It makes no assumption about order and is the default for nominal categories such as region or product line.
- Ordinal encoding maps ordered categories to integers — low = 0, medium = 1, high = 2. Use it only when the order is real.
- Grouping rare categories into an "other" bucket keeps one-hot encoding from creating hundreds of nearly empty columns.
Production data will contain categories that training data did not. Decide in advance: map unseen values to an "unknown" column (or to all zeros) and count how often it happens. A sudden rise in unknown categories is an early warning of upstream change and belongs in the monitoring of Chapter 20.
Never ordinal-encode a nominal category. Encoding regions as north = 1, south = 2, east = 3 tells a linear model that east is "three times" north, which is meaningless and can be harmful.
1.8 Annotated example: a preprocessing audit
A churn model reports 0.97 accuracy in development and 0.71 in its first month of production. A preprocessing audit finds:
- The scaler and imputer were fitted on all rows before the split.
- A feature called days_since_last_contact was computed at extraction time, after many churned customers had already been contacted by the retention team — target leakage.
- The split was random by row, and many customers appeared in both training and test data.
- Region was ordinal-encoded alphabetically.
After fixing all four — fit on training only, removing the leaking feature, splitting by customer, and one-hot encoding region — development accuracy fell to 0.78 and production stayed close to it. The lower number was the honest one. The audit took a day; the misplaced confidence had cost a quarter of retention spending.
Common mistakes
- Unseeded splits: results cannot be reproduced or compared.
- Preprocessing before splitting: fit every learning step on training data only.
- Leaking features: check that every feature exists at prediction time.
- Row-level splits for grouped data: keep each entity in one split.
- Ordinal-encoding nominal categories: use one-hot encoding unless order is real.
- Silent imputation: add missing indicators where missingness may matter, and report imputation counts.
- No plan for unseen categories: define and count the unknown bucket.
Guided practice
- Split the same data with two different seeds and compare class balance and a simple metric. How large is the difference?
- Fit a scaler on all data and on training data only; compare the learned means and the test metric.
- One-hot encode a region column, then introduce a new region in test data and confirm your handling.
Hands-on lab: A reproducible preprocessing step
- Load a customer table with numeric, categorical, and missing values and a binary churn target.
- Write a problem statement and remove any feature not available at prediction time.
- Create a seeded, stratified, customer-grouped 80/20 split; verify that no customer is in both sets.
- Fit median imputation with missing indicators and standardization on training numeric features; fit one-hot encoding with an unknown bucket on categorical features.
- Transform training and test data; record the fitted parameters (medians, means, standard deviations, category lists) in a small JSON report.
- Rerun the whole step and confirm the outputs and report are identical.
Review questions
- What is the difference between the validation set and the test set?
- Why must splits be seeded?
- When should a split be stratified, and when group-aware?
- Why must preprocessing be fitted on training data only?
- When is robust scaling preferable to standardization?
- Why add a missing-value indicator?
- How should a pipeline handle categories not seen during training?
Applied challenge
An insurer wants to predict whether a claim will need manual review. Claims belong to policies, many policies have several claims, and the data spans three years. Design the split strategy, the leakage review, and the preprocessing plan. Justify each choice and list which fitted parameters must be stored with the model.
Lesson summary
Honest machine learning starts before the model. Define the prediction moment, remove leaking features, split with a recorded seed and the right stratification, grouping, or time ordering, fit every preprocessing step on training data only, and treat missing values and unseen categories as explicit, monitored decisions.
Transition to Lesson 2
With clean, comparable features, Lesson 2 fits the first two model families: linear regression for numbers and logistic regression for categories.
Lesson status: Ready for review.