Watch it overfit
The first script trains the club model on the date split and prints training and validation loss as it goes. It finds the step where early stopping would stop, tries four values of λ chosen on the validation set, and only then touches the test set, once.
- Pick a league on the board. The code follows it.
- Save it as
overfit.pyand runpython overfit.py. - At which step does validation loss bottom out? How far has training loss fallen by step 2,000?
- Does the best model beat "always predict the home win rate" on the test set? If not, why not?
import json
import math
import urllib.request
API = "https://tactical-insights.com/api"
LEAGUE = 1 # change it to try another league
played = sorted(json.load(urllib.request.urlopen(f"{API}/fixtures?league_id={LEAGUE}&status=FT&limit=200")),
key=lambda m: m["fixture_date"])
# Three sets, oldest matches first: 70% training, 15% validation, 15% test.
a, b = int(len(played) * 0.70), int(len(played) * 0.85)
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)}
size = 2 * len(clubs) # one-hot home club, then one-hot away club
def rows(matches):
return [([index[m["home_team"]], len(clubs) + index[m["away_team"]]], 1 if m["home_goals"] > m["away_goals"] else 0)
for m in matches]
train, validation, test = rows(played[:a]), rows(played[a:b]), rows(played[b:])
print(f"{len(train)} training, {len(validation)} validation, {len(test)} test matches; {size} weights")
print(f"rule of thumb: 10 to 100 examples per weight, so {10 * size} to {100 * size} matches\n")
def sigmoid(z):
return 1 / (1 + math.exp(-z))
def log_loss(data, w, bias):
return -sum(y * math.log(sigmoid(bias + sum(w[i] for i in f))) + (1 - y) * math.log(1 - sigmoid(bias + sum(w[i] for i in f)))
for f, y in data) / len(data)
def train_model(lam, steps=2000, rate=1.0, report=()):
w, bias = [0.0] * size, 0.0
best = (float("inf"), 0, None)
for step in range(1, steps + 1):
grad, grad_b = [0.0] * size, 0.0
for f, y in train:
error = sigmoid(bias + sum(w[i] for i in f)) - y
grad_b += error
for i in f:
grad[i] += error
bias -= rate * grad_b / len(train)
w = [wi - rate * (g / len(train) + 2 * lam * wi) for wi, g in zip(w, grad)]
v = log_loss(validation, w, bias)
if v < best[0]:
best = (v, step, (list(w), bias)) # early stopping: remember the weights with the lowest validation loss
if step in report:
print(f"step {step:5} training {log_loss(train, w, bias):.3f} validation {v:.3f}")
return w, bias, best
# 1. The generalization curve: training loss keeps falling, validation loss turns around.
w, bias, (best_loss, best_step, best_weights) = train_model(0, report=(1, 10, 30, 100, 300, 1000, 2000))
print(f"\nlowest validation loss {best_loss:.3f} at step {best_step}: early stopping would stop there")
# 2. L2 instead of stopping early. Choose lambda on the validation set, never on the test set.
print()
results = []
for lam in (0, 0.005, 0.02, 0.1):
w, bias, _ = train_model(lam)
results.append((log_loss(validation, w, bias), lam, w, bias))
print(f"lambda {lam:<6} training {log_loss(train, w, bias):.3f} validation {log_loss(validation, w, bias):.3f}")
# 3. Only now, once, the test set.
_, lam, w, bias = min(results)
rate = sum(y for _, y in train) / len(train)
baseline = -sum(y * math.log(rate) + (1 - y) * math.log(1 - rate) for _, y in test) / len(test)
print(f"\nbest lambda on validation: {lam}. Test log loss {log_loss(test, w, bias):.3f} (always {rate:.0%}: {baseline:.3f})")