Artificial Intelligence Fundamentals / Use AI Responsibly

Evaluate fairness across groups

Lesson 22 of 26. Open to read. No account needed.

One Score Can Hide a Gap

Every score so far was a single number for the whole test set. A single number is an average, and an average can hide a group for whom the model works badly, especially if that group is small. If a model serves 900 customers well and 100 poorly, its overall score still looks good, and the 100 are the ones who pay for it.

This lesson shows how to look for such gaps by calculating a metric separately for each group, and how to interpret what you find.

Two Kinds of Harm

The Fairlearn project, which builds tools for assessing fairness in machine learning, describes two kinds of harm a system can cause:

  • Allocation harms: the system extends or withholds opportunities, resources or information, for example who is offered a loan, a job interview or urgent support.
  • Quality-of-service harms: the system works less well for some groups than for others, for example speech recognition that makes more mistakes with some accents, even when nothing is formally allocated.

Fairlearn also stresses that fairness is sociotechnical: it depends on the people affected, the setting and the decisions a system feeds into, not only on numbers. A metric can reveal a gap; it cannot say on its own whether the gap is acceptable, what caused it or what the right response is. Those need judgement, knowledge of the context and, ideally, the people affected.

Metrics per Group

The basic technique is simple: calculate the same metric separately for each group, which Fairlearn calls a disaggregated metric, and put the results side by side with the overall value and each group's size.

On the left, one overall recall of 0.61 for all test tickets. On the right, the same test tickets split by region: North, 450 tickets, recall 0.69; South, 50 tickets, recall 0.12. The overall number sits close to North's because North makes up most of the data, hiding South's much lower recall.

Compare the bar on the left with the two on the right. The overall value is pulled towards the larger group. Only the per-group values show that the smaller group is served much worse, and the group sizes underneath show how much evidence each value rests on.

Two cautions apply:

  • Small groups give rough estimates. If a group has 8 positive cases, each one changes its recall by 0.125. Report group sizes and treat small-group results as signals to investigate, not precise measurements.
  • A gap is a symptom, not an explanation. It could come from too few examples of the group, from a different pattern in that group, from measurement problems in the data or from labels that were themselves unfair. Finding the cause comes next.

Exercise: Find a Hidden Gap

A fictional support team uses a model to flag urgent tickets, so they are answered first: missing an urgent ticket means a customer waits too long, a quality-of-service harm. The tickets come from two regions, North and South. The data is generated, and the regions are fictional.

Starting state: the course environment, active in your terminal. The script generates its own data.

  1. Create the exercise folder. macOS and Linux:

    mkdir -p ~/ai-practice/group-recall
    cd ~/ai-practice/group-recall
    

    Windows PowerShell:

    mkdir $HOME\ai-practice\group-recall
    cd $HOME\ai-practice\group-recall
    

    Save this as group_recall.py in that folder:

    """Compare a model's recall overall and for two synthetic regions."""
    import numpy as np
    import pandas as pd
    from sklearn.linear_model import LogisticRegression
    from sklearn.metrics import recall_score
    from sklearn.model_selection import train_test_split
    
    rng = np.random.default_rng(7)
    
    
    def make_region(name, size, key_feature):
        """Generated tickets: in each region, a different feature signals an urgent ticket."""
        data = pd.DataFrame({"wait_days": rng.normal(0, 1, size), "messages": rng.normal(0, 1, size)})
        data["urgent"] = (data[key_feature] + rng.normal(0, 0.3, size) > 1).astype(int)
        data["region"] = name
        return data
    
    
    tickets = pd.concat([make_region("North", 1800, "wait_days"), make_region("South", 200, "messages")], ignore_index=True)
    features = ["wait_days", "messages"]  # the region itself is not a feature
    train, test = train_test_split(tickets, random_state=7, stratify=tickets["region"])
    
    model = LogisticRegression().fit(train[features], train["urgent"])
    test = test.assign(predicted=model.predict(test[features]))
    
    print(f"Overall recall: {recall_score(test['urgent'], test['predicted']):.2f}")
    for region, part in test.groupby("region"):
        recall = recall_score(part["urgent"], part["predicted"])
        print(f"{region}: {len(part)} test tickets, {part['urgent'].sum()} urgent, recall {recall:.2f}")
    
  2. Run it:

    python group_recall.py
    

    Output, which should match exactly:

    Overall recall: 0.61
    North: 450 test tickets, 54 urgent, recall 0.69
    South: 50 test tickets, 8 urgent, recall 0.12
    

How the Script Works

Generating the regions. make_region creates one region's tickets with two features: wait_days, how long the customer has waited, and messages, how many messages they have sent, both as standardised numbers around 0. A ticket is urgent when the region's key feature, plus a little random noise, is above 1. In North the key feature is waiting time; in South it is the number of messages, perhaps because South's customers chase their tickets by writing. North has 1,800 tickets and South 200.

Training. pd.concat joins the regions into one table. The model uses only the two features; the region is not given to it. The split is stratified by region, so both parts keep the 9-to-1 balance.

Per-group evaluation. test.assign(predicted=...) adds the predictions as a column. groupby("region") then hands over each region's rows in turn, and recall is calculated separately for each, beside the number of tickets and of urgent tickets.

What the results show. Overall recall, 0.61, looks moderate. Split by region, the model finds about 69% of North's urgent tickets but only 1 of South's 8. South's 8 urgent cases are too few for a precise figure, but the gap is far too large to be chance alone. The cause is visible in how the data was generated: the model learned mostly from North, where waiting time signals urgency, and South's urgent tickets show up in a different feature. In real data you would not know the cause in advance; you would have to investigate.

Success: the output matches; you can explain why the overall recall hides South's result and why the group sizes matter for interpreting it.

If something differs:

What you seeLikely causeNext step
Different numbersThe seed 7 or a size was changedRestore the values shown
A warning that recall is ill-definedA group's test part has no urgent tickets, usually after changing sizesRestore the sizes; very small groups can have no positive cases
KeyError: 'region'The region column line in make_region was changedRestore make_region exactly
ModuleNotFoundErrorThe course environment is not activeActivate it and rerun
  1. Clean up. macOS and Linux:

    cd ~/ai-practice
    ls
    rm -rf group-recall
    ls
    

    Windows PowerShell:

    cd $HOME\ai-practice
    ls
    Remove-Item -Recurse group-recall
    ls
    

    Check that the first ls shows group-recall before removing it. Do the independent task first.

Independent task: a colleague suggests that the fix is simply more South data. Change make_region("South", 200, "messages") to make_region("South", 1800, "messages"), so that both regions are equally represented. Predict what will happen to each region's recall, then run the script and explain the result.

Check Your Understanding

  1. Explain how a model can have a high overall score and still cause a quality-of-service harm.
  2. Is each of these an allocation harm or a quality-of-service harm? a) A loan model approves fewer applications from one group. b) A transcription tool makes more mistakes for some accents.
  3. Why should a per-group report always include group sizes?

Answer and Reasoning

Independent task

The output becomes:

Overall recall: 0.24
North: 450 test tickets, 54 urgent, recall 0.30
South: 450 test tickets, 74 urgent, recall 0.20

The gap narrows, but mainly because North's recall collapses from 0.69 to 0.30; South improves only from 0.12 to 0.20. More data did not fix the problem, because the problem is not a shortage of examples: the two regions signal urgency in different ways, and a single linear model that is not told the region cannot follow both patterns, so it ends up following neither well.

A real fix starts by understanding the cause, for example by asking the South team how urgent tickets look there, then trying designs that can represent both patterns, such as including the region where that is appropriate or using a separate model per region, and checking every group again. Narrowing a gap by making the better-served group worse helps nobody.

Understanding check

  1. The overall score is an average dominated by the largest groups. If a small group is served badly, the average barely moves, so the harm stays invisible until the metric is calculated per group.
  2. a) Allocation: an opportunity is withheld. b) Quality of service: the tool works less well for some people, although nothing is allocated.
  3. A metric on a small group is a rough estimate: with 8 positive cases, each one changes recall by 0.125. Group sizes show how much evidence each value rests on and prevent over-reading small differences, or dismissing large ones.

References

Study this course with an account

Course access adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

See course access

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy