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.
- Pick a league on the board. The code follows it.
- Save it as
automl.pyand runpython automl.py. Does the winner beat the flat guess on the test matches? - Set
LABELto"over 2.5". Is there any signal for that question? - 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})")