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.
- Pick a league on the board. The code follows it.
- Save it as
embed.pyand runpython embed.py. Do the coordinates match the map? - 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)}")