Preprocessing a Mixed Tabular Dataset Across Model Families
Machine LearningModel answerLast updated
Design leak-safe preprocessing for zero-heavy counts, skewed money, a binary flag and two collinear measurements, and compare choices for linear, tree and k-NN models.
You are building a supervised model on a table with these columns:
- A – a count variable, mostly small integers, with a large share of zeros. Some values are missing.
- B – a money amount in dollars with a heavy right tail.
- C – a binary flag (0/1).
- D and E – two continuous measurements that are very strongly correlated (|r| > 0.9).
- y – the target (assume binary classification; say what changes for regression).
Answer the following as you would in a technical screen:
- Scaling. State which columns need standardization or normalization, which scaler you would use for each, and why. Say what must be fit on training data only.
- The count column A. It has many zeros and missing entries. Describe your options (imputation, zero-inflated or hurdle-style handling, transformations) and how you would validate which one to use.
- Correlated D and E. Give three different strategies for selecting or transforming them (for example VIF-based dropping, an L1-type penalty, PCA). Explain how you would choose among them with cross-validation while keeping the model interpretable.
- Model families. For regularized linear/logistic models, tree ensembles and k-NN, say exactly how preprocessing should differ and why scale and correlation matter differently for each.
- Pipeline and evaluation. Outline a leak-safe, scikit-learn-style pipeline and a cross-validation plan to compare these choices. Include metrics, stratification, and how you would decide statistically whether one pipeline is really better than another.
Hints
Hint 1
Separate the questions 'does the model care about scale?' and 'does the model care about correlation?' for each model family; the answers differ for penalties, splits and distances.
Hint 2
A zero in A and a missing value in A mean different things. Think about encodings that keep both pieces of information (an indicator plus a transformed value) and treat each encoding as something to be compared under identical CV folds.
Hint 3
Anything learned from data (imputer medians, scaler statistics, PCA loadings, VIF-based drops) must be refit inside each fold, so put every step in a single Pipeline and cross-validate that. For comparing pipelines, use repeated stratified folds and look at paired differences rather than single scores.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
The goal is to match each preprocessing step to both the data and the model family, and to prove that a choice helps without leaking information. I assume binary y; for regression, swap in RMSE/MAE and use plain K-fold.
1. Scaling
| Column | Transform | Scaler | Reason |
|---|---|---|---|
| A (counts) | log1p | StandardScaler | Compresses the right tail; zero stays zero. |
| B (dollars) | log1p (signed log if negatives such as refunds exist) | StandardScaler, or RobustScaler if outliers persist after the log | A few huge values would otherwise dominate gradients and distances. |
| C (binary) | none | none (optionally standardize for penalized linear models) | Already bounded; scaling only changes how hard the penalty hits it. |
| D, E | none | StandardScaler | Comparable units matter for penalties, PCA and distances. |
Avoid MinMaxScaler on B: one extreme value squashes everything else near 0.
Leakage rule: every learned statistic (imputer medians, scaler means/SDs, PCA loadings, VIF decisions) is fit on the training fold only. Put all steps inside a Pipeline and cross-validate the pipeline; never call fit_transform on the full data before splitting.
2. The count column A
First separate two phenomena:
- Structural zero: the count really is 0. This is information.
- Missing: unknown. Compare the target rate for missing vs. observed rows. If missingness is related to
y, it is informative and must be preserved.
Candidate encodings:
- Median imputation + missing indicator. Cheap default.
- Hurdle encoding. Build
is_zero = 1[A == 0]andlog1p(A), so the model learns "any vs. none" separately from "how many". This is the feature-side analogue of a zero-inflated model. A true zero-inflated Poisson is only natural if A were the target or if you fit it to impute A. - Model-based imputation (e.g. iterative imputer on B–E). Worth it only if A is well predicted by other columns.
- Bucketing (0, 1, 2–5, 6+). Robust and interpretable for linear models.
Never fill with 0 without an indicator: it merges "unknown" with "none".
Validation: plug each encoding into the same pipeline, evaluate on identical repeated stratified folds, and choose the best mean score, or the simplest option within one standard error of it. Also check calibration and the metric on the rows where A was missing.
3. Correlated D and E
- VIF / domain-based dropping. With r = 0.9, VIF ≈ 1/(1 − 0.81) ≈ 5.3. Compute it on the training fold, drop one if VIF exceeds roughly 5–10, and keep the cheaper or more meaningful measurement. Most interpretable.
- PCA on {D, E} only. After standardizing, PC1 ≈ (zD + zE)/√2 is the shared "level" and PC2 ≈ (zD − zE)/√2 is their "disagreement". Both have clear meanings. PCA over all features would destroy interpretability.
- Penalized selection. Lasso tends to pick one of the pair arbitrarily and flips between folds. Elastic net (l1_ratio around 0.5) spreads weight across the group and is more stable. Measure stability by how often each coefficient is nonzero across folds or bootstraps.
Choosing: treat the strategy as a hyperparameter, score all three under the same CV, apply the one-standard-error rule, and break ties by interpretability and coefficient stability. Collinearity mainly harms coefficient variance and interpretation, not predictive accuracy, so scores will often be similar and interpretability becomes the tiebreaker.
4. Differences by model family
| Regularized linear/logistic | Tree ensembles | k-NN | |
|---|---|---|---|
| Scaling | Required; penalty is scale-dependent | Not needed; splits are invariant to monotone transforms | Critical; large-scale features dominate distance |
| log on A/B | Linearizes, reduces leverage | Irrelevant to splits | Helps; outliers distort neighborhoods |
| Missing A | Impute + indicator | Native NaN support in histogram GBMs; indicator optional | Impute + indicator (distances can't use NaN) |
| D/E correlation | Inflates coefficient variance; use drop, PCA or elastic net (ridge already stabilizes predictions) | Accuracy barely changes; importance is split between them, so use grouped permutation importance or SHAP | The shared direction is effectively double-weighted; drop one or use PC1 |
| Binary C | Pass through | Pass through | Its weight vs. scaled continuous columns matters; scale consistently or tune |
5. Pipeline and CV plan
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, FunctionTransformer
from sklearn.impute import SimpleImputer
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import RepeatedStratifiedKFold, cross_validate
def hurdle(Z):
v, miss = Z[:, [0]], Z[:, [1]]
return np.hstack([np.log1p(v), (v == 0).astype(float), miss])
a_pipe = Pipeline([
("imp", SimpleImputer(strategy="median", add_indicator=True)),
("hurdle", FunctionTransformer(hurdle)),
("sc", StandardScaler()),
])
b_pipe = Pipeline([("log", FunctionTransformer(np.log1p)), ("sc", StandardScaler())])
de_pipe = Pipeline([("sc", StandardScaler()), ("pca", PCA(n_components=1))])
prep = ColumnTransformer([
("A", a_pipe, ["A"]),
("B", b_pipe, ["B"]),
("C", "passthrough", ["C"]),
("DE", de_pipe, ["D", "E"]),
])
model = Pipeline([("prep", prep),
("clf", LogisticRegression(penalty="elasticnet", solver="saga",
l1_ratio=0.5, max_iter=5000))])
cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=5, random_state=0)
res = cross_validate(model, X, y, cv=cv, scoring=["roc_auc", "average_precision", "neg_log_loss"])
For trees, drop the scalers and let a histogram GBM handle NaN; for k-NN, keep scaling and the imputer and tune k.
Plan details:
- Stratification on
y(and on the A-missing flag if it is rare) so every fold has comparable class balance. - Metrics: ROC-AUC and PR-AUC for ranking, log loss and a calibration curve for probability quality; choose the headline metric from the business cost, and use PR-AUC when positives are rare.
- Tuning (C, l1_ratio, k, tree depth, preprocessing variants) happens in a nested CV, or at least inside the inner loop, so the outer score is unbiased.
- Comparing pipelines: use the same folds for all candidates and examine paired per-fold differences. Because repeated-CV folds overlap, a naive paired t-test is overconfident; use the corrected resampled t-test (Nadeau–Bengio), or a bootstrap confidence interval on the paired difference. Prefer the simpler pipeline unless the gain exceeds about one standard error.
- Final check: a holdout, ideally time-based if data drifts, scored once.
Common mistakes
- Fitting scalers, imputers or PCA on the full dataset before splitting.
- Imputing A with 0 and no indicator.
- Using MinMax scaling on heavy-tailed dollars.
- Scaling for trees (harmless but unnecessary) while forgetting to scale for k-NN or penalized models.
- Reading lasso's arbitrary pick between D and E as evidence that one is "more important".
- Declaring a winner from a 0.002 AUC difference on a single split.