Chapter 7 — Lab: Understanding Your Data
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.
| Exercise | Topic | Points |
|---|---|---|
| 1 | The IQR fences and outlier flags | 15 |
| 2 | A missing-value report | 15 |
| 3 | Median imputation, learned on the training set | 15 |
| 4 | One-hot and ordinal encoding | 15 |
| 5 | Standardisation without leakage | 15 |
| 6 | Pearson and Spearman correlation | 25 |
| Challenge | A 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.
import numpy as np
import pandas as pd
from scipy.stats import pearsonr, spearmanr
def check(name, test):
"""Run one self-check: test() must return True; any exception or False is reported."""
try:
ok = test()
except NotImplementedError:
print(f'❌ {name}: not implemented yet'); return
except Exception as e:
print(f'❌ {name}: {type(e).__name__}: {e}'); return
print(f'✅ {name}' if ok else f'❌ {name}: wrong result')
print('Setup complete.')Exercise 1: The IQR Fences (15 points)¶
quartiles(values)returns(q1, q3), the 25th and 75th percentiles, with the same convention asnp.percentile(linear interpolation).iqr_fences(values, k=1.5)returns(low, high) = (q1 - k·IQR, q3 + k·IQR).flag_outliers(values, k=1.5)returns a list of booleans:Truewhere a value lies outside the fences.
def quartiles(values):
# TODO: the 25th and 75th percentiles
raise NotImplementedError
def iqr_fences(values, k=1.5):
# TODO: use quartiles()
raise NotImplementedError
def flag_outliers(values, k=1.5):
# TODO: True where a value is below low or above high
raise NotImplementedErrorareas = [63, 70, 72, 78, 80, 85, 92, 100, 104, 1090]
check('quartiles', lambda: np.allclose(quartiles(areas), (73.5, 98.0)))
check('fences', lambda: np.allclose(iqr_fences(areas), (36.75, 134.75)))
check('only the typo is flagged', lambda: flag_outliers(areas) == [False] * 9 + [True])
check('a wider k flags less', lambda: sum(flag_outliers([1, 2, 3, 4, 5, 6, 7, 8, 9, 20], k=3)) == 0)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.
def missing_report(df):
# TODO
raise NotImplementedErrortoy = pd.DataFrame({'a': [1, None, 3, 4], 'b': ['x', 'y', None, None], 'c': [1, 2, 3, 4]})
check('two columns with gaps', lambda: missing_report(toy) == {'a': (1, 25.0), 'b': (2, 50.0)})
check('no gaps, empty report', lambda: missing_report(toy[['c']]) == {})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.
def impute_median(train, test):
# TODO
raise NotImplementedErrortr, te = impute_median([1, None, 3, 10], [None, 1000, float('nan')])
check('the training median fills both', lambda: tr == [1, 3.0, 3, 10] and te == [3.0, 1000, 3.0])
check('test values never change the median', lambda: impute_median([2, 4], [None, 1e9, 1e9])[1][0] == 3.0)Exercise 4: One-Hot and Ordinal Encoding (15 points)¶
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.ordinal(values, order)returns the position of each value inorder(for['poor', 'fair', 'good']: poor → 0, fair → 1, good → 2).
def one_hot(values, categories):
# TODO
raise NotImplementedError
def ordinal(values, order):
# TODO
raise NotImplementedErrorcats = ['Centre', 'East', 'North', 'South']
check('one-hot', lambda: one_hot(['North', 'Centre'], cats).tolist() == [[0, 0, 1, 0], [1, 0, 0, 0]])
check('an unknown district is all zeros', lambda: one_hot(['Harbour'], cats).tolist() == [[0, 0, 0, 0]])
check('ordinal keeps the order', lambda: ordinal(['good', 'poor', 'excellent'], ['poor', 'fair', 'good', 'excellent']) == [2, 0, 3])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).
def standardise(train, test):
# TODO
raise NotImplementedErrorA = np.array([[1., 10.], [3., 10.], [5., 10.]]); B = np.array([[7., 20.]])
ta, tb = standardise(A, B)
check('training columns: mean 0', lambda: np.allclose(ta.mean(axis=0), 0))
check('test uses the training mean and sd', lambda: np.allclose(tb, [[(7 - 3) / np.std([1, 3, 5]), 10.0]]))
check('the test set does not change the scaling', lambda: np.allclose(standardise(A, B * 100)[0], ta))Exercise 6: Pearson and Spearman Correlation (25 points)¶
pearson(x, y)returns .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].spearman(x, y)ispearson(ranks(x), ranks(y)).
def pearson(x, y):
# TODO
raise NotImplementedError
def ranks(x):
# TODO: average ranks for ties
raise NotImplementedError
def spearman(x, y):
# TODO
raise NotImplementedErrorrng = np.random.default_rng(0); u = rng.normal(size=50); v = u ** 3 + rng.normal(scale=0.5, size=50)
check('pearson matches SciPy', lambda: abs(pearson(u, v) - pearsonr(u, v)[0]) < 1e-9)
check('ranks with ties', lambda: ranks([10, 20, 20, 30]) == [1, 2.5, 2.5, 4])
check('spearman matches SciPy', lambda: abs(spearman(u, v) - spearmanr(u, v)[0]) < 1e-9)
check('a monotonic curve has spearman 1', lambda: abs(spearman([1, 2, 3, 4], [1, 8, 27, 64]) - 1) < 1e-12)Question. Find a small dataset of 5 points where Pearson’s is negative but Spearman’s 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.
def suspicious_columns(df, target, threshold=0.99):
# TODO
raise NotImplementedErrorrng = np.random.default_rng(3)
area = rng.uniform(40, 150, 200); price = 3 * area * rng.lognormal(0, 0.2, 200)
leaky = pd.DataFrame({'area': area, 'floor': rng.integers(0, 10, 200), 'price': price,
'price_per_m2': price / area, 'price_eur': price * 1.08})
check('the two leaks are found', lambda: suspicious_columns(leaky, 'price') == {'direct': ['price_eur'], 'pairs': [('area', 'price_per_m2')]})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.