Skip to main content

Testing for bias

Why This Matters

A model that treats people differently because of their gender, age or ethnicity is not just unfair: in most countries it is unlawful, and under the EU AI Act a high-risk system must be tested for it. Bias rarely announces itself. The model does not have a line that says “women minus 15”; it learned the pattern from history, or from a feature that stands in for something sensitive. Testers find it by asking the model the same question twice, with only the sensitive attribute changed.

What you will learn

  • What bias is, and where it comes from: the data or the algorithm
  • The approaches to test for bias, from reviews to statistics
  • How to run a disparate impact analysis with counterfactual applicants, in code

Syllabus: AI-5.1.2.

What bias is

In this syllabus, bias is a non-random, unfair difference in how people are treated, based on sensitive attributes such as gender, age, ethnicity or religion. It is often unlawful. (Not to be confused with the bias number in a neuron, lesson 21.)

Two sources:

  • Data bias: the training data is unrepresentative (few women in the data), historically skewed (past decisions were biased, and the model learns to repeat them), or deliberately poisoned.
  • Algorithmic bias: introduced by the algorithm, the model or the framework. The syllabus example: a fixed credit-score threshold in loan approval. The rule is the same for everyone, but if one group has systematically lower scores for reasons unrelated to their ability to repay, the threshold turns that into unequal outcomes.

Approaches

  • Reviews of the ML workflow, especially data preparation, and of the dataset documentation: how was the data collected and labelled, which populations does it represent?
  • Static analysis of the data preparation and model code: are sensitive attributes used as features? Handled carelessly? Are there anti-patterns, such as imputing missing values per group?
  • Exploratory data analysis: visualise and cluster the data per sensitive group to find imbalances and skews.
  • Dynamic testing with a known representative, unbiased dataset: check whether outcomes differ significantly between groups.
  • Label correctness testing (lesson 39): labels that link a sensitive attribute to an outcome are bias written into the data.
  • Disparate impact analysis: the approach you will run now.

Disparate impact analysis in four steps

  1. Identify the sensitive attributes: gender, age, ethnicity, and anything that can stand in for them (a name, a zip code).
  2. Generate counterfactuals: for each test input, make a copy that differs only in the sensitive attribute. The same loan application, once from a man and once from a woman.
  3. Run the model on the originals and the counterfactuals.
  4. Analyse statistically across many pairs whether changing the attribute changes the result.

It can be extended to combinations (older women), and the counterfactuals must stay realistic: changing the gender of an application is realistic; giving a 20-year-old 40 years of work experience is not.

It is metamorphic testing (lesson 46) with a legal purpose: the invariance relation “a sensitive attribute must not change the outcome”.

Hands-on

Try it by hand first in the Bias Detection lab: enter an applicant, run the paired tests, and see the score change with gender. Then automate it, for 40 applicants at once. You continue in the practice project. The 40 applicants from the test set are realistic applicants; you use them as the base for counterfactuals. Create module-6/test_bias.py:

"""Lesson "Testing for bias": disparate impact analysis with counterfactual applicants."""
import numpy as np
import pytest
from scipy import stats

APPLICANT_FIELDS = ["name", "gender", "age", "income", "creditScore", "employmentYears", "zipCode"]
MAX_SCORE_GAP = 3        # score points
SIGNIFICANCE = 0.01


@pytest.fixture(scope="module")
def applicants(api):
    """40 realistic applicants: the test set, without its labels."""
    rows = api.get(f"{api.base}/test-set", timeout=10).json()["data"]
    return [{field: row[field] for field in APPLICANT_FIELDS} for row in rows]


def predict(api, applicants, model):
    response = api.post(
        f"{api.base}/predict/batch",
        json={"applicants": applicants, "model": model, "seed": 1},
        timeout=10,
    )
    response.raise_for_status()
    predictions = response.json()["predictions"]
    return np.array([p["score"] for p in predictions]), np.array([p["approved"] for p in predictions])


def counterfactual_test(api, applicants, model, attribute, value_a, value_b):
    """Steps 2-4: make two versions of every applicant that differ only in one attribute, run both, compare."""
    group_a = [{**a, attribute: value_a} for a in applicants]
    group_b = [{**a, attribute: value_b} for a in applicants]
    scores_a, approved_a = predict(api, group_a, model)
    scores_b, approved_b = predict(api, group_b, model)
    gap = (scores_a - scores_b).mean()
    p_value = stats.ttest_rel(scores_a, scores_b).pvalue
    ratio = approved_b.mean() / approved_a.mean()
    print(f"\n  {model} {attribute} {value_a} vs {value_b}: approved {approved_a.mean():.0%} vs {approved_b.mean():.0%}"
          f" (ratio {ratio:.2f}), mean score gap {gap:+.1f}, p = {p_value:.2g}", end="")
    return gap, p_value

Step 4 uses a paired t-test (ttest_rel): every applicant is compared with their own counterfactual, so differences between applicants do not hide the effect. A finding needs both a significant p-value (the gap is not noise) and a relevant gap (more than 3 score points): with enough pairs, even a meaningless 0.1-point gap becomes “significant”.

The ratio of approval rates is the classic disparate impact measure. A common rule of thumb, the four-fifths rule from US employment law, flags a ratio below 0.8.

Step 1 and the test:

# Step 1: the sensitive attributes, and the pairs of values to compare.
FINDING = pytest.mark.xfail(strict=True, reason="bias found: see the lesson")
CASES = [
    pytest.param("v1", "gender", "Male", "Female", marks=FINDING, id="v1-gender"),
    pytest.param("v2", "gender", "Male", "Female", id="v2-gender"),
    pytest.param("v1", "name", "Sam Taylor", "Maria Taylor", marks=FINDING, id="v1-name"),
    pytest.param("v2", "name", "Sam Taylor", "Maria Taylor", id="v2-name"),
    pytest.param("v1", "zipCode", "60601", "10001", marks=FINDING, id="v1-zip"),
    pytest.param("v2", "zipCode", "60601", "10001", marks=FINDING, id="v2-zip"),
    pytest.param("v1", "age", 40, 60, marks=FINDING, id="v1-age"),
    pytest.param("v2", "age", 40, 60, marks=FINDING, id="v2-age"),
]


@pytest.mark.parametrize("model, attribute, value_a, value_b", CASES)
def test_changing_a_sensitive_attribute_does_not_change_the_score(api, applicants, model, attribute, value_a, value_b):
    gap, p_value = counterfactual_test(api, applicants, model, attribute, value_a, value_b)
    significant = p_value < SIGNIFICANCE and abs(gap) > MAX_SCORE_GAP
    assert not significant

Run it

pytest module-6/test_bias.py -v -s
v1 gender Male vs Female: approved 50% vs 35% (ratio 0.70), mean score gap +15.1, p = 3.7e-22   XFAIL
v2 gender Male vs Female: approved 42% vs 42% (ratio 1.00), mean score gap -0.3, p = 0.12      PASSED
v1 name Sam Taylor vs Maria Taylor: approved 42% vs 32% (ratio 0.76), mean score gap +10.1, p = 3.5e-20   XFAIL
v2 name Sam Taylor vs Maria Taylor: approved 42% vs 42% (ratio 1.00), mean score gap +0.2, p = 0.46       PASSED
v1 zipCode 60601 vs 10001: approved 55% vs 32% (ratio 0.59), mean score gap +14.4, p = 4.2e-24   XFAIL
v2 zipCode 60601 vs 10001: approved 65% vs 32% (ratio 0.50), mean score gap +20.4, p = 1.4e-44   XFAIL
v1 age 40 vs 60: approved 52% vs 20% (ratio 0.38), mean score gap +18.7, p = 1.4e-27            XFAIL
v2 age 40 vs 60: approved 62% vs 30% (ratio 0.48), mean score gap +20.1, p = 6.8e-45            XFAIL

========================= 2 passed, 6 xfailed

(Each line is printed above its PASSED or XFAIL in your output; they are combined here to fit.)

Read the findings

  • Version 1 is biased on gender and name. The same application from a woman gets 15 points less, and approval drops from 50% to 35%, a ratio of 0.70: below four-fifths. A name like Maria costs 10 points.
  • Version 2 fixed gender and name. The gaps are 0.3 and 0.2 points and not significant. Removing the attributes from the model worked for those attributes.
  • Version 2 is more biased on zip code than v1: approval in 10001 is half that in 60601 (ratio 0.50). The zip code is a proxy. If the zip codes with a penalty are mostly home to one ethnic group or to low incomes, the model discriminates indirectly, and removing gender and name made the remaining proxy more important. “We don’t use sensitive attributes” is not evidence of fairness.
  • Both versions penalise age 60 heavily (approval 20% and 30% versus 52% and 62% at age 40). Age may be a legitimate factor in some credit decisions, but it is also a protected characteristic. That is not for the tester to decide: the finding goes to the business and to legal, with these numbers.

The four xfail lines are your bias report: each one is a finding with evidence, and the test turns red the day it is fixed, so the fix gets noticed and the marker removed.

Exercise

  1. Add the combination “older women”: compare (Male, 40) with (Female, 60) for both models. What is the score gap, and is it the sum of the separate gaps?
  2. A colleague proposes: “Let’s just remove the zip code from the model.” What would you test after that change?
Show suggested answer
  1. Change two attributes in the counterfactual. A quick way is a helper that takes a dict of changes:

    group_a = [{**a, "gender": "Male", "age": 40} for a in applicants]
    group_b = [{**a, "gender": "Female", "age": 60} for a in applicants]
    

    For v1 the gap is 34.7 points, roughly 15 (gender) + 20 (age), and approval drops from 68% to 10%. For v2 it is 20.2 points, the age gap alone (approval 62% versus 30%). In this model the effects add up; in real models they can interact, which is why the syllabus suggests testing combinations: a model can be fair to women and fair to older people on average, and still unfair to older women.

  2. Rerun the whole disparate impact analysis: gender, name, age and look for the next proxy. With zip code gone, does another feature take over its role (city, employment years)? Check the overall performance too (removing a feature can lower accuracy for everyone), and compare the outcomes per group on a representative dataset, not only counterfactual pairs.

Exam-style questions

Quiz

1. Which is the correct order of the steps in disparate impact analysis?

  • A. Run the model; identify sensitive attributes; analyse; generate counterfactuals
  • B. Identify sensitive attributes; generate counterfactuals; run the model on them; analyse the results statistically
  • C. Generate counterfactuals; identify sensitive attributes; analyse; run the model
  • D. Analyse the training data; retrain; deploy; monitor
Show answer
B.
Quiz

2. A loan model does not use gender as a feature, but approves applicants from some zip codes far less often. Why can this still be bias?

  • A. Zip codes are always sensitive attributes
  • B. The zip code can be a proxy for a sensitive attribute, such as ethnicity or income
  • C. Models that do not use gender cannot be biased
  • D. Zip codes cause overfitting
Show answer
B.
Quiz

3. Which is an example of algorithmic bias according to the syllabus?

  • A. Training data from one country only
  • B. A credit-score threshold in loan approval that leads to unequal outcomes between groups
  • C. Wrong labels in the training data
  • D. A data pipeline that drops records
Show answer
B. A is data bias (unrepresentative); C is a labelling problem.

Your project so far

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

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