Machine learning with football · Chapter 12 · AutoML

Programming exercise

Write a small AutoML in plain Python: search every feature set and regularization rate, then test the winner once.

Estimated time: 15 minutes · page 4 of 4

An AutoML of your own

The first script is a small AutoML in plain Python. It computes team numbers from the oldest 60% of matches, then tries every non-empty set of four features with three amounts of L2, 45 models in all. It ranks them on the next 20% and tests only the winner on the latest 20%, once, next to the smoke-test baseline.

  1. Pick a league on the board. The code follows it.
  2. Save it as automl.py and run python automl.py. Does the winner beat the flat guess on the test matches?
  3. Set LABEL to "over 2.5". Is there any signal for that question?
  4. Add a fifth feature of your own, such as goals for per game, and search again.
import itertools
import json
import math
import urllib.request

API = "https://tactical-insights.com/api"
LEAGUE = 1  # change it to try another league
LABEL = "home win"  # or "over 2.5"

played = sorted(json.load(urllib.request.urlopen(f"{API}/fixtures?league_id={LEAGUE}&status=FT&limit=200")),
                key=lambda m: m["fixture_date"])

# Oldest 60% to train, next 20% to choose the model, latest 20% to test the winner once.
a, b = int(len(played) * 0.6), int(len(played) * 0.8)
train_m, valid_m, test_m = played[:a], played[a:b], played[b:]

# Team numbers from the training matches only: goal difference and xG per game.
stats = {}
for m in train_m:
    for team, gd, xg in ((m["home_team_id"], m["home_goals"] - m["away_goals"], m["home_xg"] or 0),
                         (m["away_team_id"], m["away_goals"] - m["home_goals"], m["away_xg"] or 0)):
        s = stats.setdefault(team, [0, 0, 0])
        s[0] += gd
        s[1] += xg
        s[2] += 1

FEATURES = ["home goal difference", "away goal difference", "home xG", "away xG"]

def rows(matches):
    out = []
    for m in matches:
        h, w = stats.get(m["home_team_id"]), stats.get(m["away_team_id"])
        if not h or not w:
            continue
        x = [h[0] / h[2], w[0] / w[2], h[1] / h[2], w[1] / w[2]]
        if LABEL == "home win":
            y = 1 if m["home_goals"] > m["away_goals"] else 0
        else:
            y = 1 if m["home_goals"] + m["away_goals"] > 2.5 else 0
        out.append((x, y))
    return out

train, valid, test = rows(train_m), rows(valid_m), rows(test_m)

def sigmoid(z):
    return 1 / (1 + math.exp(-max(-30, min(30, z))))

def fit(data, cols, lam, steps=800, rate=0.3):
    w, bias = [0.0] * len(cols), 0.0
    for _ in range(steps):
        g, gb = [0.0] * len(cols), 0.0
        for x, y in data:
            e = sigmoid(bias + sum(wi * x[c] for wi, c in zip(w, cols))) - y
            gb += e
            for i, c in enumerate(cols):
                g[i] += e * x[c]
        bias -= rate * gb / len(data)
        w = [wi - rate * (gi / len(data) + 2 * lam * wi) for wi, gi in zip(w, g)]
    return w, bias

def log_loss(data, cols, model):
    w, bias = model
    total = 0.0
    for x, y in data:
        p = sigmoid(bias + sum(wi * x[c] for wi, c in zip(w, cols)))
        total -= y * math.log(p) + (1 - y) * math.log(1 - p)
    return total / len(data)

# The search: every non-empty set of features, with three amounts of L2. AutoML does this, and more, for you.
board = []
for k in range(1, len(FEATURES) + 1):
    for cols in itertools.combinations(range(len(FEATURES)), k):
        for lam in (0, 0.01, 0.1):
            model = fit(train, cols, lam)
            board.append((log_loss(valid, cols, model), cols, lam, model))
board.sort(key=lambda r: r[0])

rate = sum(y for _, y in train) / len(train)
flat = -sum(y * math.log(rate) + (1 - y) * math.log(1 - rate) for _, y in valid) / len(valid)
print(f"label: {LABEL}. {len(board)} models tried on {len(train)} training and {len(valid)} validation matches")
print(f"smoke test: always guessing {rate:.0%} scores {flat:.4f} on validation\n")
print("rank  validation  lambda  features")
for i, (loss, cols, lam, _) in enumerate(board[:5], 1):
    print(f"{i:>4}  {loss:.4f}      {lam:<6}  {', '.join(FEATURES[c] for c in cols)}")

loss, cols, lam, model = board[0]
test_flat = -sum(y * math.log(rate) + (1 - y) * math.log(1 - rate) for _, y in test) / len(test)
print(f"\nthe winner on the test matches, once: {log_loss(test, cols, model):.4f} (always {rate:.0%}: {test_flat:.4f})")

Check the types

The second script does what a no-code tool does on import. It looks at the values in each column of the match data and guesses a type, then compares the guess with what the column really is and marks the ones to fix.

  1. Run it. Which columns does the guesser get wrong, and why?
  2. Improve guess so it recognises dates.
  3. Which column has only one value here, and is it any use to a model?
import json
import urllib.request

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

played = json.load(urllib.request.urlopen(f"{API}/fixtures?league_id={LEAGUE}&status=FT&limit=200"))

def guess(values):
    """What a no-code AutoML tool does on import: look at the values and guess a type."""
    present = [v for v in values if v is not None]
    if not present:
        return "empty"
    if all(isinstance(v, bool) for v in present):
        return "boolean"
    if all(isinstance(v, (int, float)) for v in present):
        return "numeric"
    if len(set(present)) <= 30:
        return "categorical"
    return "text"

# Columns a model might use, with what a person who knows football would say they are.
TRUTH = {
    "home_team_id": "categorical (an ID: club 8 is not twice club 4)",
    "away_team_id": "categorical (an ID)",
    "matchday": "numeric (how far into the season)",
    "home_goals": "numeric",
    "away_goals": "numeric",
    "home_xg": "numeric",
    "venue": "categorical",
    "home_team": "categorical",
    "status": "categorical (one value here: every match is finished)",
    "fixture_date": "a date: split it into features such as weekday and hour",
}

print(f"{'column':<14} {'tool guesses':<13} {'distinct':>8}   really")
for column, truth in TRUTH.items():
    values = [m.get(column) for m in played]
    kind = guess(values)
    flag = "" if truth.startswith(kind) else "   <- fix this"
    print(f"{column:<14} {kind:<13} {len(set(values)):>8}   {truth}{flag}")

Check yourself

The first script picks the winner on the validation set and only then scores it on the test set. Why not pick on the test set?
The second script's type guesser calls fixture_date "text". What should it become?

What the chapter adds up to

AutoML hands the search to software: features, algorithms, hyperparameters, all scored on held-back data. It saves time and gives a quick answer on whether the data has signal. It can't frame the problem, fix the labels or explain itself, and on small, noisy data like a season of football it can't conjure signal that isn't there. Google's course closes with fairness, the question of who a model works well for.

Leagues