Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 7 — Lab: Understanding Your Data

Open in Colab

Lab Overview

You will write, from scratch, the small tools that a data scientist uses before training any model, and you will learn why each one must be fitted on the training data only.

ExerciseTopicPoints
1The IQR fences and outlier flags15
2A missing-value report15
3Median imputation, learned on the training set15
4One-hot and ordinal encoding15
5Standardisation without leakage15
6Pearson and Spearman correlation25
ChallengeA leak detector+10

How it works. Each exercise has a function to complete where you see # TODO. Run the check cell under it: ✅ means your function is right, ❌ tells you what is wrong. Use NumPy and plain Python; pandas and SciPy are used only by the checks. Do not change the check cells.


Exercise 1: The IQR Fences (15 points)

  1. quartiles(values) returns (q1, q3), the 25th and 75th percentiles, with the same convention as np.percentile (linear interpolation).

  2. iqr_fences(values, k=1.5) returns (low, high) = (q1 - k·IQR, q3 + k·IQR).

  3. flag_outliers(values, k=1.5) returns a list of booleans: True where a value lies outside the fences.


Exercise 2: A Missing-Value Report (15 points)

missing_report(df) returns a dictionary {column: (count, percent)} for the columns that have at least one missing value, where percent is rounded to one decimal. Columns with no gap are left out.


Exercise 3: Median Imputation, Learned on the Training Set (15 points)

impute_median(train, test) takes two lists of numbers where missing values are None or nan. It computes the median of the training values that are present, and returns two new lists with every gap filled by that median. The test set’s own values must play no part.


Exercise 4: One-Hot and Ordinal Encoding (15 points)

  1. one_hot(values, categories) returns a NumPy array of shape (len(values), len(categories)) with a 1 in the column of each value’s category. An unknown value gets a row of zeros.

  2. ordinal(values, order) returns the position of each value in order (for ['poor', 'fair', 'good']: poor → 0, fair → 1, good → 2).


Exercise 5: Standardisation Without Leakage (15 points)

standardise(train, test) takes two 2-D arrays (rows are examples, columns features). It computes the mean and the standard deviation (ddof=0) of each column of the training array, and returns both arrays transformed with them. A column with a standard deviation of 0 is only centred (divide by 1).


Exercise 6: Pearson and Spearman Correlation (25 points)

  1. pearson(x, y) returns r=∑(xi−xˉ)(yi−yˉ)∑(xi−xˉ)2∑(yi−yˉ)2r = \dfrac{\sum (x_i - \bar{x})(y_i - \bar{y})}{\sqrt{\sum (x_i - \bar{x})^2}\sqrt{\sum (y_i - \bar{y})^2}}.

  2. ranks(x) returns the rank of each value, starting at 1. Tied values share the average of their ranks: the ranks of [10, 20, 20, 30] are [1, 2.5, 2.5, 4].

  3. spearman(x, y) is pearson(ranks(x), ranks(y)).

Question. Find a small dataset of 5 points where Pearson’s rr is negative but Spearman’s ρ\rho is positive. What does it tell you about relying on one number?


Challenge: A Leak Detector (+10 points)

suspicious_columns(df, target, threshold=0.99) looks for two kinds of leak among the numerical columns other than the target:

  • direct: a column whose absolute Pearson correlation with the target is above threshold (the target in another unit, say);

  • pairs: two columns, neither of them direct, whose product has an absolute correlation with the target above threshold (a price per square metre and an area multiply back to the price).

Return a dictionary {'direct': [...], 'pairs': [...]}: the direct names sorted, the pairs as sorted tuples in sorted order.

Question. The detector reports the pair ('area', 'price_per_m2'), not which of the two is the leak. Which one is it, and why can no code that only sees the numbers decide?


Lab Report

Submit this notebook with:

  • every check cell showing ✅,

  • your answer to the question of Exercise 6,

  • one paragraph: describe a real dataset you know (from work, a course or the news) and one leak it could contain.