Chapter 7: Understanding Your Data — Implementation
This notebook turns the chapter’s checklist into code you can reuse on any table:
A first look in one function
Outliers: the IQR rule and a robust z-score
Missing values: what each imputer does to the data
Relationships: Pearson against Spearman
A preparation pipeline with
ColumnTransformerTwo leaks measured: feature selection before cross-validation, and the same patient on both sides
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer
def make_apartments(n=600, seed=7):
"""The chapter's dataset (see the theory page): listings with their sale price, problems included on purpose."""
rng = np.random.default_rng(seed)
district = rng.choice(['Centre', 'North', 'South', 'East'], size=n, p=[0.25, 0.30, 0.25, 0.20])
area = np.round(np.exp(rng.normal(np.log(80), 0.35, n)), 0)
rooms = np.clip(np.round(area / 28 + rng.normal(0, 0.6, n)), 1, 7).astype(int)
floor = rng.integers(0, 16, n)
year = rng.integers(1950, 2024, n)
condition = rng.choice(['poor', 'fair', 'good', 'excellent'], size=n, p=[0.15, 0.35, 0.35, 0.15])
parking = rng.random(n) < 0.45
base = pd.Series(district).map({'Centre': 4.2, 'North': 2.9, 'South': 2.6, 'East': 2.2}).to_numpy()
cond = pd.Series(condition).map({'poor': 0.80, 'fair': 0.95, 'good': 1.05, 'excellent': 1.25}).to_numpy()
price = base * area * cond * (1 - 0.003 * (2024 - year)) * (1 + 0.08 * parking) * np.exp(rng.normal(0, 0.12, n))
df = pd.DataFrame({'listing_id': [f'L{i:04d}' for i in range(1, n + 1)], 'district': district, 'area_m2': area,
'rooms': rooms, 'floor': floor, 'year_built': year.astype(float), 'condition': condition,
'parking': np.where(parking, 'yes', 'no'),
'listed': pd.Timestamp('2022-01-01') + pd.to_timedelta(np.sort(rng.integers(0, 730, n)), unit='D'),
'price_k': np.round(price, 1)})
df['price_per_m2'] = np.round(df['price_k'] * 1000 / df['area_m2'], 0)
for i in rng.choice(n, 3, replace=False):
df.loc[i, 'area_m2'] *= 10
old = df['year_built'] < 1975
df.loc[old & (rng.random(n) < 0.30), 'year_built'] = np.nan
df.loc[rng.choice(n, 12, replace=False), 'parking'] = None
return pd.concat([df, df.sample(5, random_state=seed)], ignore_index=True)
apartments = make_apartments()
print(apartments.shape)(605, 11)
1. A First Look in One Function¶
first_look gathers, for every column, what the checklist asks: its type, how many values are missing, how many distinct values it has, and an example. A column with as many distinct values as rows is probably an identifier; a column with one distinct value carries no information.
def first_look(df):
"""One row per column: type, missing count and share, distinct values, an example; plus the duplicate count."""
rows = []
for col in df.columns:
s = df[col]
rows.append({'column': col, 'type': str(s.dtype), 'missing': int(s.isna().sum()),
'missing_%': round(100 * s.isna().mean(), 1), 'distinct': int(s.nunique()),
'example': s.dropna().iloc[0] if s.notna().any() else None})
profile = pd.DataFrame(rows).set_index('column')
profile['hint'] = np.select([profile['distinct'] == len(df), profile['distinct'] <= 1, profile['missing_%'] > 50],
['identifier?', 'constant', 'mostly missing'], '')
print(f'{len(df)} rows, {df.shape[1]} columns, {df.duplicated().sum()} duplicated rows')
return profile
first_look(apartments)605 rows, 11 columns, 5 duplicated rows
The profile flags listing_id as an identifier and finds the five duplicates. price_per_m2 is not flagged: no rule can tell that a column is computed from the target. Only knowing what each column means can.
2. Outliers: the IQR Rule and a Robust z-score¶
The ordinary z-score uses the mean and the standard deviation, which the outliers themselves inflate. A robust z-score replaces them by the median and the median absolute deviation (MAD), which a few extreme values cannot move: , flagged when .
def iqr_flags(s, k=1.5):
q1, q3 = s.quantile([0.25, 0.75])
return (s < q1 - k * (q3 - q1)) | (s > q3 + k * (q3 - q1))
def robust_z(s):
med = s.median(); mad = (s - med).abs().median()
return 0.6745 * (s - med) / mad
def plain_z(s):
return (s - s.mean()) / s.std()
area = apartments['area_m2']
print('IQR rule: ', iqr_flags(area).sum(), 'flagged')
print('plain z > 3: ', (plain_z(area).abs() > 3).sum(), 'flagged')
print('robust z > 3.5: ', (robust_z(area).abs() > 3.5).sum(), 'flagged')
print('the plain z-score of the 1 090 m² typo:', round(plain_z(area).max(), 1),
'; its robust z-score:', round(robust_z(area).max(), 1))IQR rule: 25 flagged
plain z > 3: 3 flagged
robust z > 3.5: 16 flagged
the plain z-score of the 1 090 m² typo: 16.1 ; its robust z-score: 40.2
The plain z-score flags only the three typos: they inflate the standard deviation so much that the genuinely large apartments look normal. The robust z-score and the IQR rule both see the typos and the long tail; only domain knowledge separates them (Section 7.4).
3. Missing Values: What Each Imputer Does¶
We hide 30% of a column on purpose, in two ways, and fill it in three ways. Because we hid the values ourselves, we can measure the error of each method.
MCAR: 30% of the areas, chosen at random.
MNAR: the 30% smallest areas (small flats whose owners left the field blank).
from sklearn.impute import SimpleImputer, KNNImputer
clean = apartments.drop_duplicates().query('area_m2 < 400')[['area_m2', 'rooms', 'price_k']].reset_index(drop=True)
rng = np.random.default_rng(0)
patterns = {'MCAR': rng.random(len(clean)) < 0.30,
'MNAR': clean['area_m2'] < clean['area_m2'].quantile(0.30)}
results = []
for pattern, hide in patterns.items():
holed = clean.copy(); holed.loc[hide, 'area_m2'] = np.nan
for name, imp in [('mean', SimpleImputer(strategy='mean')), ('median', SimpleImputer(strategy='median')),
('5 nearest neighbours', KNNImputer(n_neighbors=5))]:
filled = imp.fit_transform(holed)[:, 0]
err = np.abs(filled[hide] - clean.loc[hide, 'area_m2']).mean()
bias = filled.mean() - clean['area_m2'].mean()
results.append({'pattern': pattern, 'imputer': name, 'mean abs error (m²)': round(err, 1), 'bias of the mean (m²)': round(bias, 1)})
pd.DataFrame(results)Two lessons:
k-nearest-neighbours imputation uses the other columns (rooms, price) to guess the area, and is far more accurate than a single number for everyone.
Under MNAR, the mean and the median of the observed values are too high (the small flats are exactly the ones missing), so filling with them biases the column. KNN helps because rooms and price still reveal that the flat is small. When the pattern is MNAR, add a missing-indicator column as well.
4. Relationships: Pearson Against Spearman¶
Pearson’s measures straight-line association; Spearman’s measures any monotonic association. They disagree in two situations: a curved but monotonic relation, and an outlier.
from scipy.stats import pearsonr, spearmanr
x = np.linspace(1, 10, 50)
cases = {'straight line': (x, 2 * x + 1), 'exponential curve': (x, np.exp(x)),
'line plus one outlier': (np.append(x, 30), np.append(2 * x + 1, -60))}
for name, (a, b) in cases.items():
print(f'{name:22s} Pearson {pearsonr(a, b)[0]:+.2f} Spearman {spearmanr(a, b)[0]:+.2f}')straight line Pearson +1.00 Spearman +1.00
exponential curve Pearson +0.72 Spearman +1.00
line plus one outlier Pearson -0.42 Spearman +0.88
On the exponential curve, (the relation never falls) while is lower; one outlier turns a perfect Pearson correlation negative, but barely moves Spearman’s.
On real data, a correlation heatmap shows redundant features at a glance. The breast-cancer dataset that ships with scikit-learn measures 30 properties of cell nuclei:
Source
cancer = load_breast_cancer(as_frame=True)
corr = cancer.data.iloc[:, :10].corr()
fig, ax = plt.subplots(figsize=(7, 5.5))
im = ax.imshow(corr, cmap='coolwarm', vmin=-1, vmax=1)
ax.set_xticks(range(10)); ax.set_xticklabels(corr.columns, rotation=60, ha='right', fontsize=8)
ax.set_yticks(range(10)); ax.set_yticklabels(corr.columns, fontsize=8)
fig.colorbar(im, shrink=0.8); ax.set_title('Correlations of the first 10 features')
plt.tight_layout(); plt.show()
print('radius and perimeter: r =', round(cancer.data['mean radius'].corr(cancer.data['mean perimeter']), 3))
radius and perimeter: r = 0.998
Radius, perimeter and area are almost perfectly correlated: they measure the same size three times (perimeter = 2πr; area = πr²). For prediction this redundancy is harmless; for interpreting a linear model’s coefficients it is not.
5. A Preparation Pipeline¶
ColumnTransformer sends each group of columns through its own steps, and get_feature_names_out tells us what the model will receive.
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler, OneHotEncoder, OrdinalEncoder
prepare = ColumnTransformer([
('num', make_pipeline(SimpleImputer(strategy='median', add_indicator=True), StandardScaler()), ['area_m2', 'rooms', 'floor', 'year_built']),
('nom', make_pipeline(SimpleImputer(strategy='most_frequent'), OneHotEncoder(handle_unknown='ignore')), ['district', 'parking']),
('ord', OrdinalEncoder(categories=[['poor', 'fair', 'good', 'excellent']]), ['condition'])])
data = apartments.drop_duplicates()
Xp = prepare.fit_transform(data)
print(Xp.shape)
list(prepare.get_feature_names_out())(600, 12)
['num__area_m2',
'num__rooms',
'num__floor',
'num__year_built',
'num__missingindicator_year_built',
'nom__district_Centre',
'nom__district_East',
'nom__district_North',
'nom__district_South',
'nom__parking_no',
'nom__parking_yes',
'ord__condition']Eleven raw columns became 12 model inputs: four scaled numbers, one missing-indicator (only year_built had gaps among the numbers here), six one-hot columns (four districts, parking yes and no), and one ordinal code. The identifier, the date and the leaky column were simply not listed.
6. Two Leaks, Measured¶
Feature selection before cross-validation¶
A classic trap: 100 examples, 5 000 features of pure noise, and random labels. No model can do better than 50% here. But if we first select the 20 features most correlated with the labels using all the data, and only then cross-validate, the score looks excellent.
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
rng = np.random.default_rng(1)
X_noise = rng.normal(size=(100, 5000)); y_noise = rng.integers(0, 2, 100)
X_selected = SelectKBest(f_classif, k=20).fit_transform(X_noise, y_noise) # selection saw every label
leaky = cross_val_score(LogisticRegression(max_iter=1000), X_selected, y_noise, cv=5).mean()
honest_model = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000)) # selection inside each fold
honest = cross_val_score(honest_model, X_noise, y_noise, cv=5).mean()
print(f'selection outside cross-validation: {leaky:.2f} inside the pipeline: {honest:.2f}')selection outside cross-validation: 0.91 inside the pipeline: 0.47
The selection step had already looked at the test folds’ labels and picked the noise columns that happen to match them. Inside a pipeline, each fold selects its features from its own training part, and the score falls back to chance, which is the truth.
The same patient on both sides¶
Many medical datasets hold several measurements per patient. Each patient has their own baseline, so a model can learn to recognise patients instead of learning the disease. Here 40 patients have 10 visits each; the label depends on the patient, not on any measured symptom.
from sklearn.model_selection import KFold, GroupKFold
from sklearn.ensemble import RandomForestClassifier
rng = np.random.default_rng(2)
patients = np.repeat(np.arange(40), 10)
signature = rng.normal(size=(40, 5))[patients] + rng.normal(scale=0.3, size=(400, 5)) # each patient's own baseline
label = rng.integers(0, 2, 40)[patients] # unrelated to the measurements
forest = RandomForestClassifier(n_estimators=200, random_state=0)
random_split = cross_val_score(forest, signature, label, cv=KFold(5, shuffle=True, random_state=0)).mean()
group_split = cross_val_score(forest, signature, label, cv=GroupKFold(5), groups=patients).mean()
print(f'random folds: {random_split:.2f} folds by patient: {group_split:.2f}')random folds: 0.88 folds by patient: 0.56
With random folds, every test visit has nine siblings in the training set, and the forest recognises the patient. With folds by patient, the model meets new patients, as it would in a hospital, and its score falls to chance.
Summary¶
first_lookprofiles a table in one call; meaning (which column is computed from the target) still needs a person.Robust statistics (IQR, median and MAD) find outliers that inflate the plain z-score.
Imputers differ most when values are missing not at random; neighbours-based imputation and missing-indicators help.
Spearman sees monotonic curves and shrugs off outliers; heatmaps reveal redundant features.
ColumnTransformer+Pipelineprepare each kind of column correctly and are fitted on training data only.Selection before cross-validation and splits that ignore groups both produce excellent, false scores.