Machine learning with football · Chapter 7 · Datasets and overfitting

Programming exercise

Watch a model overfit in Python, stop it two ways, and fix an imbalanced dataset.

Estimated time: 15 minutes · page 12 of 12

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.

  1. Pick a league on the board. The code follows it.
  2. Save it as overfit.py and run python overfit.py.
  3. At which step does validation loss bottom out? How far has training loss fallen by step 2,000?
  4. 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})")

Fix a rare class

The second script models matches with five or more goals, the rare class from the imbalanced datasets page. Its one feature is how many goals both teams' earlier matches averaged. It trains three times: on all matches, after downsampling the majority by 3, and after downsampling and upweighting. For each it prints the average prediction next to the real rate.

  1. Run it. How far does the average prediction drift after downsampling alone?
  2. Set GOALS to 6 and FACTOR to 5. Does upweighting still fix the bias?
  3. Which of chapter 4's pages describes the drift you just saw?
import json
import math
import random
import urllib.request

API = "https://tactical-insights.com/api"
LEAGUE = 1  # change it to try another league
GOALS = 5  # the rare class: matches with at least this many goals

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

# Feature: how many goals both teams' matches have had per game so far (from earlier matches only).
seen, goals = {}, {}
data = []
for m in played:
    h, a = m["home_team_id"], m["away_team_id"]
    if seen.get(h) and seen.get(a):
        x = goals[h] / seen[h] + goals[a] / seen[a]
        data.append((x, 1 if m["home_goals"] + m["away_goals"] >= GOALS else 0))
    for team in (h, a):
        seen[team] = seen.get(team, 0) + 1
        goals[team] = goals.get(team, 0) + m["home_goals"] + m["away_goals"]

positives = sum(y for _, y in data)
print(f"{len(data)} matches, {positives} with {GOALS}+ goals ({positives / len(data):.0%}): the minority class")
print(f"a batch of 20 holds {20 * positives / len(data):.1f} of them on average\n")

def sigmoid(z):
    return 1 / (1 + math.exp(-z))

def fit(rows, steps=3000, rate=0.1):
    """Logistic regression on (x, y, weight) rows. The weight multiplies an example's share of the loss."""
    w, b = 0.0, 0.0
    total = sum(weight for _, _, weight in rows)
    for _ in range(steps):
        gw = gb = 0.0
        for x, y, weight in rows:
            error = (sigmoid(w * x + b) - y) * weight
            gw += error * x
            gb += error
        w -= rate * gw / total
        b -= rate * gb / total
    return w, b

def mean_prediction(w, b):
    return sum(sigmoid(w * x + b) for x, _ in data) / len(data)

random.seed(1)
FACTOR = 3
majority = [(x, y) for x, y in data if y == 0]
minority = [(x, y) for x, y in data if y == 1]
kept = random.sample(majority, len(majority) // FACTOR)  # downsample: keep one majority match in three

for name, rows in (
    ("all matches", [(x, y, 1) for x, y in data]),
    (f"downsampled {FACTOR}x", [(x, y, 1) for x, y in kept + minority]),
    (f"downsampled {FACTOR}x, upweighted {FACTOR}x", [(x, y, FACTOR) for x, y in kept] + [(x, y, 1) for x, y in minority]),
):
    w, b = fit(rows)
    share = sum(y for _, y, _ in rows) / len(rows)
    print(f"{name:<32} minority share {share:.0%}   average prediction {mean_prediction(w, b):.0%}   (real rate {positives / len(data):.0%})")

Check yourself

In the first script, which set decides λ, and which set is only used once at the end?
In the second script, why does the average prediction jump after downsampling, and drop back after upweighting?

What the chapter adds up to

A model is only as good as the data it learned from and the honesty of the test it passed. Keep a validation set for decisions and a test set for the end, watch both loss curves, and rein in complexity with regularization or early stopping. Chapter 8 moves on to neural networks, models that find their own feature crosses and need these habits more than any model so far.

Leagues