Home › Theme A › A4 › A4.4 › A4.4.1

A4.4.1 The ethics of machine learning

SL + HLCommand term: Discuss

1. How biased training data creates a biased model

A company trains a model to screen job applicants using 10 years of its own past hiring decisions. In reality, people in group A and group B are equally skilled. But in the past, group B applicants were held to a tougher standard. Change the settings, retrain, and compare how the model treats equally qualified people from each group.

Results on 2,000 new applicants (equally skilled groups)
👤 Group A👤 Group B
Selected for interview
Qualified but wrongly rejected
Model accuracy

2. Ethics case explorer

Choose a scenario. Click the ethical issues you think it raises, then click Check to compare with an expert view and see arguments on both sides.

3. Machine learning in online communication

Which ethical issue does each situation mainly show? Score: 0 /

4. Build a "Discuss" answer

Question: Discuss whether schools should use AI proctoring software (webcam monitoring and automatic cheating detection) for online exams. Sort each point. Score: 0 /

ShelfWise AI · Hands-on lab A4.4.1: Auditing a model for bias. ShelfWise wants AI to choose who gets a free premium membership. It learns from past decisions by staff, but those decisions were unfair to members from District B.

In this lab you practise how biased training data creates biased models, demographic parity and equal opportunity, and why removing a sensitive feature may not be enough. Work through the sections in order: run it, read it, change it, then extend it.

1. Set up in PyCharm

  1. Open PyCharm and choose New Project (a pure Python project; any recent Python 3 works). Name it shelfwise_ai.
  2. Right-click the project folder → New → Python File, and give it the file name shown below.
  3. Press Copy code below and paste it into the empty file (or press Download .py and drag the file into the project).
  4. Right-click inside the editor and choose Run (Windows Shift+F10, Mac Ctrl+R). The output appears in the Run window at the bottom.
  5. No extra libraries are needed: the lab uses only Python's built-in modules, so you can see exactly how the algorithm works.

2. Copy and run the program

File: lab_a4_4_1.py
# ShelfWise AI - Lab A4.4.1: auditing a model for bias
# ShelfWise wants a model to decide who gets a free "premium membership" offer.
# It learns from past decisions made by staff, which were biased against District B.
import random

EXTRA = "district"       # extra feature the model may see: "district", "area" (postcode area) or "none"
K = 7
random.seed(21)

def member():
    district = random.choice("AB")
    engagement = random.uniform(0, 10)                       # how actively they use the library
    # postcode area is linked to district (a proxy): mostly 1 in A, mostly 2 in B
    area = 1 if (district == "A") == (random.random() < 0.85) else 2
    deserves = engagement > 5                                # the fair answer
    past_yes = deserves and not (district == "B" and random.random() < 0.6)   # staff bias
    return {"district": district, "engagement": engagement, "area": area,
            "deserves": deserves, "past_yes": past_yes}

history = [member() for _ in range(400)]
new = [member() for _ in range(400)]

def features(m):
    f = [m["engagement"] / 10]
    if EXTRA == "district":
        f.append(1 if m["district"] == "B" else 0)
    elif EXTRA == "area":
        f.append(m["area"] - 1)
    return f

def predict(m):
    x = features(m)
    near = sorted(history, key=lambda h: sum((a - b) ** 2 for a, b in zip(features(h), x)))[:K]
    return sum(h["past_yes"] for h in near) * 2 > K

decisions = [(m, predict(m)) for m in new]

print(f"Model trained on past staff decisions; extra feature = {EXTRA}\n")
print(f"{'group':12}{'members':>8}{'offered':>9}{'offer rate':>12}{'deserving offered':>19}")
rates = {}
for g in "AB":
    rows = [(m, p) for m, p in decisions if m["district"] == g]
    offered = sum(p for _, p in rows)
    deserving = [(m, p) for m, p in rows if m["deserves"]]
    tpr = sum(p for _, p in deserving) / len(deserving)          # equal opportunity: true positive rate
    rates[g] = (offered / len(rows), tpr)
    print(f"District {g:3}{len(rows):8}{offered:9}{offered / len(rows):12.0%}{tpr:19.0%}")

acc = sum(p == m["deserves"] for m, p in decisions) / len(decisions)
print(f"\nDemographic parity gap (offer rate A - B): {rates['A'][0] - rates['B'][0]:+.0%}")
print(f"Equal opportunity gap (deserving offered A - B): {rates['A'][1] - rates['B'][1]:+.0%}")
print(f"Agreement with the FAIR answer (engagement > 5): {acc:.0%}")

3. Expected output

The program uses a fixed random seed, so with the same settings you should see exactly this output.

Model trained on past staff decisions; extra feature = district

group        members  offered  offer rate  deserving offered
District A       206       97         47%                99%
District B       194       22         11%                22%

Demographic parity gap (offer rate A - B): +36%
Equal opportunity gap (deserving offered A - B): +77%
Agreement with the FAIR answer (engagement > 5): 80%

4. Read the output

Answer each question from your own output before you open the answer.

What share of deserving District B members did the model offer premium membership to?
Only 22%, compared with 99% in District A. The model copied the historical bias in its training labels.
What is the difference between the two fairness measures?
Demographic parity compares offer rates for all members of each group; equal opportunity compares offer rates only among members who deserve an offer.
The model agrees with the fair answer 80% of the time. Why is accuracy not enough?
The errors are not spread evenly: almost all fall on District B. A model can look accurate overall while being unfair to a group.

5. Change it and predict

For each change: write down your prediction first, then edit the setting at the top of the program, run it, and compare. Change the setting back before the next task.

Task 1. Change EXTRA = "district" → EXTRA = "area"
Set EXTRA = "area" (remove district, keep postcode area). Is the model now fair?

Check your prediction

No. The equal opportunity gap is still +38%. Postcode area is a proxy for district, so the model can still learn the bias. Simply deleting the sensitive feature is not enough.

Output with this change:

Model trained on past staff decisions; extra feature = area

group        members  offered  offer rate  deserving offered
District A       206       91         44%                93%
District B       194       55         28%                55%

Demographic parity gap (offer rate A - B): +16%
Equal opportunity gap (deserving offered A - B): +38%
Agreement with the FAIR answer (engagement > 5): 87%

Task 2. Change EXTRA = "district" → EXTRA = "none"
Set EXTRA = "none". What happens?

Check your prediction

The gaps almost disappear (-3% and +1%), and agreement with the fair answer rises to 93%, because the model now only uses engagement. But the labels are still biased: in real data, bias can hide in many features, so audits must be repeated.

Output with this change:

Model trained on past staff decisions; extra feature = none

group        members  offered  offer rate  deserving offered
District A       206       84         41%                86%
District B       194       85         44%                85%

Demographic parity gap (offer rate A - B): -3%
Equal opportunity gap (deserving offered A - B): +1%
Agreement with the FAIR answer (engagement > 5): 93%

6. Extended activity: Write a fairness audit for ShelfWise

A longer project for homework or a double lesson. Save it as a new file so you keep the original.

  1. Add a third group (District C) with its own historical bias, and report both fairness measures for all three districts.
  2. Try a fix: train on corrected labels (use 'deserves' instead of 'past_yes'), or reweight District B examples. Measure the effect.
  3. Research the ethical issues of accountability, transparency and consent for this system.
  4. Write a short audit report: findings with numbers, causes, the fix you recommend, and who should be accountable.

Success criteria

  • Both fairness measures are reported for every group.
  • Your fix is tested, not just suggested.
  • Your report discusses accountability and transparency.

Learning objectives

By the end of this page you should be able to:

  1. Discuss accountability, algorithmic fairness, bias and transparency in machine learning.
  2. Discuss consent, privacy and security in machine learning.
  3. Discuss the environmental and societal impact of machine learning.
  4. Explain the challenges posed by bias in training data.
  5. Discuss the ethics of machine learning in online communication, including misinformation, harassment, anonymity and privacy.

Nine ethical issues

IssueThe question it raisesExample
AccountabilityWho is responsible when an ML system causes harm: developer, company, user?A self-driving car injures a pedestrian.
Algorithmic fairnessDoes the system treat individuals and groups equitably?Loan approval rates differ by ethnicity for equally qualified applicants.
BiasDoes the model reproduce prejudice from data or design?Face recognition is less accurate for darker-skinned women.
ConsentDid people agree to their data being collected and used this way?Photos scraped from social media to train face recognition.
Environmental impactWhat energy, water and hardware does training and running models use?Training very large models in data centres.
PrivacyIs personal data protected? Can the model reveal or infer private information?Inferring health or sexuality from online behaviour.
SecurityCan the system be attacked, fooled or misused?Stickers on a stop sign fool a car's vision system; data breaches.
Societal impactEffects on jobs, democracy, inequality, mental health.Automation replacing jobs; filter bubbles.
TransparencyCan people understand and challenge how decisions are made?A "black box" rejects a loan with no explanation.

Bias in training data

  • Historical bias: the data records past unfair decisions, and the model learns to repeat them.
  • Sampling / representation bias: some groups are under-represented, so the model is less accurate for them.
  • Measurement / labelling bias: labels reflect human judgement or flawed measurement (e.g. recorded arrests ≠ actual crime).
  • Proxy variables: removing a protected attribute (e.g. ethnicity) doesn't remove bias if other features (postcode, school) are closely linked to it.
  • Feedback loops: biased predictions create biased new data (more patrols → more recorded crime → more patrols).
  • Mitigations: diverse, representative data; auditing data and outcomes for each group; fairness metrics; human oversight; transparency and the right to appeal; diverse development teams.

ML in online communication

  • Misinformation: recommendation algorithms amplify engaging (often false or extreme) content; generative AI creates deepfakes and fake news at scale.
  • Bias: moderation or ranking algorithms treat some groups, languages or viewpoints unfairly.
  • Online harassment: AI can detect abuse, but also generate it (bots, deepfake abuse); moderation errors leave victims unprotected.
  • Anonymity: protects whistleblowers and vulnerable users, but makes it harder to hold abusers accountable; ML can also de-anonymise people.
  • Privacy: platforms profile users from their behaviour for advertising, often without meaningful consent.

How to "Discuss"

Present a balanced review: benefits and concerns, supported by the scenario; consider different stakeholders (users, companies, society, minorities); suggest mitigations; and end with a justified conclusion.

Use the 中文 button at the top to show or hide the Chinese terms.

Term中文Meaning

Choose an answer. You get instant feedback.

Score: 0 /

Write your answer first, then reveal the markscheme. These are exam-style practice questions written for this site.

1. Explain how bias in training data can lead to unfair outcomes from a machine learning model. [3]

The model learns patterns from the training data [1]; if the data reflects historical discrimination / under-represents some groups, these patterns are learned as if they were correct [1]; so the model reproduces / amplifies the bias, e.g. rejecting qualified applicants from one group, and it may appear objective, so the unfairness is hidden [1].

2. A company removes the "gender" column from its hiring data to make its model fair. Explain why the model might still be biased. [2]

Other features may act as proxies for gender, e.g. membership of certain clubs, career gaps, previous job titles [1]; the model can still learn the historical bias through these correlated features / the labels themselves are still biased [1].

3. Outline two ethical issues raised by the use of machine learning to moderate content on social media. [4]

Award [1] for each issue and [1] for its outline, up to two: bias [1]: some dialects / languages / groups may be wrongly flagged more often [1]; transparency [1]: users may not know why posts were removed, and can't appeal effectively [1]; accountability [1]: unclear who is responsible for wrongful removal or failure to remove harmful content [1]; freedom of expression / societal impact [1]: over-removal can silence legitimate speech [1]; harassment [1]: failures leave victims unprotected [1].

4. A police force plans to use live facial recognition cameras in a city centre. Discuss the ethical implications of this plan. [8]

Level-style marking. A balanced answer may include: benefits: faster identification of wanted / missing people; deterrence of crime; efficient use of police resources. Concerns: privacy: mass surveillance of innocent people; consent: people can't opt out in public spaces; bias: lower accuracy for some ethnic groups and women, leading to wrongful stops; accountability: who is responsible for misidentification; transparency: how the watchlist is created and how decisions are made; security: the biometric database could be hacked; societal impact: chilling effect on protest / freedom of assembly; feedback loops in policing. Mitigations: independent audits of accuracy by group, human verification before action, strict data retention limits, public consultation and legal oversight. Conclusion: a justified judgement, e.g. acceptable only with strong safeguards and limited use. [7–8] balanced, well-developed, uses scenario, justified conclusion; [5–6] good range, mostly balanced; [3–4] some issues, limited development / one-sided; [1–2] superficial.

5. Describe one environmental impact of machine learning, and one way it could be reduced. [2]

Training and running large models uses large amounts of electricity (and water for cooling data centres), contributing to carbon emissions / e-waste from hardware [1]; reduce by using renewable-powered data centres / more efficient hardware and smaller models / reusing pre-trained models (transfer learning) instead of training from scratch [1].