Machine learning with football · Chapter 6 · Categorical data

Programming exercise

Vocabulary, one-hot, hashing and a feature cross in plain Python, tested on matches the model has never seen.

Estimated time: 15 minutes · page 5 of 5

Encode the clubs

The first script builds the vocabulary, prints a one-hot vector, its sparse form and where an unknown club lands. It shows the hashing trick squeezing the clubs into 8 bins. Then it trains a model on nothing but the identity of the two clubs, one-hot home club plus one-hot away club, and tests it on the latest 20% of matches.

  1. Pick a league on the board. The code follows it.
  2. Save it as clubs.py and run python clubs.py.
  3. Which clubs share a hash bin? Change 8 to 32: how many collisions are left?
  4. Does club identity alone beat the baseline? Try three leagues.
import json
import math
import sys
import urllib.request
import zlib

sys.stdout.reconfigure(encoding="utf-8")  # club names with accents print on any terminal

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

# 1. The vocabulary: every club in the league gets an index, plus one slot for anything unknown.
table = get(f"/standings?league_id={LEAGUE}")
vocabulary = sorted(t["team"] for t in table)
index = {team: i for i, team in enumerate(vocabulary)}
OOV = len(vocabulary)  # out of vocabulary: a club this model has never seen

def one_hot(team):
    v = [0] * (len(vocabulary) + 1)
    v[index.get(team, OOV)] = 1
    return v

first = vocabulary[0]
print(f"{len(vocabulary)} clubs in the vocabulary, plus 1 out-of-vocabulary slot")
print(f"{first}: index {index[first]}, one-hot {one_hot(first)}")
print(f"Sparse form of the same vector: just the position, {index[first]}")
print(f"A club from another league lands in slot {OOV}: {one_hot('Some Other FC')[-3:]} (last three slots)\n")

# 2. The hashing trick: squeeze the clubs into 8 bins. Fewer features, but some clubs share a bin.
bins = {}
for team in vocabulary:
    bins.setdefault(zlib.crc32(team.encode()) % 8, []).append(team)
for b in sorted(bins):
    print(f"bin {b}: {', '.join(bins[b])}")

# 3. A model on club identity alone: one-hot home club + one-hot away club, nothing computed from results.
played = sorted(get(f"/fixtures?league_id={LEAGUE}&status=FT&limit=200"), key=lambda m: m["fixture_date"])
cut = int(len(played) * 0.8)

def features(m):
    # Positions of the 1s: home club in the first block, away club in the second.
    return [index.get(m["home_team"], OOV), len(vocabulary) + 1 + index.get(m["away_team"], OOV)]

def label(m):
    return 1 if m["home_goals"] > m["away_goals"] else 0

train = [(features(m), label(m)) for m in played[:cut]]
test = [(features(m), label(m)) for m in played[cut:]]

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

size = 2 * (len(vocabulary) + 1)
w, b = [0.0] * size, 0.0
for _ in range(1000):
    grad, grad_b = [0.0] * size, 0.0
    for f, y in train:
        error = sigmoid(b + sum(w[i] for i in f)) - y
        grad_b += error
        for i in f:
            grad[i] += error
    b -= 0.5 * grad_b / len(train)
    w = [wi - 0.5 * (g / len(train) + 2 * 0.01 * wi) for wi, g in zip(w, grad)]  # a little L2, chapter 3

def log_loss(rows, chance):
    return -sum(y * math.log(chance(f)) + (1 - y) * math.log(1 - chance(f)) for f, y in rows) / len(rows)

rate = sum(y for _, y in train) / len(train)
print(f"\ntest log loss, always {rate:.0%}:      {log_loss(test, lambda f: rate):.4f}")
print(f"test log loss, one-hot clubs:  {log_loss(test, lambda f: sigmoid(b + sum(w[i] for i in f))):.4f}")
best = sorted(vocabulary, key=lambda t: -w[index[t]])[:3]
print(f"strongest home weights: {', '.join(best)}")

Is the cross worth it?

The second script repeats the board's experiment honestly. It sorts clubs into thirds using only the earliest 80% of matches, trains the separate and the crossed model on those, and tests both on the latest 20%. The crossed model also runs with two amounts of L2.

  1. Run it. Which model has the best training loss, and which the best test loss?
  2. Look at the 3 × 3 table at the end. Which cells have so few matches that their weight is mostly noise?
  3. Try other leagues and other values of λ. Is there one that works everywhere?
import json
import math
import urllib.request

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

played = sorted(get(f"/fixtures?league_id={LEAGUE}&status=FT&limit=200"), key=lambda m: m["fixture_date"])
cut = int(len(played) * 0.8)
train_matches, test_matches = played[:cut], played[cut:]

# Strength from the training matches only: goal difference per game, then cut into thirds.
goals, games = {}, {}
for m in train_matches:
    for team, scored, conceded in ((m["home_team_id"], m["home_goals"], m["away_goals"]),
                                   (m["away_team_id"], m["away_goals"], m["home_goals"])):
        goals[team] = goals.get(team, 0) + scored - conceded
        games[team] = games.get(team, 0) + 1
ranked = sorted(goals, key=lambda t: -goals[t] / games[t])
third = {team: min(2, i * 3 // len(ranked)) for i, team in enumerate(ranked)}
NAMES = ["top", "middle", "bottom"]

def rows(matches, crossed):
    out = []
    for m in matches:
        h, a = third.get(m["home_team_id"]), third.get(m["away_team_id"])
        if h is None or a is None:
            continue
        y = 1 if m["home_goals"] > m["away_goals"] else 0
        # Without the cross: one-hot home third (slots 0-2) + one-hot away third (slots 3-5).
        # With the cross: one slot for each of the 9 (home third, away third) pairs.
        out.append(([3 * h + a] if crossed else [h, 3 + a], y))
    return out

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

def fit(data, size, lam=0.0, steps=3000, rate=0.5):
    w, b = [0.0] * size, 0.0
    for _ in range(steps):
        grad, grad_b = [0.0] * size, 0.0
        for f, y in data:
            error = sigmoid(b + sum(w[i] for i in f)) - y
            grad_b += error
            for i in f:
                grad[i] += error
        b -= rate * grad_b / len(data)
        w = [wi - rate * (g / len(data) + 2 * lam * wi) for wi, g in zip(w, grad)]  # L2, chapter 3
    return w, b

def log_loss(data, w, b):
    return -sum(y * math.log(sigmoid(b + sum(w[i] for i in f))) + (1 - y) * math.log(1 - sigmoid(b + sum(w[i] for i in f)))
                for f, y in data) / len(data)

for crossed, size, lam in ((False, 6, 0), (True, 9, 0), (True, 9, 0.02), (True, 9, 0.1)):
    w, b = fit(rows(train_matches, crossed), size, lam)
    name = ("with the cross" if crossed else "without the cross") + (f", lambda {lam}" if lam else "")
    print(f"{name:<28}  train {log_loss(rows(train_matches, crossed), w, b):.4f}   test {log_loss(rows(test_matches, crossed), w, b):.4f}")

print()
print("home wins / matches in training, home third down, away third across:")
for h in range(3):
    cells = []
    for a in range(3):
        n = [y for f, y in rows(train_matches, True) if f[0] == 3 * h + a]
        cells.append(f"{sum(n):>2}/{len(n):<2}")
    print(f"{NAMES[h]:>8}   " + "   ".join(cells))

Check yourself

The hashing trick puts several clubs into the same bin. What does the model lose?
In the second script, the unregularized cross has the best training loss and the worst test loss. What is that called?

What the chapter adds up to

Categories become numbers through a vocabulary and one-hot vectors, with a slot for the unknown. Labels deserve as much suspicion as features. Crosses can capture combinations, but they spread the data thin, and regularization keeps them honest. Chapter 7 is about exactly that kind of honesty: splitting data, generalizing and spotting overfitting.

Leagues