Machine learning with football · Chapter 4 · Classification

Programming exercise

Thresholds, the confusion matrix, AUC and three classes in plain Python, on matches the model has never seen.

Estimated time: 15 minutes · page 7 of 7

Classify the test matches

The first script reuses chapter 3's honest setup. It keeps back the latest 20% of matches as a test and describes each team only by the matches before. Then it scores the test matches and prints the confusion matrix, accuracy, precision and recall at five thresholds, plus the AUC.

  1. Pick a league on the board. The code follows it.
  2. Save it as classify.py and run python classify.py.
  3. Find the threshold with the best accuracy, and the one with the best precision. Are they the same?
  4. Compare the AUC with the board's. The board scores every match and peeks, so it should look better.
import json
import math
import urllib.request

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))

# The honest setup from chapter 3: the latest 20% of matches are the test,
# and each team's goal difference per game comes from the other 80% only.
played = sorted(get(f"/fixtures?league_id={LEAGUE}&status=FT&limit=200"), key=lambda m: m["fixture_date"])
cut = int(len(played) * 0.8)
train_matches, test_matches = played[:cut], played[cut:]

goals, games = {}, {}
for m in train_matches:
    for team, scored, conceded in ((m["home_team_id"], m["home_goals"], m["away_goals"]),
                                   (m["away_team_id"], m["away_goals"], m["home_goals"])):
        goals[team] = goals.get(team, 0) + scored - conceded
        games[team] = games.get(team, 0) + 1
gd = {team: goals[team] / games[team] for team in goals}

def examples(matches):
    return [(gd[m["home_team_id"]] - gd[m["away_team_id"]], 1 if m["home_goals"] > m["away_goals"] else 0)
            for m in matches if m["home_team_id"] in gd and m["away_team_id"] in gd]

train, test = examples(train_matches), examples(test_matches)

def sigmoid(z):
    return 1 / (1 + math.exp(-z))

w, b = 0.0, 0.0
for _ in range(500):
    errors = [sigmoid(w * x + b) - y for x, y in train]
    w -= 0.5 * sum(e * x for e, (x, _) in zip(errors, train)) / len(train)
    b -= 0.5 * sum(errors) / len(train)

# The model's home win chance for every test match, next to what happened.
scored = [(sigmoid(w * x + b), y) for x, y in test]

def confusion(threshold):
    tp = sum(1 for p, y in scored if p > threshold and y == 1)
    fp = sum(1 for p, y in scored if p > threshold and y == 0)
    fn = sum(1 for p, y in scored if p <= threshold and y == 1)
    tn = sum(1 for p, y in scored if p <= threshold and y == 0)
    return tp, fp, fn, tn

def ratio(a, b):
    return f"{a / b:.2f}" if b else " n/a"

print(f"{len(test)} test matches, {sum(y for _, y in scored)} home wins\n")
print("threshold   TP  FP  FN  TN   accuracy  precision  recall")
for threshold in (0.3, 0.4, 0.5, 0.6, 0.7):
    tp, fp, fn, tn = confusion(threshold)
    print(f"   {threshold:.1f}     {tp:3} {fp:3} {fn:3} {tn:3}     {ratio(tp + tn, len(scored))}      {ratio(tp, tp + fp)}     {ratio(tp, tp + fn)}")

# AUC: how often a real home win got a higher score than a match without one.
wins = [p for p, y in scored if y == 1]
others = [p for p, y in scored if y == 0]
pairs = sum(1 if a > o else 0.5 if a == o else 0 for a in wins for o in others)
print(f"\nAUC = {pairs / (len(wins) * len(others)):.2f}   (0.5 is a coin flip, 1.0 is perfect)")

Three classes

The second script builds the multi-class model from the previous page, two logistic regressions one after the other. It picks the most likely result for every test match and prints the accuracy, the 3 × 3 confusion matrix, and a baseline that always says "home win".

  1. Run it. How often does the model predict a draw?
  2. Does it beat the baseline? Try three leagues.
  3. Change it to predict a draw whenever the draw chance is above 28%. What happens to the accuracy, and to the draw row?
import json
import math
import urllib.request

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))

played = sorted(get(f"/fixtures?league_id={LEAGUE}&status=FT&limit=200"), key=lambda m: m["fixture_date"])
cut = int(len(played) * 0.8)
train_matches, test_matches = played[:cut], played[cut:]

goals, games = {}, {}
for m in train_matches:
    for team, scored, conceded in ((m["home_team_id"], m["home_goals"], m["away_goals"]),
                                   (m["away_team_id"], m["away_goals"], m["home_goals"])):
        goals[team] = goals.get(team, 0) + scored - conceded
        games[team] = games.get(team, 0) + 1
gd = {team: goals[team] / games[team] for team in goals}

HOME, DRAW, AWAY = 0, 1, 2
NAMES = ["home win", "draw", "away win"]

def result(m):
    return HOME if m["home_goals"] > m["away_goals"] else DRAW if m["home_goals"] == m["away_goals"] else AWAY

def examples(matches):
    return [(gd[m["home_team_id"]] - gd[m["away_team_id"]], result(m))
            for m in matches if m["home_team_id"] in gd and m["away_team_id"] in gd]

train, test = examples(train_matches), examples(test_matches)

def sigmoid(z):
    return 1 / (1 + math.exp(-z))

def fit(data):
    """Logistic regression on (x, 0 or 1) pairs, as in chapter 3."""
    w, b = 0.0, 0.0
    for _ in range(500):
        errors = [sigmoid(w * x + b) - y for x, y in data]
        w -= 0.5 * sum(e * x for e, (x, _) in zip(errors, data)) / len(data)
        b -= 0.5 * sum(errors) / len(data)
    return w, b

# Three classes as two yes or no questions.
# 1. Home win, or not?
w1, b1 = fit([(x, 1 if r == HOME else 0) for x, r in train])
# 2. Among the matches the home side did not win: away win, or draw?
w2, b2 = fit([(x, 1 if r == AWAY else 0) for x, r in train if r != HOME])

def chances(x):
    home = sigmoid(w1 * x + b1)
    away_given_not_home = sigmoid(w2 * x + b2)
    return [home, (1 - home) * (1 - away_given_not_home), (1 - home) * away_given_not_home]

# Predict the most likely result for every test match.
matrix = [[0, 0, 0] for _ in range(3)]  # rows: predicted, columns: what happened
for x, r in test:
    c = chances(x)
    matrix[c.index(max(c))][r] += 1

correct = sum(matrix[i][i] for i in range(3))
always_home = sum(1 for _, r in test if r == HOME)
print(f"{len(test)} test matches")
print(f"model accuracy        {correct / len(test):.0%}")
print(f"always 'home win'     {always_home / len(test):.0%}\n")
print("rows: predicted, columns: real     home win   draw   away win")
for i in range(3):
    print(f"{NAMES[i]:>36}   {matrix[i][0]:8}   {matrix[i][1]:4}   {matrix[i][2]:8}")

Check yourself

Which threshold gives the highest recall in the first script's table?
In some leagues the three-class model is no more accurate than always saying "home win". Why might that still be a fine model?

What the chapter adds up to

A probability becomes a decision only once you choose a threshold, and the right threshold depends on what each mistake costs. The metrics tell you what you're trading. Chapter 5 goes back a step to the data itself, starting with how to prepare numerical features like goals, shots and xG before a model sees them.

Leagues