Skip to main content

Hands-on: input data testing

Why This Matters

Before anyone trains a model on a dataset, someone should look at it with a tester’s eye: what is missing, what is there twice, what is impossible? It takes an hour, it catches defects that would otherwise surface months later as an unexplained model failure, and the result is a report the data owner can act on. This lesson turns the three most common checks into code: missing data, duplicates and outliers.

What you will learn

  • Detect missing values, including values hidden as the wrong type
  • Detect exact and near duplicates
  • Detect outliers statistically (Tukey’s IQR rule), and see what statistics miss
  • Report findings so the data owner can act

Syllabus: HO-5.1.7 (perform input data testing for ML datasets).

Try it by hand first

Open the Data Quality lab. It shows the same 50 loan applications as the practice API. Find as many problems as you can in 10 minutes, and write them down: you will compare your list with what the code finds.

Hands-on

You continue in the practice project. Create module-6/test_input_data.py:

"""Lesson "Hands-on: input data testing": find missing data, duplicates and outliers in a tabular dataset."""
import pandas as pd
import pytest

NUMERIC = ["age", "income", "creditScore"]


@pytest.fixture(scope="module")
def data(api):
    raw = pd.DataFrame(api.get(f"{api.base}/datasets/loans-train", timeout=10).json()["data"])
    df = raw.copy()
    df["age"] = pd.to_numeric(df["age"], errors="coerce")   # text in a number column becomes missing
    return raw, df


def missing(df):
    """{column: [ids]} for every column with missing values."""
    return {c: df.loc[df[c].isna(), "id"].tolist() for c in df.columns if df[c].isna().any()}


def duplicates(df):
    """Ids of records that repeat an earlier record in every field except the id."""
    return df.loc[df.drop(columns="id").duplicated(keep="first"), "id"].tolist()


def outliers_iqr(df, column, k=1.5):
    """Tukey's rule: below Q1 - k*IQR or above Q3 + k*IQR."""
    q1, q3 = df[column].quantile([0.25, 0.75])
    low, high = q1 - k * (q3 - q1), q3 + k * (q3 - q1)
    return df.loc[(df[column] < low) | (df[column] > high), "id"].tolist(), (low, high)

Three things in these few lines matter:

  • Missing hides in other forms. "thirty-five" in the age column is not NaN, so isna() does not see it. Converting to a number first turns it into a missing value you can count. Other disguises: empty strings, 0, -1, "N/A", 9999.
  • Duplicates ignore the id. Two records with different ids and the same everything else are the same application entered twice. A duplicate check on all columns would miss them.
  • Tukey’s IQR rule flags values far outside the middle 50% of the data: below Q1 − 1.5 × IQR or above Q3 + 1.5 × IQR, where IQR = Q3 − Q1. It is robust: unlike a z-score, it is not pulled off course by the outliers themselves.

The report and the tests:

def test_report(data):
    raw, df = data
    print(f"\n  rows: {len(df)}")
    print(f"  missing: {missing(df)}  (age includes text that is not a number: {raw.loc[raw['age'].notna() & df['age'].isna(), 'id'].tolist()})")
    print(f"  duplicates: {duplicates(df)}")
    for column in NUMERIC:
        ids, (low, high) = outliers_iqr(df, column)
        print(f"  outliers {column} (outside {low:.0f} to {high:.0f}): {ids}")


def test_missing_values(data):
    _, df = data
    assert missing(df) == {"age": [25, 28], "income": [5], "creditScore": [12]}


def test_duplicates(data):
    _, df = data
    assert duplicates(df) == [8, 9]


def test_statistical_outliers_in_age(data):
    _, df = data
    assert outliers_iqr(df, "age")[0] == [15, 41]


def test_statistics_miss_an_impossible_income(data):
    # -5000 lies inside the IQR fences, because incomes vary a lot. Only a domain rule finds it.
    _, df = data
    assert 22 not in outliers_iqr(df, "income")[0]
    assert df.loc[df["income"] < 0, "id"].tolist() == [22]

Run it

pytest module-6/test_input_data.py -v -s
  rows: 50
  missing: {'age': [25, 28], 'income': [5], 'creditScore': [12]}  (age includes text that is not a number: [25])
  duplicates: [8, 9]
  outliers age (outside -2 to 91): [15, 41]
  outliers income (outside -41114 to 183562): []
  outliers creditScore (outside 342 to 930): []
PASSED
module-6/test_input_data.py::test_missing_values PASSED
module-6/test_input_data.py::test_duplicates PASSED
module-6/test_input_data.py::test_statistical_outliers_in_age PASSED
module-6/test_input_data.py::test_statistics_miss_an_impossible_income PASSED

============================== 5 passed

What it found, and what it missed

FindingRowsFound by
Missing value5 (income), 12 (credit score), 28 (age)missing
Text in a number column25 (“thirty-five”)missing, after conversion
Duplicate application8 and 9 (copies of 7)duplicates
Impossible age15 (150), 41 (−5)IQR outliers
Impossible income22 (−5,000)not IQR: only the domain rule income < 0

The IQR fences for income run from −41,114 to 183,562, because incomes legitimately vary a lot. A negative income sits comfortably inside them. Statistics find values that are unusual; they do not know what is impossible. You need both: statistical checks for the unexpected, and domain rules (constraints, lesson 38) for what you know cannot be.

Compare with your list from the Data Quality lab. Did you also spot "new york" and "NYC", and the two wrong labels? Those are not missing, duplicate or outlier problems: they are found by a constraint (lesson 38) and by label testing (lesson 39). A complete input data test uses all of them.

Report it

A finding is only useful if the data owner can act on it. Per finding, give:

  • what (the check and the rule), where (the row ids and columns), how many (count and share of the data)
  • impact for the model (a duplicate gives an example double weight; a missing income will be imputed)
  • a suggested action (fix at the source, impute, exclude, or accept)

Example: “Duplicate applications: rows 8 and 9 repeat row 7 in every field except the id (2 rows, 4%). Impact: this applicant counts three times in training, and may end up in both training and test data. Action: deduplicate on all fields except the id at ingestion, and find out why the form submitted three times.”

Exercise

  1. Change the IQR factor k from 1.5 to 3 (Tukey’s “far out” rule). Which age outliers remain?
  2. Add a check for near duplicates: applications with the same name and city but a different id and a slightly different income (within 1%). Why are near duplicates harder to handle than exact ones?
Show suggested answer
  1. With k = 3 the fences widen (to −37 to 126 for age), so 150 is still flagged and −5 is not. Row 41 is then found only by a domain rule (age ≥ 18). The choice of k trades missed outliers against false alarms; for impossible values, use a rule instead.

  2. For example:

    def near_duplicates(df, tolerance=0.01):
        pairs = df.merge(df, on=["name", "city"], suffixes=("", "_other"))
        pairs = pairs[pairs["id"] < pairs["id_other"]]
        close = (pairs["income"] - pairs["income_other"]).abs() <= tolerance * pairs["income"]
        return pairs.loc[close, ["id", "id_other"]].values.tolist()
    

    On the practice data it finds only the exact copies again (7–8, 7–9, 8–9). Near duplicates are harder because they need a judgement: is it the same person applying twice with a corrected income (a duplicate), or two people with the same name in the same city (not)? The rule needs domain knowledge, and the result needs a review.

Your project so far

ai-testing-practice/
├── ...
└── module-6/
    ├── test_dataset_constraints.py
    ├── test_bias.py
    ├── test_representativeness.py
    ├── test_label_correctness.py
    └── test_input_data.py    new in this lesson

The finished version is in the example repository: module-6/test_input_data.py.