Defend a Tabular ML Project: Validation, Tuning, PCA, SHAP
Machine LearningModel answerLast updated
Walk through one supervised ML project end to end, covering leakage, time-aware validation, feature choices and tuning, then derive PCA and explain SHAP and its pitfalls.
Choose one supervised machine learning project on tabular data that you have built yourself, and present it as if you had to justify every decision to a skeptical reviewer. Assume a feature matrix X with n rows and p columns, a target y (continuous or binary), and train/validation/test splits (time-ordered if the data is temporal). Your explanation should work for both an ML-literate peer and a non-technical stakeholder.
Cover the following five areas.
-
Project framing. State the problem and business goal. Describe the data: size, schema, how and when the label is defined, the time span, and the main data-quality problems. Identify the leakage risks, describe your train/validation scheme (especially if the data is temporal), and name your primary metric(s) with the trade-offs they imply. Say which models you tried and why.
-
Feature decisions. Explain how you chose which features to keep or drop: domain reasoning versus automated selection, handling of missing values, outliers and scaling, high-cardinality categoricals, correlated features, prevention of target and time-based leakage, and how you checked that features stay useful over time.
-
Hyperparameter tuning. Name the hyperparameters that mattered most for your model, the search method and the metric you optimized, how you structured cross-validation (time-based or grouped where needed), how you used early stopping, how you avoided overfitting the validation set, and how you picked the final model.
-
PCA. Write the core optimization objective and its solution. Relate it to the covariance matrix and to the SVD, say what the components mean, explain how you would choose the number of components, and discuss when PCA helps or hurts in a supervised task.
-
SHAP. Explain what SHAP is and how it connects to Shapley values from cooperative game theory, including why it is considered "fair". State its key properties, explain how to read the summary (beeswarm), dependence and force plots, and list at least three pitfalls.
Hints
Hint 1
Pick a concrete project and fix the timeline first: when is the label known, when is each feature available, and do label windows overlap between adjacent rows? Most leakage questions follow from that.
Hint 2
For PCA, start from maximizing variance along a unit vector, write the Lagrangian, and you will land on an eigenvalue equation. Then substitute the SVD of the centered data to connect eigenvalues to singular values.
Hint 3
For SHAP, think of each feature as a player and the prediction as the payoff. Ask what happens to the attributions if features are correlated, or if you change the background (reference) dataset.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
What a strong answer demonstrates
The reviewer is looking for data discipline (leakage, point-in-time correctness, non-stationarity), metrics tied to the real decision, honest validation, and understanding of the math behind PCA and SHAP rather than just API usage. Use one project throughout and give each choice a rigorous explanation plus a one-line plain-language version.
1. Project framing (example)
Problem. Rank stocks weekly by the probability of beating their sector over the next 20 trading days; the ranking feeds a long-short portfolio. Plain version: "Each week we order stocks by how likely they are to beat their peers next month."
Data. About 3,000 equities over 13 years, sampled weekly: roughly 1.5M rows and ~150 features (price/volume, fundamentals, estimates, sentiment). The label is 1 if the 20-day forward sector-relative return is positive, computed only from prices after the as-of timestamp.
Quality issues and fixes. Survivorship bias (use a point-in-time universe including delisted names), restated fundamentals (use as-reported values with a reporting lag), stale prices and corporate actions.
Leakage risks. Fundamentals used before their filing date, overlapping 20-day labels in adjacent weeks, scalers fit on the full sample, survivorship.
Validation. Expanding-window walk-forward: train through year t, validate on t+1, with a purge/embargo gap of at least the label horizon (20 trading days). Keep the last two years as an untouched test set.
Metrics. Primary: mean per-date rank correlation (Spearman IC) between score and forward return, because the signal is used for within-date ranking. Secondary: AUC/log-loss (calibration matters if scores size positions), decile spread, and net-of-cost Sharpe. Trade-off: IC averages over the whole cross-section while a portfolio lives in the tails, and a high-IC, high-turnover model can lose money after costs.
Models. A regularized linear baseline (strong in low signal-to-noise data), gradient boosting (nonlinearity, native missing values), and a small MLP that was less stable and did not beat boosting out of sample.
2. Feature decisions
- Selection. Require an economic rationale first (guards against data mining), then prune automatically with permutation importance on validation folds, dropping features that do not help consistently.
- Scaling, outliers, missing values. Rank-normalize cross-sectionally per date; this tames outliers and removes market-wide level shifts. Let boosting handle NaNs natively; for linear models impute with the per-date median plus a missing flag, since missingness can carry signal.
- High-cardinality categoricals. Out-of-fold, time-respecting, smoothed target encoding, or collapse into a hierarchy (sector, industry).
- Correlated features. Cluster by Spearman correlation, keep one representative or average each cluster, compute importance per cluster (importance is split among correlated features), and use ridge for linear models.
- Leakage controls. An "available-at" timestamp on every feature with as-of joins; every encoder and scaler fit inside the training fold; audit any feature with suspiciously high IC.
- Stability. Per-year IC with consistent sign, population stability index for drift, and adversarial validation (a classifier separating train from test) to find features that mostly encode time. Drop unstable features even if pooled importance is high.
3. Hyperparameter tuning
- What mattered (LightGBM).
num_leaves,min_data_in_leaf, learning rate with number of trees, feature and bagging fractions, and L2 regularization. Complexity controls dominate in noisy data. - Search. Bayesian (TPE via Optuna), ~100 trials, optimizing mean fold IC minus a penalty on its standard deviation, so stable configurations win.
- CV. Purged walk-forward folds; for grouped data (e.g., users) use group-aware splits so a group never straddles train and validation.
- Early stopping. Use an inner slice from the end of each fold's training period, never the evaluation fold. Set final rounds to the median best iteration, scaled for the larger refit set.
- Avoiding validation overfit. Limited trial budget, prefer broad flat optima over the single best trial, hold out the final test period, average over seeds.
- Final model. Refit on everything before the test start and evaluate once.
4. PCA
Objective. With centered data X_c and covariance S = X_cᵀX_c/(n−1), the first component solves
max over w of wᵀSw subject to ‖w‖ = 1.
The Lagrangian gives Sw = λw: w is an eigenvector of S and the captured variance is λ. The top-k components are the eigenvectors with the k largest eigenvalues. Equivalently, PCA minimizes reconstruction error ‖X_c − X_c W Wᵀ‖²_F subject to WᵀW = I.
SVD link. With X_c = UΣVᵀ: S = VΣ²Vᵀ/(n−1), loadings are the columns of V, scores are X_c V = UΣ, and eigenvalues are σᵢ²/(n−1). The SVD is the numerically preferred way to compute PCA.
Meaning. Components are orthogonal directions of maximal variance with uncorrelated scores. Example: yield-curve changes decompose into level, slope and curvature.
How many to keep. Use cumulative explained variance (e.g., 90-95%), a scree-plot elbow, or, best for supervised work, treat k as a hyperparameter chosen by cross-validated downstream performance. Fit PCA inside each training fold, after standardizing features.
When it helps. Many collinear features, noise reduction, speeding up or stabilizing linear models, visualization.
When it hurts. Variance is not relevance: a low-variance direction may be the predictive one. Components are hard to interpret, results are scale-sensitive, PCA is linear, and fitting on all data leaks information. Tree models rarely benefit.
5. SHAP
Idea. Treat features as players in a cooperative game and the prediction as the payoff. The Shapley value of feature i is its average marginal contribution over all orderings (subsets) of the other features. SHAP estimates this for a model's prediction relative to a baseline (the expected prediction over a background dataset). TreeSHAP computes it exactly and efficiently for tree ensembles; KernelSHAP approximates it for any model.
Why "fair". Shapley values are the unique attribution satisfying:
- Local accuracy / additivity: baseline plus the sum of SHAP values equals the prediction.
- Consistency: if a model changes so a feature contributes more, its attribution does not decrease.
- Symmetry and dummy: identical features get equal credit; irrelevant ones get zero.
Plots.
- Beeswarm/summary: features ranked by mean |SHAP| (global importance); each point is a row, colored by feature value, showing direction and spread.
- Dependence plot: SHAP value versus feature value, with color by an interacting feature; reveals nonlinearity, thresholds and interactions.
- Force/waterfall: how each feature pushes one prediction from the baseline to its output.
Pitfalls.
- Correlated features: credit is split arbitrarily, and some methods evaluate unrealistic feature combinations (off-manifold).
- Association, not causation: SHAP explains the model, not the world; do not read it as an intervention effect.
- Background choice: attributions are relative to the reference data, so change the background and the values change.
- Model-space units: for classifiers, values are usually in log-odds, not probability.
- Instability and cost: estimates can be noisy for small samples or KernelSHAP, and importance on training data can reflect overfitting; compute it on held-out data.
- Explaining a bad model: a leaky feature will top the SHAP ranking, so use SHAP as a leakage audit too.
Common mistakes
Fitting scalers, encoders or PCA before splitting; random K-fold on temporal data; ignoring overlapping labels; tuning on the test set; equating high variance with predictive power; and presenting SHAP rankings as causal findings.