Machine learning with football · Chapter 13 · Fairness

Programming exercise

Audit the scouting shortlist under three rules, then hunt for the red flags in the data yourself.

Estimated time: 15 minutes · page 9 of 9

Audit the shortlist

The first script repeats the board's audit in plain Python. It builds the regulars of a league, marks the qualified, and checks three rules, a single cut, demographic parity and equality of opportunity. For each group it prints the shortlist rate and how many qualified players were picked.

  1. Pick a league on the board. The code follows it.
  2. Save it as audit.py and run python audit.py. How far apart are the groups under the single cut?
  3. Change "qualified" to the top quarter by minutes played. Does the picture change, and what does that say about who defines qualified?
import json
import sys
import urllib.request

sys.stdout.reconfigure(encoding="utf-8")  # player names with accents print on any terminal

API = "https://tactical-insights.com/api"
LEAGUE = 1  # change it to try another league
SHARE = 0.25  # the scouts' shortlist: the top quarter

def get(path):
    return json.load(urllib.request.urlopen(API + path))

table = get(f"/standings?league_id={LEAGUE}")
top_half = {t["team_id"] for t in table if t["rank"] <= len(table) // 2}
players = [p for p in get(f"/leagues/{LEAGUE}/player-stats")["players"] if p["minutes"] >= 450 and p["avg_rating"] is not None]
for p in players:
    p["group"] = "top half" if p["team_id"] in top_half else "bottom half"
    p["ga90"] = 90 * (p["goals"] + p["assists"]) / p["minutes"]

# "Qualified": the top quarter by goals plus assists per 90 minutes, whatever their club.
cut_ga = sorted((p["ga90"] for p in players), reverse=True)[int(len(players) * SHARE)]
for p in players:
    p["qualified"] = p["ga90"] > cut_ga

def audit(name, shortlisted):
    print(name)
    for group in ("top half", "bottom half"):
        g = [p for p in players if p["group"] == group]
        q = [p for p in g if p["qualified"]]
        picked = sum(1 for p in g if shortlisted(p))
        picked_q = sum(1 for p in q if shortlisted(p))
        print(f"   {group:<12} {len(g):>3} players   shortlisted {picked / len(g):>4.0%}   "
              f"qualified shortlisted {picked_q}/{len(q)} = {picked_q / max(len(q), 1):.0%}")
    print()

# 1. The scouts' rule: one rating cut for everyone.
cut = sorted((p["avg_rating"] for p in players), reverse=True)[int(len(players) * SHARE)]
audit(f"Same rating cut for all ({cut}):", lambda p: p["avg_rating"] > cut)

# 2. Demographic parity: a separate cut per group, so each group sends the same share.
cuts = {}
for group in ("top half", "bottom half"):
    ratings = sorted((p["avg_rating"] for p in players if p["group"] == group), reverse=True)
    cuts[group] = ratings[int(len(ratings) * SHARE)]
audit(f"Demographic parity (cuts {cuts}):", lambda p: p["avg_rating"] > cuts[p["group"]])

# 3. Equality of opportunity: cuts that shortlist the same share of qualified players in each group.
def cuts_for(rate):
    out = {}
    for group in ("top half", "bottom half"):
        q = sorted((p["avg_rating"] for p in players if p["group"] == group and p["qualified"]), reverse=True)
        out[group] = q[min(len(q) - 1, max(0, round(rate * len(q)) - 1))] - 1e-9
    return out
best = min((abs(sum(1 for p in players if p["avg_rating"] > cuts_for(r / 100)[p["group"]]) - SHARE * len(players)), r / 100)
           for r in range(5, 100))
eo = cuts_for(best[1])
audit(f"Equality of opportunity (cuts {{'top half': {eo['top half']:.2f}, 'bottom half': {eo['bottom half']:.2f}}}):",
      lambda p: p["avg_rating"] > eo[p["group"]])

Hunt for the red flags

The second script looks for the warning signs from the identifying-bias page. It checks missing ratings by group, ratings that rest on almost no minutes, how many regulars each group has, and how often the site's news mentions clubs from each half of the table.

  1. Run it. Which group has more players without a rating, and why might that be?
  2. Try another league. Is the news coverage just as lopsided?
  3. Name one decision a club could make with the shortlist where this bias would cost someone a chance.
import json
import sys
import urllib.request

sys.stdout.reconfigure(encoding="utf-8")  # club names with accents print on any terminal

API = "https://tactical-insights.com/api"
LEAGUE = 1  # change it to try another league

def get(path):
    return json.load(urllib.request.urlopen(API + path))

table = get(f"/standings?league_id={LEAGUE}")
top_half = {t["team_id"] for t in table if t["rank"] <= len(table) // 2}
group = lambda team_id: "top half" if team_id in top_half else "bottom half"
players = get(f"/leagues/{LEAGUE}/player-stats")["players"]

# 1. Missing values: who has no rating, and where?
print("players without a rating, by group:")
for g in ("top half", "bottom half"):
    mine = [p for p in players if group(p["team_id"]) == g]
    missing = sum(1 for p in mine if p["avg_rating"] is None)
    print(f"   {g:<12} {missing} of {len(mine)}")

# 2. Unexpected values: ratings resting on almost no minutes.
odd = sorted((p for p in players if p["avg_rating"] is not None and p["minutes"] < 90), key=lambda p: -p["avg_rating"])[:3]
print("\nhighest ratings from under 90 minutes:")
for p in odd:
    print(f"   {p['player']:<24} {p['avg_rating']}  after {p['minutes']} minutes")

# 3. Skew: does one group dominate the data a scout would see?
print("\nplayers with 450+ minutes, by group:")
for g in ("top half", "bottom half"):
    print(f"   {g:<12} {sum(1 for p in players if group(p['team_id']) == g and p['minutes'] >= 450)}")

# 4. Reporting bias: whose clubs make the news?
news = get("/news?limit=200")
names = {t["team_id"]: t["team"] for t in table}
mentions = {g: 0 for g in ("top half", "bottom half")}
for story in news:
    for team in story.get("teams") or []:
        if team["id"] in names:
            mentions[group(team["id"])] += 1
print(f"\nclub mentions in the latest {len(news)} news stories: "
      + ", ".join(f"{g} {n}" for g, n in mentions.items()))

Check yourself

In the first script, which rule gives qualified players from both groups about the same chance?
The second script finds that news stories mention top-half clubs far more often. Which bias would a model trained on those stories inherit?

What the course adds up to

Back in chapter 2 a line went through the league table. Since then the course has built logistic regression, classifiers, prepared features, learned embeddings, neural networks, a language model, a small AutoML and a production pipeline, all on this season's football. Fairness is the last check and the one that matters most once a model decides about people. Look group by group, ask who defined the label, and choose your definition of fair on purpose.

Leagues