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.
- Pick a league on the board. The code follows it.
- Save it as
stale.pyand runpython stale.py. Does the gap grow as the season goes on? - Set
FROZEN_AFTERto 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)")