PeaBox Lab › PeaLang › Learn › Chapter 19 › Lesson 1

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:

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

SetUsed forRule
TrainingFitting preprocessing and model parametersThe only data a fit step may see
ValidationComparing models and choosing settingsMay be reused during development, or replaced by cross-validation (Lesson 4)
TestFinal, one-time estimate of performanceTouched 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.

ScalerFormulaUse when
Standardization(x − mean) / standard deviationDefault for linear and logistic models
Min-max(x − min) / (max − min)A bounded 0–1 range is required
Robust(x − median) / interquartile rangeHeavy 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

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:

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

Guided practice

Hands-on lab: A reproducible preprocessing step

Review questions

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.

← Previous Next →