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.
- Pick a league on the board. The code follows it.
- Save it as
clubs.pyand runpython clubs.py. - Which clubs share a hash bin? Change 8 to 32: how many collisions are left?
- 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)}")