Data Preprocessing & Feature Engineering
Level: 3 (Production — from-scratch derivations, code-from-memory, explain-out-loud) Time limit: 45 minutes Total marks: 60
Instructions: Show all working. Where code is asked, write it from memory (NumPy/pandas/sklearn-style pseudocode accepted if consistent). Round numerical answers to 4 decimal places unless stated.
Q1 — Scaling from scratch (12 marks)
You are given the feature vector .
(a) Derive and compute the z-score standardization of the value , using the population standard deviation. Show mean, variance, std, and final z. (5)
(b) Derive and compute the min-max scaling of into the range , then into a general range (give the formula). (4)
(c) Explain out loud (2–3 sentences): why must the scaler's parameters (mean/std or min/max) be fit on the training set only and then applied to validation/test? Name the failure this prevents. (3)
Q2 — Outlier detection by IQR (10 marks)
For the dataset :
(a) Compute , , and the IQR. State the interpolation convention you use. (4)
(b) Compute the lower and upper Tukey fences ( rule) and list which points are flagged as outliers. (4)
(c) Give one situation where you should not delete a detected outlier. (2)
Q3 — Encoding & target encoding leakage (12 marks)
(a) Given the categorical column color = [red, green, blue, green, red], write the one-hot encoded matrix (drop-first NOT applied). State how many columns and why drop-first is sometimes used. (4)
(b) You use target (mean) encoding on a binary target. Category A has targets and category B has . Compute the naive mean encoding for each category. (3)
(c) Explain out loud why naive target encoding leaks, and describe one concrete technique to prevent it. (3)
(d) When would you prefer label/ordinal encoding over one-hot? Give one case. (2)
Q4 — Log transform & skew (8 marks)
A right-skewed monetary feature has values .
(a) Apply the transform and give the transformed values. (3)
(b) Why does reduce right skew and stabilize variance? Explain the intuition. (3)
(c) The feature contains some zeros. State the standard fix and write the transform formula. (2)
Q5 — Imbalanced data & SMOTE (10 marks)
A binary dataset has 950 negatives and 50 positives.
(a) State the imbalance ratio and one reason accuracy is misleading here. (2)
(b) Describe the SMOTE algorithm in steps (how a synthetic minority sample is created). (4)
(c) Critical ordering question: in a train/val/test pipeline, should SMOTE be applied before or after the split, and to which partition(s)? Justify. (4)
Q6 — Correlation & multicollinearity (8 marks)
(a) Compute the Pearson correlation between and . Show the covariance and standard deviations. (4)
(b) Define VIF (Variance Inflation Factor) and state the formula in terms of . What VIF value corresponds to ? (2)
(c) Name one consequence of high multicollinearity for a linear regression model and one remedy. (2)
Answer keyMark scheme & solutions
Q1 (12)
(a) Mean . (1) Deviations squared: . (1) Population variance ; . (2) . (1)
(b) , , range . For : . (2) General range : . (2)
(c) Fit on train only, transform val/test with those stored params. (1) If you fit using the whole dataset, statistics of val/test leak into the transform → data leakage, giving optimistically biased performance estimates. (2)
Q2 (10)
(a) Sorted (n=9): . Using linear interpolation (numpy default): at position → index 2 → . (2) at position → index 6 → . IQR . (2)
(b) Lower fence ; Upper fence . (2) Points outside : only 40 is an outlier. (2)
(c) When the outlier is a genuine/valid extreme value carrying real signal (e.g., fraud, rare disease, sensor spike of interest) — deleting it loses information. (2)
Q3 (12)
(a) One-hot (columns blue, green, red order or any consistent order):
| red | green | blue |
|---|---|---|
| 1 | 0 | 0 |
| 0 | 1 | 0 |
| 0 | 0 | 1 |
| 0 | 1 | 0 |
| 1 | 0 | 0 |
3 columns. (3) Drop-first is used to avoid the dummy variable trap / perfect multicollinearity (one column is redundant given the intercept). (1)
(b) A: mean. (1.5) B: . (1.5)
(c) Naive encoding uses each row's own target to build the feature → the target directly informs the feature, leaking label information into . (1.5) Prevention (any one): out-of-fold/K-fold target encoding, leave-one-out encoding, or smoothing with the global mean + adding noise. (1.5)
(d) When cardinality is very high (one-hot explodes dimensionality) or the categories have a genuine order (ordinal), or for tree-based models that handle integer splits well. (2)
Q4 (8)
(a) . (3)
(b) Log compresses large values more than small ones (multiplicative → additive spacing), pulling in the long right tail so the distribution becomes more symmetric and variance more constant across the range. (3)
(c) Use (i.e., log1p) to handle zeros: . (2)
Q5 (10)
(a) Imbalance ratio (5% positives). (1) A model predicting all-negative gets 95% accuracy while catching zero positives → accuracy hides failure on the minority class. (1)
(b) SMOTE steps: (4, 1 each)
- For each minority sample, find its nearest minority neighbours.
- Randomly pick one neighbour.
- Draw random .
- Synthetic point (interpolate along the line segment). Repeat to reach target count.
(c) Apply SMOTE after the split, on the training set only. (2) If applied before splitting, synthetic points generated from test/val neighbours (or duplicates thereof) leak into training → inflated, invalid evaluation. Val/test must reflect the true class distribution. (2)
Q6 (8)
(a) , . Deviations : , : . Cov numerator ; (or /3 for sample). (2) , . . (2) (Perfect positive since .)
(b) . (1) For : . (1)
(c) Consequence: unstable/inflated coefficient variances → unreliable coefficient estimates & signs. (1) Remedy: drop one collinear feature, use PCA, or apply regularization (ridge). (1)
[
{"claim":"Z-score of x=9 with pop std is 2","code":"x=[2,4,4,4,5,5,7,9]; mu=sum(x)/len(x); var=sum((v-mu)**2 for v in x)/len(x); z=(9-mu)/sqrt(var); result=(z==2)"},
{"claim":"Min-max of x=4 in [0,1] is 2/7","code":"val=(4-2)/(9-2); result=simplify(val-Rational(2,7))==0"},
{"claim":"IQR Tukey upper fence flags only 40","code":"import numpy as np; d=np.array([7,8,9,10,10,11,12,13,40]); q1=np.percentile(d,25); q3=np.percentile(d,75); iqr=q3-q1; up=q3+1.5*iqr; lo=q1-1.5*iqr; out=[v for v in d if v>up or v<lo]; result=(out==[40])"},
{"claim":"Pearson r of x and y=2x is 1","code":"import numpy as np; x=np.array([1,2,3,4.]); y=np.array([2,4,6,8.]); r=np.corrcoef(x,y)[0,1]; result=bool(abs(r-1)<1e-9)"},
{"claim":"VIF at R2=0.9 equals 10","code":"vif=1/(1-Rational(9,10)); result=(vif==10)"}
]