Concepts and worked examples

Preparing Reliable, Available Data

Prepare data that will be available when the model needs to make a prediction.

From business records to feature vectors

Models work with data, not the real world directly. Usually, each row is one example and its columns are the details the model can use. Data preparation joins records, fixes types, handles missing values, and reshapes columns when needed. The aim is simple: every feature should mean something and be available again when a prediction is made.

Start by documenting the unit, primary keys, target, horizon, source systems, timestamps, and feature definitions. Check join cardinality explicitly. Joining a customer table to many transactions can multiply customer rows, silently changing weights and label counts. Aggregate transactions to the intended customer-time unit before joining, or deliberately model the finer-grained unit. Reconcile row counts, unique entities, and totals before and after every major transformation.

Availability comes before convenience

A point-in-time feature uses only records available before its prediction timestamp. Event time and ingestion time can differ: an invoice dated Monday but loaded Wednesday cannot support Tuesday's real-time decision. Future cancellations, resolved claim amounts, and post-review outcomes are common sources of leakage. Labels may legitimately describe the future; predictors may not reveal that future.

Split evaluation data before learning preprocessing parameters. Fit imputation values, category vocabularies, scaling statistics, feature selection, and dimensionality reduction using training data only. During cross-validation, repeat these fits inside each training fold. Apply the resulting transformations unchanged to validation and test observations. A pipeline makes this boundary explicit and reduces training-serving discrepancies.

Missingness is information with a mechanism

Worked example: distinguish MCAR, missing completely at random; MAR, missingness explained by observed variables after conditioning; and MNAR, missingness still related to the unobserved value. These are assumptions about the process, not diagnoses established merely by inspecting one histogram. For example, customers with unusually high income may decline to report it, creating MNAR income data.

Preparation choices and safeguards
IssuePossible treatmentSafeguard
Missing numeric valuesTraining median, conditional imputation, or a model supporting missing values.Consider a missingness indicator; check subgroup behavior.
Nominal categoriesOne-hot encoding or another justified categorical representation.Handle unseen categories explicitly; avoid artificial ordinal distances.
Ordered categoriesDocumented ordinal coding where ordering is meaningful.Numeric spacing may impose unjustified equal differences.
Mixed numeric scalesStandardization or a robust alternative.Fit transformation statistics only on training observations.

Deleting incomplete rows can change the population and discard valuable information. Filling every missing value with zero conflates “unknown” with a real quantity. Missingness indicators can help prediction but may encode changing operational practices rather than stable relationships. Evaluate sensitivity to plausible mechanisms and document what the system does when required inputs are absent.

Encoding, scaling, and robust checks

One-hot encoding represents each category with an indicator; with an intercept, unregularized linear models usually omit a reference category to avoid exact redundancy. Target encoding uses category-level outcome information and therefore needs out-of-fold or other leakage-safe training construction. Rare and unseen categories require a predefined fallback rather than production failures.

Standardization uses z = (x − μ_train)/σ_train. Robust scaling can use (x − median_train)/IQR_train, where IQR is the upper quartile minus the lower quartile. Handle zero denominators explicitly. Scaling affects distance-based methods, regularized linear models, and SVMs; ordinary axis-aligned trees usually do not require it because monotonic rescaling preserves split ordering.

Inspect units, impossible ranges, duplicates, time zones, skew, and abrupt source changes. A large value may be a valid high-value customer rather than an error. Verify outliers before removing or capping them; learn any caps on training data and assess their business consequences. Log transformations may help nonnegative skewed quantities, but domain restrictions and interpretation matter.

Worked example: a reproducible transformation

Training account-spend values are 10, 20, 30, and 40, with one additional missing value. Fit the observed-value median: (20 + 30)/2 = 25. Impute the missing value to 25 and set its missingness indicator to one; observed rows receive zero. The completed training mean is 25. Using population standard deviation for this example gives √[(225 + 25 + 25 + 225 + 0)/5] = 10.

A new available spend of 45 becomes (45 − 25)/10 = 2. A new missing value becomes zero after imputation and scaling, but its indicator remains one. Do not recompute the mean using new evaluation customers. Persist the median, mean, scale, indicator definition, and category mapping so deployment produces exactly the same representation.

Production safeguards and worked examples

Business usefulness depends on timely inputs. Monitor freshness, null rates, unseen categories, schema versions, and feature distributions; test batch and online transformations for agreement. Specify fallback behavior when a source is delayed and distinguish changing inputs from changing outcome relationships. Track consent, retention, access, and subgroup coverage alongside predictive performance.

Why is global imputation before cross-validation a problem?

Validation observations influence a learned transformation, so the reported performance no longer evaluates a pipeline trained only on its training fold. Fit preprocessing separately inside each fold.

Should every model receive normalized inputs?

No. Scaling is consequential for distances and coefficient penalties, but usually unnecessary for ordinary trees. Choose transformations for the algorithm, measurement meaning, and deployment contract.

Related: problem framing, linear models, and validation.

Definition

View in glossary →