Machine learning with football · Chapter 9 · Embeddings

Programming exercise

Build both embeddings in plain Python: PCA by hand, then attack and defence numbers trained on every goal.

Estimated time: 15 minutes · page 5 of 5

PCA by hand

The first script builds the board's map in plain Python. It describes each club with nine per-match numbers, z-scores them, finds the two main directions by power iteration, and prints what each direction is made of, each club's two coordinates and its nearest neighbours.

  1. Pick a league on the board. The code follows it.
  2. Save it as embed.py and run python embed.py. Do the coordinates match the map?
  3. Drop the home and away points from describe. How much of the spread do two dimensions keep now?
import json
import math
import sys
import urllib.request

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

clubs = [t for t in json.load(urllib.request.urlopen(f"{API}/leagues/{LEAGUE}/team-stats")) if t["played"]]

# 1. Every club as a vector of nine per-match numbers: a high-dimensional description.
NAMES = ["goals for", "goals against", "points", "clean sheets", "failed to score",
         "both scored", "over 2.5", "home points", "away points"]

def describe(t):
    p = t["played"]
    return [t["goals_for_per_match"], t["goals_against_per_match"], t["points_per_match"],
            t["clean_sheets"] / p, t["failed_to_score"] / p, t["both_teams_scored"] / p, t["over_2_5_goals"] / p,
            t["home_points"] / max(t["home_played"], 1), t["away_points"] / max(t["away_played"], 1)]

X = [describe(t) for t in clubs]
n, k = len(X), len(X[0])

# 2. Z-scores (chapter 5), so goals and percentages count the same.
mean = [sum(r[j] for r in X) / n for j in range(k)]
sd = [math.sqrt(sum((r[j] - mean[j]) ** 2 for r in X) / n) or 1 for j in range(k)]
Z = [[(r[j] - mean[j]) / sd[j] for j in range(k)] for r in X]

# 3. PCA: find the two directions along which the clubs differ most (power iteration on the covariance matrix).
cov = [[sum(z[a] * z[b] for z in Z) / n for b in range(k)] for a in range(k)]
directions = []
for _ in range(2):
    v = [1.0] * k
    for _ in range(300):
        w = [sum(cov[a][b] * v[b] for b in range(k)) for a in range(k)]
        for d in directions:  # stay at right angles to the directions already found
            dot = sum(wi * di for wi, di in zip(w, d))
            w = [wi - dot * di for wi, di in zip(w, d)]
        length = math.sqrt(sum(x * x for x in w))
        v = [x / length for x in w]
    if v[max(range(k), key=lambda j: abs(v[j]))] < 0:  # point the direction so its biggest part is positive, as on the board
        v = [-x for x in v]
    directions.append(v)
    share = sum(v[a] * sum(cov[a][b] * v[b] for b in range(k)) for a in range(k)) / k
    top = sorted(range(k), key=lambda j: -abs(v[j]))[:3]
    print(f"dimension {len(directions)} keeps {share:.0%} of the spread, mostly: " + ", ".join(f"{NAMES[j]} ({v[j]:+.2f})" for j in top))

# 4. The embedding: each club becomes 2 numbers instead of 9.
embedding = {t["team"]: [sum(z[j] * d[j] for j in range(k)) for d in directions] for t, z in zip(clubs, Z)}

print()
for t in clubs[:5]:
    name = t["team"]
    near = sorted(embedding, key=lambda other: math.dist(embedding[name], embedding[other]))[1:4]
    x, y = embedding[name]
    print(f"{name:>26}: ({x:+.2f}, {y:+.2f})   nearest: {', '.join(near)}")

An embedding layer by hand

The second script trains the learned embedding from the previous page. Every club gets an attack and a defence number, starting at 0. Gradient descent on the Poisson loss moves them until the expected goals fit every finished match. It prints the loss as it goes, the home advantage, the clubs with the best numbers, and expected goals for the next matches.

  1. Run it. Which club has the best attack, and is it the top scorer in the table?
  2. Compare the expected goals for the next matches with the bookmakers' prices on this site's match pages.
  3. Set the L2 term (0.02) to 0 and run it again. What happens to clubs that have played few matches?
import json
import math
import sys
import urllib.request

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

played = get(f"/fixtures?league_id={LEAGUE}&status=FT&limit=200")
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)}

# An embedding layer: every club gets two learned numbers, attack and defence, instead of a one-hot vector.
# Expected goals for a side = exp(base + home bonus + its attack - the other side's defence).
attack = [0.0] * len(clubs)
defence = [0.0] * len(clubs)
base, home = 0.0, 0.0

def expected(h, a):
    return (math.exp(base + home + attack[h] - defence[a]),  # home goals
            math.exp(base + attack[a] - defence[h]))          # away goals

def loss():
    # Poisson loss: how unlikely the real scorelines are under the expected goals (lower is better).
    total = 0.0
    for m in played:
        lh, la = expected(index[m["home_team"]], index[m["away_team"]])
        total += lh - m["home_goals"] * math.log(lh) + la - m["away_goals"] * math.log(la)
    return total / len(played)

rate = 0.05
for step in range(1, 1501):
    g_att, g_def = [0.0] * len(clubs), [0.0] * len(clubs)
    g_base = g_home = 0.0
    for m in played:
        h, a = index[m["home_team"]], index[m["away_team"]]
        lh, la = expected(h, a)
        eh, ea = lh - m["home_goals"], la - m["away_goals"]  # the gradient of the Poisson loss: expected minus real
        g_base += eh + ea
        g_home += eh
        g_att[h] += eh
        g_def[a] -= eh
        g_att[a] += ea
        g_def[h] -= ea
    n = len(played)
    base -= rate * g_base / n
    home -= rate * g_home / n
    attack = [x - rate * (g / n + 0.02 * x) for x, g in zip(attack, g_att)]   # a little L2, chapter 7
    defence = [x - rate * (g / n + 0.02 * x) for x, g in zip(defence, g_def)]
    if step in (1, 100, 500, 1500):
        print(f"step {step:5}   loss {loss():.4f}")

print(f"\nhome advantage: home sides score {math.exp(home):.2f} times as many goals, all else equal\n")
print("club                         attack   defence")
for i in sorted(range(len(clubs)), key=lambda i: -(attack[i] + defence[i]))[:6]:
    print(f"{clubs[i]:<26} {attack[i]:+8.2f}  {defence[i]:+8.2f}")

print("\nexpected goals in the next matches:")
for m in get(f"/fixtures?league_id={LEAGUE}&status=NS&limit=6"):
    if m["home_team"] in index and m["away_team"] in index:
        lh, la = expected(index[m["home_team"]], index[m["away_team"]])
        print(f"   {m['home_team']:>26} {lh:.1f} - {la:.1f} {m['away_team']}")

Check yourself

Why does the first script z-score the nine stats before PCA?
In the second script, what does the home advantage of about 1.36 mean?

What the chapter adds up to

An embedding swaps a long, empty one-hot vector for a few numbers that carry meaning, so similar things sit close together. You get one by squashing a rich description or by learning it inside a model. Static embeddings give one point per item, contextual ones a point per situation, and that idea is the starting point of the large language models in the next chapter.

Leagues