Data preparation
Why This Matters
Data preparation takes more effort than building the model, often far more. It is also where many defects are introduced: a cleaning step that silently drops half the women from the data, an imputation that turns every missing income into the average. And if the data in production does not look like the prepared training data, every assumption about the model’s performance, and its safety, can be wrong. Testers who understand preparation know where to look.
What you will learn
- The activities of data preparation: acquisition, preprocessing, feature engineering and exploratory data analysis
- How to prepare a real dataset for a supervised classification model
- How to test each preparation step, so a defect in the preparation does not end up in the model
Syllabus: AI-3.2.1, HO-3.2.2 (perform data preparation).
The activities
Data acquisition
- Identify the data types: numerical, categorical, image, text, time series, sensor, geospatial, video, audio. Each needs different preparation.
- Gather the data from databases, APIs or sensors.
- Label the data for supervised learning, and check that the labels are accurate and consistent (lesson 39).
Data preprocessing
- Cleaning: remove defects, duplicates and outliers; impute missing values (fill them in with the mean, median or mode); anonymise or remove personal data.
- Transformation: convert formats, scale and normalise numbers so that features with large values (income) do not dominate features with small ones (age) in algorithms that are sensitive to it.
- Augmentation: create more examples: more samples of a rare class, adversarial examples to make the model robust, synthetic data.
- Sampling: use a subset of the data to reduce training time and cost.
Feature engineering
Choose the features the model learns from: keep the relevant ones, drop the irrelevant or redundant ones, and extract new, more informative features from the raw data (a date of birth becomes an age; a free-text city becomes one column per city).
Exploratory data analysis (EDA)
Look at the data before and during preparation: distributions, trends, patterns and anomalies, usually with plots and summary tables. EDA is where you discover that an age column contains the word “thirty-five”.
Preparation is iterative and often manual. Steps can be done in another order or skipped, and the preparation in production may be simplified for speed. That last point is a risk: if production prepares data differently from training, the model sees inputs it was not trained on (lesson 36, Data pipeline testing).
Hands-on: prepare the loan data
In lesson 13 you trained a model after a quick_clean that threw away every row with a problem: 9 of 50 rows. Now you prepare the data properly. You continue in the practice project from the lesson Set up your practice project:
cd ai-testing-practice
source .venv/bin/activate # Windows: .venv\Scripts\activate
Look first (EDA)
Start a Python prompt with python and look at the raw data:
import pandas as pd, requests
df = pd.DataFrame(requests.get("https://practiceautomatedtesting.com/api/ml/datasets/loans-train").json()["data"])
df.dtypes
df.isna().sum()
df["city"].value_counts()
df["approved"].value_counts()
What you find:
agehas typeobjectinstead of a number: one value is the text"thirty-five". There are also ages of 150 and −5.age,incomeandcreditScoreeach have one missing value. One income is −5,000.cityhas seven values for five cities: New York appears asNew York(8),new york(1) andNYC(1).approvedis No 36 times and Yes 14 times: an imbalanced dataset. A model that always says No is right 72% of the time (remember the baseline from lesson 13).- Grace Lee applied three times with exactly the same values.
Prepare
Create module-3/test_data_preparation.py. The function prepare does the preparation; every block is one activity from above:
"""Lesson "Data preparation": clean, transform and engineer the loan data, and test that each step did its job."""
import numpy as np
import pandas as pd
import pytest
NUMERIC = ["age", "income", "creditScore"]
CITIES = {"New York", "Los Angeles", "Chicago", "Houston", "Phoenix"}
def prepare(raw):
"""Turn the raw training data into data a model can learn from."""
df = raw.copy()
# Cleaning: wrong types and impossible values become missing values
df["age"] = pd.to_numeric(df["age"], errors="coerce") # "thirty-five" -> NaN
df.loc[~df["age"].between(18, 120), "age"] = np.nan # 150 and -5 -> NaN
df.loc[df["income"] < 0, "income"] = np.nan # -5000 -> NaN
# Cleaning: one spelling per city
df["city"] = df["city"].str.strip().str.title().replace({"Nyc": "New York"})
# Cleaning: remove duplicate applications (same values, different id)
df = df.drop_duplicates(subset=[c for c in df.columns if c != "id"])
# Cleaning: impute missing numbers with the median of the column
for column in NUMERIC:
df[column] = df[column].fillna(df[column].median())
# Personal data: the name is not needed to learn a loan decision
df = df.drop(columns=["name"])
# Transformation / feature engineering: one column per city (one-hot encoding)
df = pd.get_dummies(df, columns=["city"], prefix="city", dtype=int)
return df.reset_index(drop=True)
Some choices worth noticing:
- Impossible values become missing, then imputed, instead of dropping the whole row. Row 15 has an impossible age but a perfectly good income, credit score and decision; dropping it loses that information.
- The median, not the mean. One very high income pulls the mean up; the median is not affected by outliers.
- The name is removed. It is personal data, and a loan decision should not depend on it (module 6 shows a model that does).
- One-hot encoding. A model cannot calculate with “Chicago”.
get_dummiesmakes a column per city with 0 or 1. Mapping cities to numbers 1 to 5 instead would suggest that Phoenix is “more” than Chicago, which means nothing. - No scaling. Decision trees compare one feature at a time with a threshold, so the scale does not matter. For a neural network or a distance-based algorithm you would scale income and age to the same range.
Test the preparation
Preparation is code, and code has defects. Each test checks that one step did its job:
@pytest.fixture(scope="module")
def raw(api):
response = api.get(f"{api.base}/datasets/loans-train", timeout=10)
response.raise_for_status()
return pd.DataFrame(response.json()["data"])
@pytest.fixture(scope="module")
def prepared(raw):
data = prepare(raw)
print(f"\n{len(raw)} rows in, {len(data)} rows out")
print(data[NUMERIC].describe().round(0).loc[["count", "min", "50%", "max"]].to_string())
return data
def test_no_missing_values(prepared):
assert prepared.isna().sum().sum() == 0
def test_numbers_are_numbers_within_range(prepared):
assert pd.api.types.is_numeric_dtype(prepared["age"])
assert prepared["age"].between(18, 120).all()
assert (prepared["income"] >= 0).all()
assert prepared["creditScore"].between(300, 850).all()
def test_no_duplicate_applications(prepared):
assert not prepared.drop(columns="id").duplicated().any()
def test_one_column_per_known_city(prepared):
city_columns = {c.removeprefix("city_") for c in prepared.columns if c.startswith("city_")}
assert city_columns == CITIES
def test_personal_data_is_removed(prepared):
assert "name" not in prepared.columns
def test_preparation_keeps_more_data_than_dropping_rows(raw, prepared):
dropped = raw.dropna(subset=NUMERIC)
assert len(prepared) > len(dropped)
def test_preparation_does_not_change_the_raw_data(raw):
before = raw.copy()
prepare(raw)
pd.testing.assert_frame_equal(raw, before)
The last test catches a classic: a preparation function that changes its input. If prepare modified the raw data in place, every later step that uses the “raw” data would get prepared data instead, and nobody would notice.
Run it
pytest module-3/test_data_preparation.py -v -s
50 rows in, 48 rows out
age income creditScore
count 48.0 48.0 48.0
min 20.0 31584.0 501.0
50% 46.0 74920.0 629.0
max 69.0 129352.0 791.0
PASSED
module-3/test_data_preparation.py::test_numbers_are_numbers_within_range PASSED
module-3/test_data_preparation.py::test_no_duplicate_applications PASSED
module-3/test_data_preparation.py::test_one_column_per_known_city PASSED
module-3/test_data_preparation.py::test_personal_data_is_removed PASSED
module-3/test_data_preparation.py::test_preparation_keeps_more_data_than_dropping_rows PASSED
module-3/test_data_preparation.py::test_preparation_does_not_change_the_raw_data PASSED
============================== 7 passed
48 rows instead of the 41 that quick_clean kept: only the two extra copies of Grace Lee’s application are gone. All ages are now 20 to 69, no income is negative, nothing is missing.
See it fail
Comment out the line that cleans up the city names and run the tests again:
E AssertionError: assert {'Chicago', '...Phoenix', ...} == {'Chicago', '...k', 'Phoenix'}
E Extra items in the left set:
E 'NYC'
E 'new york'
1 failed, 6 passed
Without the test, the model would get three separate New York columns, each with too few examples to learn anything from. Put the line back.
What preparation does not fix
Two defects are still in the data, and no test above finds them: rows 18 and 22 have the wrong label (lesson 38 found them with a constraint on the label). Imputation also has a cost: the applicant whose credit score was missing now has the median, 629, and is labelled “approved”, which may teach the model something wrong. Preparation makes data usable; it does not make it correct. That is what module 6 is for.
Exercise
- The imputation uses the median of the whole dataset. In lesson 16 you will split the data into training and test data after this preparation. Why is that a problem, and how would you fix it?
- Add a test that checks that the share of approved applications is about the same before and after preparation (within 5 percentage points). Why is that a useful test for a cleaning step?
Show suggested answer
The medians are calculated from all rows, including the rows that will later be test data. Information from the test data then leaks into the training data: data leakage. Here the effect is tiny, but with a scaler or an encoder fitted on all data it can make test results look better than they are. The fix: split first, calculate the medians (and any scaling) on the training data only, and apply those same values to the test data and later to production data. Libraries such as scikit-learn’s
Pipelinedo this for you.For example:
def test_cleaning_keeps_the_label_balance(raw, prepared): before = (raw["approved"] == "Yes").mean() after = (prepared["approved"] == "Yes").mean() assert abs(after - before) <= 0.05A cleaning step that removes rows can remove them unevenly: if most of the rows with missing values were approvals, dropping them changes what the model learns. The same check per group (gender, age, city) catches cleaning that removes one group more than another, which is a source of bias (lesson 35).
Exam-style questions
1. Which activity is part of data preprocessing?
- A. Selecting the algorithm
- B. Imputing missing values with the median
- C. Deploying the model to the cloud
- D. Defining the acceptance criteria
Show answer
2. A team generates extra synthetic examples of the rare “fraud” class. Which preparation activity is this?
- A. Sampling
- B. Augmentation
- C. Feature selection
- D. Labelling
Show answer
3. Why can it be a risk when data in production is prepared differently from the training data?
- A. The model will train more slowly
- B. The model receives inputs that differ from what it was trained on, so its tested performance and safety assumptions may not hold
- C. Production data does not need to be prepared
- D. It is only a risk for unsupervised learning
Show answer
Your project so far
ai-testing-practice/
├── ...
└── module-3/
├── test_first_model.py
└── test_data_preparation.py new in this lesson
The finished version is in the example repository: module-3/test_data_preparation.py.