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

Open in Colab

Torture the data, and it will confess to anything.

Ronald Coase

7.1 Look Before You Learn

Part II of this book is about machine learning: programs that find a rule in examples instead of being told it. Every method in it, from linear regression (Chapter 8) to neural networks (Chapter 15), assumes something about the data it is given: that the numbers mean what they say, that the examples are typical of the cases it will meet, that nothing in the input secretly contains the answer. When those assumptions fail, the model still trains, still reports a score, and is still wrong.

The cheapest way to avoid that is to look at the data before learning from it. This step is called exploratory data analysis (EDA). It is not a formality: in practice it takes more time than training, and most of the mistakes that ruin a project are made, or caught, here.

This chapter uses one dataset from start to finish: 600 apartment listings from a fictional city, with the price each one sold for. The goal later is to predict the price of a new listing. The data were generated by the code below so that every number in this chapter can be reproduced, and so that the problems real data have (typing mistakes, missing values, duplicates, a leaky column) are present on purpose.

Source
Loading...

7.2 Examples, Features and a Target

A dataset for supervised learning is a table:

  • Each row is one example (also called an observation, an instance or a sample): here, one apartment.

  • Each column is a variable. The one we want to predict is the target (or label): here, price_k, the price in thousands. The others are candidate features: the inputs the model may use.

Before anything else, decide what one row stands for, the unit of observation. Here it is “one sale of one apartment”. If the same apartment were sold twice, it would appear twice, and the two rows would not be independent: a fact that matters when the data are split (Section 7.9).

Not every column is a feature. listing_id is an identifier: it names the row but says nothing about the apartment. A model given it would try to learn from it (an ID number that happens to grow with time can even look useful), so identifiers are set aside. The same goes for free-text notes, file names and anything recorded after the outcome.

Kinds of features

KindExample hereValuesWhat a model needs
Numerical, continuousarea_m2, price_kany number in a rangeoften scaling (Section 7.8)
Numerical, discreterooms, floorcountsusually used as numbers
Categorical (nominal)districtlabels with no orderencoding, e.g. one-hot
Ordinalconditionlabels with an order: poor < fair < good < excellentan encoding that keeps the order
Binaryparkingyes / no0 / 1
Date or timelisteddatessplit into parts (year, month, weekday), or an age
Identifierlisting_idunique per rownot a feature

The kind of a feature is a fact about its meaning, not its storage. A postcode is stored as a number but is categorical: postcode 75012 is not “more” than 75011. A room count stored as text ("3") is still numerical, and has to be converted.

7.3 A First Look

Four questions, each answered by one line of pandas, give most of the first picture.

How big is it, and what types does it hold?

(605, 11)
listing_id str district str area_m2 float64 rooms int64 floor int64 year_built float64 condition str parking str listed datetime64[us] price_k float64 price_per_m2 float64 dtype: object

605 rows and 11 columns. The types are what we expect: numbers for the measurements, text (object or str) for the categories, a date for listed. Watch for numbers stored as text (a stray "n/a" in a numeric column turns the whole column into text) and for categories stored as numbers.

What do the numbers look like?

Loading...

describe() gives the count, mean, standard deviation, minimum, quartiles and maximum of each numerical column. Read it line by line, asking “is this plausible?”:

  • area_m2 has a median (50%) of 78 m² and a third quartile of 100 m², but a maximum of 1 090 m²: an apartment fourteen times the median. Either a palace or a typing mistake.

  • year_built has a count of 546, not 605: some values are missing (Section 7.6).

  • price_per_m2 looks very tidy. Suspiciously tidy: we will come back to it.

What do the categories look like?

{'North': 174, 'South': 164, 'Centre': 148, 'East': 119}
{'good': 216, 'fair': 208, 'excellent': 96, 'poor': 85}
{'no': 314, 'yes': 279, nan: 12}

No surprises in the labels (no “centre” next to “Centre”, no "Excellent " with a trailing space), but parking has 12 missing values. Inconsistent spellings are common in real data and must be merged before encoding, or one category becomes two.

Are there duplicates?

duplicated rows: 5
(600, 11)

Five rows are exact copies of others. A duplicate counts its example twice, and if one copy lands in the training set and the other in the test set, the model is tested on an example it has already seen. We drop them: 600 apartments remain.

7.4 Distributions and Outliers

Summary numbers hide shapes. A histogram shows them.

Source
<Figure size 1300x330 with 3 Axes>

Skew

Most values of area_m2 sit between 50 and 120, with a long tail of large apartments to the right: the distribution is right-skewed. Prices are skewed the same way. Skew is normal for quantities that cannot go below zero and grow by multiplication (sizes, prices, incomes, waiting times).

Skew matters because many models are sensitive to a few large values. Linear regression with squared error, for example, works hard to fit the expensive apartments, at the expense of the typical ones. A log transform pulls the long tail in: the histogram of log⁡(price)\log(\text{price}) above is nearly symmetric. A model that predicts log⁡(price)\log(\text{price}) predicts a percentage error rather than an absolute one, which is usually what we want for prices.

skew of price_k:      1.29
skew of log(price_k): 0.04

A skewness near 0 means symmetric; above about 1, strongly right-skewed.

Outliers

An outlier is a value far from the others. Two simple rules find candidates:

  • The IQR rule (the box-plot rule): a value is suspicious if it lies more than 1.5×IQR1.5 \times \text{IQR} below the first quartile or above the third, where IQR=Q3−Q1\text{IQR} = Q_3 - Q_1.

  • The z-score rule: a value is suspicious if it lies more than 3 standard deviations from the mean. It is less reliable on skewed data, and the outliers themselves inflate the standard deviation they are measured with.

Q1 = 63, Q3 = 100, IQR = 37, fences = [7, 156]
25 flagged; the largest: [194.0, 197.0, 560.0, 840.0, 1090.0]

The rule flags 25 apartments. Most are large but plausible (up to 197 m²); three values, 560, 840 and 1 090 m², are in a class of their own. A rule only finds candidates; deciding what they are needs knowledge of the domain:

  1. Is it possible? A 1 090 m² apartment with 4 rooms is not, nor a 560 m² one with 2 rooms. At a few hundred per square metre, their prices would also be absurdly low for the city. These are errors, almost certainly an extra zero.

  2. If it is an error, can it be corrected? Here the rooms and the price suggest the true area (109 m² for the largest). When the correction is a guess, prefer to mark the value as missing and treat it as in Section 7.6.

  3. If it is genuine, keep it. A 197 m² penthouse is a real apartment, and the model will meet others like it. Deleting real extremes makes a model that is surprised by reality.

3 areas set to missing

7.5 Look at the Target

The target deserves the closest look, because everything is measured against it.

  • For regression, look at its distribution (here: skewed, so consider predicting its logarithm) and its range (a model trained on prices between 90 and 900 thousand cannot be trusted at 5 million).

  • For classification, count the classes. If 95% of the examples are in one class, a model that always predicts that class scores 95% accuracy and is useless. This imbalance changes how a model must be trained and judged (Chapter 11).

Whatever the task, compute the score of a baseline: the simplest possible predictor. For regression, predict the mean (or median) price for everyone; for classification, predict the most frequent class. A model is only worth its complexity if it clearly beats the baseline.

median price 214k; predicting it for everyone misses by 81k on average

7.6 Missing Values

Counting them

area_m2 3 year_built 59 parking 12 dtype: int64

Why they are missing matters

Statisticians distinguish three patterns:

PatternMeaningExample hereConsequence
MCAR, missing completely at randomthe gap has nothing to do with any valueparking lost when a form was mis-scanneddropping rows loses data but adds no bias
MAR, missing at randomthe gap depends on other, observed featuresyear_built missing more often in the oldest buildings’ records…filling must use the other features; dropping biases
MNAR, missing not at randomthe gap depends on the missing value itselfowners of tiny flats leaving area_m2 blankthe gap itself carries information

Here year_built is missing only for buildings from before 1975: the records of old buildings were lost. Dropping those rows would remove almost a third of the old apartments (59 of 198), and a model trained on what is left would know little about old buildings.

year_missing
False    214.0
True     196.0
Name: price_k, dtype: float64

The apartments with a missing year sold for less, as old apartments do: the missingness is informative.

Strategies

  1. Drop the rows with a missing value: simple, acceptable when few rows are affected and the gaps are MCAR.

  2. Drop the column: when most of it is missing and it is not essential.

  3. Impute (fill in): with the median for numbers (robust to skew and outliers), the most frequent value for categories, or a prediction from the other features (k-nearest neighbours, a regression model).

  4. Add a missing-indicator column (year_missing above) next to the imputed one, so that the model can still use the fact that the value was missing.

7.7 Relationships

Between numbers: correlation

The Pearson correlation rr measures how close a cloud of points is to a straight line, from -1 (a perfect falling line) through 0 (no linear relation) to +1 (a perfect rising line). The Spearman correlation is Pearson’s rr computed on the ranks of the values: it measures any monotonic relation (always rising or always falling, not necessarily in a straight line), and is not thrown by outliers.

Loading...
Source
<Figure size 1300x330 with 3 Axes>

Three things to read in the table and the plots:

  • Correlation with the target. area_m2 is strongly related to price (r=0.68r = 0.68); floor not at all (r≈0r \approx 0). That does not mean floor is useless (it could matter in combination with something else), but it is a first ranking.

  • Correlation between features. area_m2 and rooms are strongly correlated (r=0.84r = 0.84): larger apartments have more rooms. Two features that carry nearly the same information are redundant. For linear models this multicollinearity makes the individual coefficients unstable (the model cannot tell which of the two deserves the credit); for prediction it matters less.

  • Shape. rr only sees straight lines. Always plot: a perfect U-shaped relation has r≈0r \approx 0.

Between a category and a number

For a categorical feature, compare the target across its groups:

Loading...

Centre apartments sell for nearly twice as much as East ones (a median of 313k against 172k): district matters. A box plot per group shows the same comparison with the spread.

7.8 Preparing Features: Encoding and Scaling

Most models compute with numbers, so every feature must become numbers, in a way that keeps its meaning.

Encoding categories

  • One-hot encoding gives each category its own 0/1 column: district_Centre, district_North, …. It assumes no order between categories, which is right for nominal features. With kk categories it adds kk columns (or k−1k-1, dropping one as the reference).

  • Ordinal encoding maps ordered labels to ordered numbers: poor → 0, fair → 1, good → 2, excellent → 3. It keeps the order in one column. Using it on a nominal feature (Centre → 0, North → 1, …) invents an order and distances that do not exist.

  • Binary features become a single 0/1 column.

Loading...

High-cardinality categories (thousands of postcodes, product IDs) make one-hot encoding produce thousands of mostly-zero columns. Options are grouping rare categories into “other”, or target encoding (replacing a category by the mean target in that category), which must be computed on the training folds only, or it leaks the target.

Scaling numbers

Features come in different units: area_m2 in tens to hundreds, floor in units, year_built in thousands. Some models compare features directly and are dominated by the ones with the largest numbers:

  • Need scaling: k-nearest neighbours and k-means (distances), support vector machines, regularised linear models (the penalty treats all weights alike), neural networks and anything trained by gradient descent (Chapter 15).

  • Do not need it: decision trees and their ensembles, which only ask “is xjx_j above a threshold?”, a question that does not change when the unit does.

Three common scalers:

ScalerFormulaResultUse when
Standardisationz=(x−xˉ)/sz = (x - \bar{x}) / smean 0, standard deviation 1the default
Min–max(x−min⁡)/(max⁡−min⁡)(x - \min) / (\max - \min)between 0 and 1a bounded range is needed (pixels)
Robust(x−median)/IQR(x - \text{median}) / \text{IQR}median 0outliers remain

Like imputation, a scaler’s numbers (mean, standard deviation, minimum, maximum) are learned: fit it on the training set only.

Making new features

Feature engineering turns raw columns into inputs a model can use more easily:

  • From a date, extract the year, the month, the day of the week; or compute an age (2024 - year_built).

  • From two columns, a ratio or a product (area per room).

  • From a skewed number, its logarithm.

  • From a number with thresholds that matter, bins (“built before 1975”).

Good features come from understanding the problem. A model can learn many transformations by itself, but only from features that contain the information.

7.9 Data Leakage

Data leakage is the use, during training, of information that will not be available when the model is used. It makes the model look excellent in testing and fail in practice. It is the single most common reason why a model that “scored 99%” disappoints. Four forms account for most cases.

1. Target leakage

A feature that is computed from the target, or recorded after it. Our dataset has one: price_per_m2 is the price divided by the area. A model given price_per_m2 and area_m2 can recover the price exactly, and nobody knows the price per square metre of an apartment before it is sold.

with price_per_m2  test R² = 1.000
without it         test R² = 0.337

A test R2R^2 of 1.000 (Chapter 11: a perfect fit) is not a triumph; it is a symptom. Without the leak, three honest features reach 0.34: a modest score, but a real one. When a result looks too good to be true, look for a leak. Typical target leaks in other domains: a “treatment given” column in a model that predicts a diagnosis; the “number of reminder letters sent” in a model that predicts late payment.

2. Train–test contamination

Information from the test set used during training: scaling, imputing or selecting features on the full dataset before splitting it. The test set then helped shape the model, and its score is no longer an honest estimate. The cure is a strict order: split first, then fit every preparation step on the training part only. A scikit-learn Pipeline enforces this (Section 7.10).

3. Temporal leakage

Using the future to predict the past. Our listings span 2022–2023. If the model will price new listings, it should be tested on listings that came after those it was trained on: train on 2022, test on 2023. A random split mixes the years, and lets the model learn price trends from the future.

4. Group leakage

The same entity on both sides of the split: two sales of the same apartment, several X-rays of the same patient, many photos of the same person. The model can recognise the entity instead of learning the task. The cure is to split by group (all rows of an entity go to the same side): scikit-learn’s GroupKFold and GroupShuffleSplit do it (Chapter 10).

LeakQuestion to askPrevention
Target leakagewould I know this feature at prediction time?remove the feature
Contaminationdid any step see the test data?split first; use a pipeline
Temporaldoes the test set come after the training set?split by time
Groupcan the same entity appear on both sides?split by group

7.10 Putting It Together: a Leak-Free Pipeline

Scikit-learn’s ColumnTransformer applies a different preparation to each kind of column, and a Pipeline chains it with a model. Calling fit on the training set fits every step on the training set only; calling predict or score on the test set only applies them.

332 training and 268 test listings
mean absolute error on 2023: 29k (the median baseline: 81k)

Everything in this chapter is in those lines: the identifier and the leaky column are left out; numbers are imputed with the median (with a missing-indicator) and standardised; nominal categories are one-hot encoded; the ordinal one keeps its order; the target is predicted on a log scale; and the split respects time. The model’s error is about a third of the baseline’s (29k against 81k).

7.11 A Checklist

Before training any model:

  1. What is one row? What is the target? Which columns are identifiers?

  2. Shape, types, describe(), value_counts(): is every value plausible?

  3. Duplicates: removed, or kept on purpose?

  4. Distributions: skewed? Outliers: errors (fix or mark missing) or facts (keep)?

  5. The target: its distribution or class balance; the baseline’s score.

  6. Missing values: how many, which pattern, which strategy (fitted on training data only)?

  7. Relationships: with the target, and between features (redundancy)?

  8. Encoding and scaling: right for each kind of feature, and for the model?

  9. Leakage: would every feature be known at prediction time? Is the split by time or by group where needed?

7.12 Summary

  • A dataset is examples (rows), features and a target (columns). Identifiers and after-the-fact columns are not features.

  • The kind of a feature (numerical, nominal, ordinal, binary, date) decides how it is prepared.

  • A first look (shape, dtypes, describe, value_counts, duplicated) catches most problems in minutes.

  • Skewed quantities are often better modelled on a log scale. Outlier rules find candidates; domain knowledge decides between error and fact.

  • Missing values have a pattern; the pattern decides the strategy. Imputation is learned, so it is fitted on training data.

  • Correlation measures linear association with the target and redundancy between features; it is not causation.

  • One-hot for nominal, ordered codes for ordinal; scale for distance- and gradient-based models, not for trees.

  • Data leakage (target, contamination, temporal, group) makes models look better than they are. Split first, and put every preparation step in a pipeline.

Exercises

  1. For each column of the apartments dataset, give its kind (Section 7.2) and say how you would prepare it for a k-nearest-neighbours model.

  2. A column bedrooms_text holds values such as "2", "3", "two" and "3+". What problems do you see, and how would you clean it?

  3. The IQR fences for a feature are [10,90][10, 90]. A value of 95 is flagged. Give one situation where you should keep it and one where you should not.

  4. Explain why imputing the mean of year_built over the whole dataset before a train–test split is a leak, even though the target is not involved.

  5. A model that predicts whether a customer will cancel a subscription reaches 99% accuracy. One feature is days_since_last_login, computed on the day the dataset was exported. What may be wrong?

  6. Two features have a correlation of 0.98. Should you remove one? Answer for a linear regression whose coefficients you want to interpret, and for a random forest used only to predict.

  7. Why is one-hot encoding the right choice for district, and ordinal encoding the right choice for condition?

Further Reading

  • W. McKinney, Python for Data Analysis, 3rd ed., O’Reilly, 2022 (pandas, by its author).

  • A. Géron, Hands-On Machine Learning with Scikit-Learn, Keras and TensorFlow, 3rd ed., O’Reilly, 2022, Chapter 2 (an end-to-end project).

  • S. Kaufman, S. Rosset, C. Perlich, “Leakage in data mining: formulation, detection, and avoidance”, ACM TKDD, 2012.

  • R. J. A. Little, D. B. Rubin, Statistical Analysis with Missing Data, 3rd ed., Wiley, 2019.

  • The scikit-learn user guide, “Common pitfalls and recommended practices”.