Level 3 — ProductionData Preprocessing & Feature Engineering

Data Preprocessing & Feature Engineering

45 minutes60 marksprintable — key stays hidden on paper

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 x=[2,4,4,4,5,5,7,9]x = [2, 4, 4, 4, 5, 5, 7, 9].

(a) Derive and compute the z-score standardization of the value x=9x=9, using the population standard deviation. Show mean, variance, std, and final z. (5)

(b) Derive and compute the min-max scaling of x=4x=4 into the range [0,1][0, 1], then into a general range [a,b][a, b] (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 [7,8,9,10,10,11,12,13,40][7, 8, 9, 10, 10, 11, 12, 13, 40]:

(a) Compute Q1Q_1, Q3Q_3, and the IQR. State the interpolation convention you use. (4)

(b) Compute the lower and upper Tukey fences (1.5×IQR1.5 \times \text{IQR} 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 [1,0,1,1][1, 0, 1, 1] and category B has [0,0,1][0, 0, 1]. 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 [1,10,100,1000][1, 10, 100, 1000].

(a) Apply the log10\log_{10} transform and give the transformed values. (3)

(b) Why does log\log 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 x=[1,2,3,4]x = [1, 2, 3, 4] and y=[2,4,6,8]y = [2, 4, 6, 8]. Show the covariance and standard deviations. (4)

(b) Define VIF (Variance Inflation Factor) and state the formula in terms of Ri2R_i^2. What VIF value corresponds to Ri2=0.9R_i^2 = 0.9? (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 μ=2+4+4+4+5+5+7+98=408=5\mu = \frac{2+4+4+4+5+5+7+9}{8} = \frac{40}{8} = 5. (1) Deviations squared: (25)2+3(45)2+2(55)2+(75)2+(95)2=9+3+0+4+16=32(2-5)^2+3(4-5)^2+2(5-5)^2+(7-5)^2+(9-5)^2 = 9+3+0+4+16 = 32. (1) Population variance σ2=32/8=4\sigma^2 = 32/8 = 4; σ=2\sigma = 2. (2) z=952=2z = \frac{9-5}{2} = 2. (1)

(b) xmin=2x_{\min}=2, xmax=9x_{\max}=9, range =7=7. For x=4x=4: 4292=270.2857\frac{4-2}{9-2} = \frac{2}{7} \approx 0.2857. (2) General range [a,b][a,b]: x=a+(ba)xxminxmaxxminx' = a + (b-a)\cdot\frac{x-x_{\min}}{x_{\max}-x_{\min}}. (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): [7,8,9,10,10,11,12,13,40][7,8,9,10,10,11,12,13,40]. Using linear interpolation (numpy default): Q1Q_1 at position 0.25(91)=20.25(9-1)=2 → index 2 → Q1=9Q_1 = 9. (2) Q3Q_3 at position 0.758=60.75\cdot8 = 6 → index 6 → Q3=12Q_3 = 12. IQR =129=3= 12-9 = 3. (2)

(b) Lower fence =91.5(3)=4.5= 9 - 1.5(3) = 4.5; Upper fence =12+1.5(3)=16.5= 12 + 1.5(3) = 16.5. (2) Points outside [4.5,16.5][4.5, 16.5]: 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+0+1+1)/4=0.75= (1+0+1+1)/4 = 0.75. (1.5) B: (0+0+1)/3=0.3333(0+0+1)/3 = 0.3333. (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 XX. (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) log10[1,10,100,1000]=[0,1,2,3]\log_{10}[1,10,100,1000] = [0, 1, 2, 3]. (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 log(x+1)\log(x+1) (i.e., log1p) to handle zeros: x=log(1+x)x' = \log(1+x). (2)


Q5 (10)

(a) Imbalance ratio 950:50=19:1950:50 = 19:1 (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)

  1. For each minority sample, find its kk nearest minority neighbours.
  2. Randomly pick one neighbour.
  3. Draw random λ[0,1]\lambda \in [0,1].
  4. Synthetic point =x+λ(xneighbourx)= x + \lambda\,(x_{\text{neighbour}} - x) (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) xˉ=2.5\bar x = 2.5, yˉ=5\bar y = 5. Deviations xx: [1.5,0.5,0.5,1.5][-1.5,-0.5,0.5,1.5], yy: [3,1,1,3][-3,-1,1,3]. Cov numerator =4.5+0.5+0.5+4.5=10= 4.5+0.5+0.5+4.5 = 10; cov=10/4=2.5\text{cov} = 10/4 = 2.5 (or /3 for sample). (2) σx=(2.25+0.25+0.25+2.25)/4=1.25\sigma_x = \sqrt{(2.25+0.25+0.25+2.25)/4} = \sqrt{1.25}, σy=20/4=5\sigma_y = \sqrt{20/4}=\sqrt5. r=2.51.255=2.52.5=1r = \frac{2.5}{\sqrt{1.25}\cdot\sqrt5} = \frac{2.5}{2.5} = 1. (2) (Perfect positive since y=2xy=2x.)

(b) VIFi=11Ri2\text{VIF}_i = \frac{1}{1-R_i^2}. (1) For Ri2=0.9R_i^2=0.9: VIF=1/0.1=10\text{VIF}=1/0.1 = 10. (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)"}
]