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: Understanding Your Data — Implementation

Open in Colab

This notebook turns the chapter’s checklist into code you can reuse on any table:

  1. A first look in one function

  2. Outliers: the IQR rule and a robust z-score

  3. Missing values: what each imputer does to the data

  4. Relationships: Pearson against Spearman

  5. A preparation pipeline with ColumnTransformer

  6. Two leaks measured: feature selection before cross-validation, and the same patient on both sides

(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.

605 rows, 11 columns, 5 duplicated rows
Loading...

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: zi=0.6745 (xi−median)/MADz_i = 0.6745\,(x_i - \text{median}) / \text{MAD}, flagged when ∣zi∣>3.5|z_i| > 3.5.

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).

Loading...

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 rr measures straight-line association; Spearman’s ρ\rho measures any monotonic association. They disagree in two situations: a curved but monotonic relation, and an outlier.

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, ρ=1\rho = 1 (the relation never falls) while rr 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
<Figure size 700x550 with 2 Axes>
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.

(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.

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.

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_look profiles 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 + Pipeline prepare 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.