Skip to main content

Data Preprocessing

Docs: Preprocessing · Imputation · Pipelines and ColumnTransformer · Common pitfalls

Overview​

Preprocessing turns the EDA decision log into fixes: missing values, outliers, skew, scaling and encoding. The techniques are simple. The discipline is the hard part, because every step is a chance to leak the future into training data. On the machine-failure problem, one leaked column scored validation AUC 0.99 and production 0.65.

A dashboard feature computed over the 30 days before the query ran covers the days after the machine broke down, when vibration was zeroA dashboard feature computed over the 30 days before the query ran covers the days after the machine broke down, when vibration was zero

Figure L2-1: The same "last 30 days" feature, computed two ways. Green is the correct window, ending at the snapshot. Amber is the dashboard's window, ending when the query ran. Grey is the machine after breakdown.

Key concepts​

Decisions at a glance​

ProblemDefault fixAvoid#1 failure mode
Missing values (numeric)Median impute + missing-indicator columnDropping rowsImputing before splitting
Missing values (categorical)"missing" as its own categoryMode imputation on high-missingness columnsErasing the signal in the gap
OutliersInvestigate first; cap if real, fix if errorBlind 3σ removalDeleting your most critical machines
Skewed featuresLog / Yeo-Johnson transformRaw count and hour features into linear modelsOne 24/7 line dominating the fit
ScalingStandardScaler; RobustScaler if outliersScaling tree models (pointless)Fitting the scaler on all data
Low-cardinality categoricalsOne-hotOrdinal encoding of unordered categoriesInventing an order that isn't there
High-cardinality categoricalsTarget encoding, out-of-foldOne-hot into 1,000 columnsTarget encoding without CV
All of the aboveInside a sklearn PipelineManual fit/transform bookkeepingAny step fit outside the pipeline

The raw material​

The machine feature matrix as it arrives from the plant historian and the ERP. Every column has a problem, and each section below fixes one.

ColumnTypeWhat's wrong
load_cycles_30dnumericSpans 0 to 2.1M. Median 3,400, 24/7 lines 60× that
oil_analysis_scorenumericMissing for 11% of rows: every machine installed under 90 days ago
vibration_rms_30dnumericMissing for 0.3%: a March sensor-gateway outage, random
machine_age_daysnumericThree rows are negative (ERP install-date bug)
machine_typecategorical, 3 valuesNothing. The only innocent column
machine_modelcategorical, 400 values180 models have under 10 units in the fleet
avg_vibration_last_30dnumericScores AUC 0.99. That's the problem

The leakage bug that scores 0.99​

Every feature uses only data from before the snapshot date. The label comes only from after it. avg_vibration_last_30d broke that rule.

The column came from an old dashboard query that computed "last 30 days" at query time. For broken-down machines that window runs past the breakdown, where vibration is zero (Figure L2-1). The model learned "quiet machine means failed". That is the label, restated. Production scores running machines, so the signal doesn't exist there.

SymptomSeen here
One feature with dominant importanceavg_vibration_last_30d far ahead of the rest
Validation score too good for the problemAUC 0.99 on a problem where engineers can't call failures
Collapse after launchProduction AUC 0.65 one month later

The fix is structural, not a reminder. One feature-building function takes snapshot_date and filters event_time < snapshot_date on every table. Dashboard queries, historian views and "convenient existing columns" are the usual carriers, because none were built with a snapshot date in mind. Rebuild a suspect feature from raw events through that function and watch the score drop to something honest.

Missing values​

Why a value is missing matters more than what you fill it with. Diagnose the mechanism first: compare the failure rate with the value missing vs present.

MechanismMeaningPlant exampleSo what
MCARMissing completely at randomThe March gateway outageAnything works. Impute and move on
MARExplained by other observed columnsoil_analysis_score missing = machine under 90 days oldImpute, keep the indicator
MNARDepends on the unobserved value itselfOperators skip logging readings on machines they think are fineThe gap is the signal. Indicator mandatory

Machines missing oil_analysis_score fail at 8% vs 2.7%. That gap is the infant-mortality end of the bathtub curve. Impute-and-forget erases it.

StrategyUse whenResult on the plant data
Drop rowsAlmost never❌ Deletes exactly the new installs failing at 8%, and the same gaps still arrive at inference
Median / mode impute (SimpleImputer)Default⚠️ Works, but loses the "new install" signal
Impute + indicator (add_indicator=True)The gap has meaning (MAR/MNAR)✅ oil_analysis_missing lands in the top 10 features
KNN or iterative (MICE) imputeSmall data, correlated features➖ Buys nothing once the indicator exists. Trees barely care about the filled value
Own "missing" categoryCategoricals, always✅

Outliers​

Extreme is not wrong. The tail is often the equipment the plant cares about most.

Detection methodHowVerdict
IQR ruleFlag outside Q1 − 1.5·IQR to Q3 + 1.5·IQRSolid default, univariate
Z-scoreFlag beyond 3 standard deviationsSelf-defeating: outliers inflate the σ used to find them
Robust z (MAD)Same idea, median and MAD instead of mean and σUse this over plain z
Isolation Forest / LOFModel-based, multivariateFinds weird combinations, like high load with zero vibration (a dead sensor). See Anomaly Detection

Detection is the easy half. The decision depends on whether the value is possible and which model consumes it.

ValueModelActionResult
Impossible (negative machine_age_days)AnyFix at the source table✅ ERP install-date bug corrected
Real tail (24/7 lines in load_cycles_30d)Trees, boostingLeave it alone✅ Splits compare ranks, not magnitudes
Real tailLinear, SVM, KNN, MLPLog transform, winsorise at 1st/99th percentile, or RobustScaler✅ Keeps the row, bounds its leverage
Real tailAnyDelete past 3σ❌ Deletes the highest-throughput machines, the reason the project exists

Blind 3σ removal fails twice on imbalanced data. Skewed features put honest rows past 3σ, and the minority class is unusual by definition. It quietly deletes the failing 3% you're trying to predict.

Skew and scaling​

Transforms fix the shape of one feature. Scalers fix the units across features. Trees need neither.

TransformUse whenTool
log(x+1)Right-skewed counts and hoursnp.log1p in a FunctionTransformer
Box-Cox / Yeo-JohnsonLet the data pick the power. Yeo-Johnson handles zero and negativesPowerTransformer
Quantile → normalTails that defeat log; only rank mattersQuantileTransformer
ScalerMechanismUse when
StandardScalerSubtract mean, divide by σDefault
RobustScalerSubtract median, divide by IQRYou kept your outliers
MinMaxScalerSquash to 0–1Bounded inputs wanted. One outlier crushes the rest into a corner

Linear models, SVM, KNN and MLP need scaling (marked per model on the supervised pages). Trees and boosting don't. That's why scaling belongs in the model's pipeline, not baked into "the data".

On the plant data: log1p on load cycles, then RobustScaler across the numeric block, for the logistic baseline only. The log transform alone is worth 4 AUC points to the linear model. XGBoost skips both and scores the same.

Encoding categoricals​

Cardinality picks the encoder. Target encoding leaks by default unless it's out-of-fold.

EncoderUse whenPlant exampleResult
One-hotUp to ~15 unordered categoriesmachine_type → 3 columns✅
One-hotHundreds of categoriesmachine_model → 400 columns❌ 400 near-empty columns; 180 models have under 10 units
OrdinalA true order existssize_class S < M < L✅
OrdinalNo order existsmachine_model❌ Invents a ranking
Target encoding, out-of-foldHundreds of categoriesmachine_model → mean failure rate of its units✅ One dense column that captures "this model is a lemon"
Target encoding on all rows—A model with one failed unit encodes as 1.0❌ The label, laundered through a feature

sklearn's TargetEncoder (1.3+) encodes out-of-fold on fit_transform and smooths low-count categories toward the global mean. Set handle_unknown="ignore" on one-hot encoders. Production will send a machine model that didn't exist at training time.

The pipeline pattern​

Every step above learns something from data: the median, the scaler quantiles, the encoding table. Each must be learned from training data only, inside every CV fold (the rule from the supervised intro). A Pipeline with a ColumnTransformer makes that structural instead of manual.

Column groupSteps, in order
Numeric (load_cycles_30d, machine_age_days, oil_analysis_score)SimpleImputer(strategy="median", add_indicator=True) → log1p → RobustScaler
Low-cardinality (machine_type, duty_cycle)OneHotEncoder(handle_unknown="ignore")
High-cardinality (machine_model)TargetEncoder
ModelLogisticRegression(class_weight="balanced")

Cross-validating the whole pipeline refits every step inside each fold. The same object is what gets serialized for production, so nobody reimplements the preprocessing in serving code. That reimplementation is where training/serving skew starts.

Gotchas​

  • Imputing or scaling before the split. Validation rows contribute to the statistics. Fit every step inside the pipeline, inside the fold.
  • Trusting a convenient existing column. Dashboard and historian columns ignore the snapshot date. Rebuild features from raw events through the snapshot-filtered function.
  • Dropping rows with missing values. It deletes a segment, and the same gaps arrive at inference anyway. Impute and keep an indicator.
  • Target encoding on the full dataset. Each row's encoding contains its own label. Use out-of-fold encoding.
  • One-hot without handle_unknown="ignore". The first new machine model in production crashes the batch job.

Scenario questions​

Q1 ★★ Validation AUC was 0.99. One month in production it's 0.65. What happened?

Model answer
  • Clarify: is 0.99 plausible for this problem? Can the maintenance engineers predict failures that well?
  • Observe: feature importance shows avg_vibration_last_30d far ahead of everything else. Its lineage is a dashboard query computed at query time.
  • Hypothesise: the feature window crosses the snapshot date and sees post-breakdown zeros. Less likely: a real shift after launch, which would not explain 0.99.
  • Fix: rebuild the feature from raw sensor events, filtered to before the snapshot date, and retrain.
  • Prevent: one feature-building function with snapshot_date as an argument, used for every feature. The trade-off is giving up quick reuse of existing dashboard columns.

Q2 ★★ A teammate removes every row beyond 3σ before training. Is that OK?

Model answer
  • Clarify: which columns, and which model consumes them?
  • Observe: the rows removed are mostly 24/7 production lines in load_cycles_30d, and they're over-represented among failures.
  • Hypothesise: the "outliers" are real, and the most valuable machines in the plant.
  • Fix: keep the rows. Log-transform or winsorise for the linear baseline; do nothing for XGBoost. Fix only impossible values at the source.
  • Prevent: an outlier is treated only after it's classified as an error or as real. The trade-off is slower cleaning.

Q3 ★★ How would you encode machine_model, which has 400 values?

Model answer
  • Clarify: how many units per model, and will new models appear in production?
  • Observe: 180 of the 400 models have under 10 units.
  • Hypothesise: one-hot gives 400 sparse columns. Ordinal invents an order. Plain target encoding leaks each row's own label.
  • Fix: out-of-fold target encoding with smoothing, inside the pipeline.
  • Prevent: an unknown-category rule for models first seen in production. The trade-off is a less interpretable column.

Q4 ★★★ The scaler was fit on all the data before the split. The CV score looks fine. Does it matter?

Model answer
  • Clarify: which other steps were fit outside the folds?
  • Observe: refit inside a pipeline and compare. For the scaler alone the difference is usually small. For target encoding or imputation with indicators it can be large.
  • Hypothesise: the scaler is a minor leak. The real risk is the habit, because the next fitted step leaks more.
  • Fix: move every fitted step into one Pipeline and cross-validate the whole object.
  • Prevent: the pipeline is also the production artifact, so training and serving can't diverge. The trade-off is less freedom to poke at intermediate data in a notebook.

Summary​

  • The snapshot date is law. Every feature from before it, every label from after it, enforced in one function.
  • Missingness is signal. Diagnose why, impute the value, keep the flag.
  • Extreme is not wrong. The tail is usually your most critical equipment. Tame it, don't delete it.
  • Fit on train, always. Anything learned is learned inside the pipeline, inside the fold.
  • Audit miracles. An AUC that makes you smile is a leak until its lineage is traced.

Next → Feature Engineering & Selection