Machine learning with football · Chapter 11 · Production ML systems

Programming exercise

Freeze a model and watch it go stale, then run a small test suite against the live data.

Estimated time: 15 minutes · page 8 of 8

Freeze a model

The first script repeats the board's training experiment in plain Python. It trains chapter 9's goals model once on the first three matchdays and retrains a second copy before every matchday, then scores both on each new round.

  1. Pick a league on the board. The code follows it.
  2. Save it as stale.py and run python stale.py. Does the gap grow as the season goes on?
  3. Set FROZEN_AFTER to 6. Does a static model trained on more matches hold up longer?
import json
import math
import urllib.request

API = "https://tactical-insights.com/api"
LEAGUE = 1  # change it to try another league
FROZEN_AFTER = 3  # the static model only ever sees the first three matchdays

played = json.load(urllib.request.urlopen(f"{API}/fixtures?league_id={LEAGUE}&status=FT&limit=200"))
clubs = sorted({m["home_team"] for m in played} | {m["away_team"] for m in played})
index = {club: i for i, club in enumerate(clubs)}

def train(matches, steps=800, rate=0.05):
    """Chapter 9's goals model: attack and defence per club, a base rate and a home bonus."""
    attack, defence, base, home = [0.0] * len(clubs), [0.0] * len(clubs), 0.0, 0.0
    for _ in range(steps):
        ga, gd, gb, gh = [0.0] * len(clubs), [0.0] * len(clubs), 0.0, 0.0
        for m in matches:
            h, a = index[m["home_team"]], index[m["away_team"]]
            eh = math.exp(base + home + attack[h] - defence[a]) - m["home_goals"]
            ea = math.exp(base + attack[a] - defence[h]) - m["away_goals"]
            gb += eh + ea
            gh += eh
            ga[h] += eh
            gd[a] -= eh
            ga[a] += ea
            gd[h] -= ea
        n = len(matches)
        base -= rate * gb / n
        home -= rate * gh / n
        attack = [x - rate * (g / n + 0.02 * x) for x, g in zip(attack, ga)]
        defence = [x - rate * (g / n + 0.02 * x) for x, g in zip(defence, gd)]
    return attack, defence, base, home

def loss(model, matches):
    """Poisson loss of the real scorelines: lower means the model expected them better."""
    attack, defence, base, home = model
    total = 0.0
    for m in matches:
        h, a = index[m["home_team"]], index[m["away_team"]]
        lh = math.exp(base + home + attack[h] - defence[a])
        la = math.exp(base + attack[a] - defence[h])
        total += lh - m["home_goals"] * math.log(lh) + la - m["away_goals"] * math.log(la)
    return total / len(matches)

rounds = sorted({m["matchday"] for m in played})
static = train([m for m in played if m["matchday"] <= FROZEN_AFTER])  # trained once, then served unchanged

print(f"static model: trained once on matchdays 1-{FROZEN_AFTER}. Dynamic model: retrained before every matchday.\n")
print("matchday   static   dynamic")
totals = [0.0, 0.0, 0]
for md in rounds:
    if md <= FROZEN_AFTER:
        continue
    this_round = [m for m in played if m["matchday"] == md]
    if len(this_round) < 3:
        continue
    dynamic = train([m for m in played if m["matchday"] < md])  # everything known before this matchday
    s, d = loss(static, this_round), loss(dynamic, this_round)
    totals = [totals[0] + s, totals[1] + d, totals[2] + 1]
    print(f"{md:>8}   {s:.3f}    {d:.3f}")
print(f"\naverage    {totals[0] / totals[2]:.3f}    {totals[1] / totals[2]:.3f}   (lower is better)")

A test suite

The second script runs checks like the deployment-testing page in plain Python: schema rules on the real results, a one-hot check, a reproducibility check, a single gradient descent step, and freshness checks on the site's update log. It prints PASS or FAIL for each.

  1. Run it. Does everything pass right now?
  2. Add a schema rule of your own, for instance that every match date is in the past.
  3. Add a check that would have caught a label leak: no feature may be computed from the match it predicts.
import json
import math
import random
import urllib.request
from datetime import datetime, timezone

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

results = []

def check(name, ok, detail=""):
    results.append(ok)
    print(f"{'PASS' if ok else 'FAIL'}  {name}{'  (' + detail + ')' if detail else ''}")

played = get(f"/fixtures?league_id={LEAGUE}&status=FT&limit=200")
table = get(f"/standings?league_id={LEAGUE}")

# 1. Data schema: the rules raw data has to follow.
check("every result has goals that are whole numbers from 0 to 15",
      all(isinstance(m[k], int) and 0 <= m[k] <= 15 for m in played for k in ("home_goals", "away_goals")))
clubs = {t["team_id"] for t in table}
check("every match is between two clubs in the table", all(m["home_team_id"] in clubs and m["away_team_id"] in clubs for m in played))
check("no match appears twice", len({m["id"] for m in played}) == len(played))
missing = sum(1 for m in played if m["home_xg"] is None)
check("xG missing in fewer than 5% of matches", missing < 0.05 * len(played), f"{missing} missing")

# 2. Feature engineering: a one-hot club vector has exactly one 1.
vocabulary = sorted(clubs)
one_hot = [1 if c == vocabulary[3] else 0 for c in vocabulary]
check("a one-hot vector has exactly one 1", sum(one_hot) == 1 and len(one_hot) == len(vocabulary))

# 3. Reproducibility: the same seed gives the same starting weights.
def start(seed):
    rnd = random.Random(seed)
    return [rnd.uniform(-1, 1) for _ in range(5)]
check("training starts the same way from the same seed", start(7) == start(7))

# 4. One training step on random data runs and lowers the loss.
def sigmoid(z):
    return 1 / (1 + math.exp(-z))
rnd = random.Random(1)
data = [(rnd.uniform(-2, 2), rnd.randint(0, 1)) for _ in range(50)]
def log_loss(w, b):
    return -sum(y * math.log(sigmoid(w * x + b)) + (1 - y) * math.log(1 - sigmoid(w * x + b)) for x, y in data) / len(data)
w, b = 0.5, 0.0
before = log_loss(w, b)
gw = sum((sigmoid(w * x + b) - y) * x for x, y in data) / len(data)
gb = sum(sigmoid(w * x + b) - y for x, y in data) / len(data)
check("one gradient descent step lowers the loss", log_loss(w - 0.1 * gw, b - 0.1 * gb) < before)

# 5. Monitoring: how old is the newest data from each source? Only sources that change all the time:
#    fixture lists change rarely, so silence from them says nothing.
now = datetime.now(timezone.utc)
newest = {}
for line in get("/updates?limit=200"):
    newest.setdefault(line["source"], datetime.fromisoformat(line["created_at"]))
for source in ("live", "table", "odds"):
    if source in newest:
        hours = (now - newest[source]).total_seconds() / 3600
        check(f"'{source}' updated in the last 48 hours", hours < 48, f"{hours:.1f} h ago")
    else:
        check(f"'{source}' updated in the last 48 hours", False, "not in the last 200 updates")

print(f"\n{sum(results)} of {len(results)} checks passed")

Check yourself

In the first script, why does the dynamic model usually beat the static one on later matchdays?
The second script checks that the live scores were updated recently. Is that a test of the model?

What the chapter adds up to

A model that works in a notebook is the start. To keep it working you decide how often it learns and when it predicts, keep training and serving identical, test it before it goes live, and watch its inputs, slices and age after. This site does most of that for its data every minute of the day.

Leagues