Data Preprocessing & Feature Engineering
Level 5 — Mastery (cross-domain: math + statistics + coding + proof) Time limit: 90 minutes Total marks: 60
Instructions: Answer all three questions. Show derivations, justify every modeling choice, and state assumptions. Code may be written in Python (NumPy/pandas/scikit-learn style pseudocode acceptable if correct).
Question 1 — Scaling, Leakage, and the Pipeline Contract (20 marks)
A dataset has a single feature . You split into train and test sets and apply z-score standardization.
(a) Prove that after standardization using the training statistics , the transformed training feature has sample mean and (population) variance . Show the algebra. (4 marks)
(b) A colleague computes over the entire dataset (train + test combined) before splitting. Explain precisely why this constitutes data leakage, and quantify it: given training values and test values , compute the train feature's standardized mean under the correct (train-only) procedure versus the leaky (full-data) procedure. (6 marks)
(c) Min-max scaling maps . Prove that min-max scaling and z-score standardization are related by an affine transformation on any fixed dataset, i.e. find constants such that where is the min-max value and the z-score of point . Express in terms of range , , and . (6 marks)
(d) State one concrete scenario where min-max scaling is preferable to standardization, and one where it is dangerous. (4 marks)
Question 2 — Outliers, Transformations, and Distributional Reasoning (20 marks)
Consider positive-valued feature data that is right-skewed.
(a) For the sample , compute , , the IQR, and the Tukey upper fence . Identify which points are flagged as outliers. Use linear interpolation quartiles (positions and ). (6 marks)
(b) Apply a transform to the value and to the median. Argue mathematically (using the derivative of ) why log transforms compress large values more than small values, and hence reduce right-skew and outlier influence. (6 marks)
(c) The Box–Cox transform is for . Prove that , justifying why is the continuous case. (4 marks)
(d) Write correct pseudocode that: fits the outlier fences and log-transform parameters on the training set only, then applies them to a held-out set — and explain the leakage risk if done otherwise. (4 marks)
Question 3 — Encoding, Imbalance, and Correlation (20 marks)
A classification dataset has a categorical feature city (4 levels), a binary target y, and class imbalance (positive rate 5%).
(a) Contrast one-hot encoding vs target (mean) encoding for city. Derive the target-encoded value for a city with 3 samples having targets using additive (Laplace) smoothing with prior = global mean and smoothing weight : . (6 marks)
(b) Explain the leakage mechanism in naive target encoding and how out-of-fold / smoothed encoding mitigates it. (4 marks)
(c) SMOTE generates a synthetic minority point as , . Given minority points and nearest neighbor with , compute . Prove that every SMOTE point lies on the segment between the two points and state one risk of SMOTE with respect to outliers. (6 marks)
(d) Two features have Pearson correlation . Compute the Variance Inflation Factor (with for the two-feature case) and interpret whether multicollinearity is a concern. (4 marks)
Answer keyMark scheme & solutions
Question 1
(a) [4 marks] Standardized value . Mean: . (2) Variance: . (2)
(b) [6 marks] Leakage: test-set information (its mean/spread) influences the training transform; the model implicitly "sees" future data, inflating optimism and breaking the independence of the test set. (2)
Correct (train-only): , , . Standardized train mean by part (a). (2)
Leaky (full data, 6 points): . Train standardized mean . Train raw mean , so numerator mean ; . Var, . Leaky train mean . (2) → Correct gives ; leaky gives , showing distortion.
(c) [6 marks] , . Solve ; substitute: . So , — an affine map. (6) (4 for form, 2 for correct constants)
(d) [4 marks] Preferable: bounded-input requirements, e.g. image pixel intensities to , or neural nets with sigmoid activations / distance metrics needing fixed range. (2) Dangerous: presence of outliers — a single extreme compresses all other values into a tiny sub-interval, destroying resolution; standardization (or robust scaling) is safer. (2)
Question 2
(a) [6 marks] Sorted: , . position → between 2nd(2) and 3rd(2): . (2) position → between 8th(5) and 9th(8): . (2) IQR ; upper fence . (1) Outlier: ⇒ flagged (only 27). (1)
(b) [6 marks] ; median (avg of 5th,6th ) , . (2) Raw gap 27 vs 3 = 24; log gap — hugely compressed. (1) Since , the transform's slope decreases as grows; large get mapped with smaller local stretch, so wide right-tail spacing collapses, reducing skew and outlier leverage. (3)
(c) [4 marks] : indeterminate . Write . Either L'Hôpital w.r.t. : , denominator derivative , limit . (4) (2 for method, 2 for result)
(d) [4 marks]
# TRAIN ONLY
q1, q3 = np.percentile(X_train, [25,75])
iqr = q3 - q1
upper = q3 + 1.5*iqr # fences fit on train
# choose lambda / use log; store shift if needed
X_train_t = np.log(X_train + eps)
# APPLY to test using SAME fences/transform
X_test_clipped = np.clip(X_test, None, upper)
X_test_t = np.log(X_test_clipped + eps)Leakage risk: fitting fences/transform params on test (or full) data lets test distribution influence preprocessing, biasing evaluation optimistically. (2 code, 2 explanation)
Question 3
(a) [6 marks] One-hot: 4 binary columns, no ordinal assumption, no target leakage, but high dimensionality/sparsity for many levels. Target encoding: single column = per-category target mean, compact and captures signal, but risks leakage/overfit on rare levels. (2) Smoothed encode: , , , . . (4)
(b) [4 marks] Naive encoding uses the target of a row to build that row's feature → direct target leakage inflating training performance and overfitting rare categories. Out-of-fold encoding (compute a fold's encoding from other folds) and smoothing toward the global prior break the self-reference, shrinking unreliable small- estimates. (4)
(c) [6 marks] . (3) Proof: is a convex combination with , hence lies on the line segment between the two points. (2) Risk: if or is an outlier/noisy minority point, SMOTE interpolates into unrealistic regions, amplifying noise and blurring class boundaries. (1)
(d) [4 marks] ; . (2) VIF ⇒ severe multicollinearity; the two features are nearly redundant → unstable coefficient estimates; drop one or combine (PCA/regularization). (2)
[
{"claim":"Leaky train standardized mean approx -0.706","code":"xs=[2,4,6,8,100,102]; mu=sum(xs)/len(xs); var=sum((x-mu)**2 for x in xs)/len(xs); sig=sqrt(var); train=[2,4,6,8]; m=sum((x-mu)/sig for x in train)/len(train); result=abs(float(m)-(-0.706))<0.01"},
{"claim":"Tukey upper fence = 11.375 and 27 is the only outlier","code":"Q1=2; Q3=Rational(575,100); iqr=Q3-Q1; fence=Q3+Rational(3,2)*iqr; data=[1,2,2,3,3,3,4,5,8,27]; outs=[x for x in data if x>fence]; result=(fence==Rational(11375,1000)) and outs==[27]"},
{"claim":"Box-Cox limit equals ln x","code":"lam,x=symbols('lam x',positive=True); result=limit((x**lam-1)/lam,lam,0)==log(x)"},
{"claim":"Smoothed target encoding approx 0.1923","code":"e=(3*Rational(2,3)+10*Rational(5,100))/(3+10); result=abs(float(e)-0.1923)<0.001"},
{"claim":"VIF approx 25.25 for r=0.98","code":"r=Rational(98,100); R2=r**2; vif=1/(1-R2); result=abs(float(vif)-25.2525)<0.01"},
{"claim":"SMOTE point is (1.5,3)","code":"xi=Matrix([1,2]); xnn=Matrix([3,6]); d=Rational(1,4); xnew=xi+d*(xnn-xi); result=xnew==Matrix([Rational(3,2),3])"}
]