Machine learning with football · Chapter 5 · Numerical data

Programming exercise

Summarise, scrub, normalize and bin the real player stats in Python, then give a model its x².

Estimated time: 15 minutes · page 9 of 9

Look, scrub, scale, bin

The first script works through the chapter on the real player stats. It prints the summary and the outlier test for three features, finds players listed twice, builds feature vectors with the right scaling for each feature and a has-rating flag, and compares equal and quantile bins for minutes.

  1. Pick a league on the board. The code follows it.
  2. Save it as features.py and run python features.py.
  3. Which feature fails the outlier test most clearly?
  4. Change the bins to goals instead of minutes. What happens to the quantile edges, and why?
import json
import math
import sys
import urllib.request

sys.stdout.reconfigure(encoding="utf-8")  # names like Muñoz print on any terminal

API = "https://tactical-insights.com/api"
LEAGUE = 1  # change it to try another league

players = json.load(urllib.request.urlopen(f"{API}/leagues/{LEAGUE}/player-stats"))["players"]

def summary(values):
    v = sorted(values)
    at = lambda q: v[min(len(v) - 1, int(q * len(v)))]
    mean = sum(v) / len(v)
    sd = math.sqrt(sum((x - mean) ** 2 for x in v) / len(v))
    return {"n": len(v), "mean": mean, "sd": sd, "min": v[0], "p25": at(0.25), "median": at(0.5), "p75": at(0.75), "max": v[-1]}

# 1. Look before you transform: the five percentiles, and the outlier rule of thumb.
for feature in ("minutes", "goals", "avg_rating"):
    values = [p[feature] for p in players if p[feature] is not None]
    s = summary(values)
    missing = len(players) - len(values)
    print(f"{feature:>10}: n {s['n']}, missing {missing}, mean {s['mean']:.2f}, sd {s['sd']:.2f}, "
          f"percentiles {s['min']} / {s['p25']} / {s['median']} / {s['p75']} / {s['max']}")
    print(f"{'':>12}gap 0-25%: {s['p25'] - s['min']:.2f}   gap 75-100%: {s['max'] - s['p75']:.2f}")

# 2. Scrub: who is listed twice? Mistake, or a real transfer?
ids = [p["player_id"] for p in players if p["player_id"]]
twice = sorted({p["player"] for p in players if p["player_id"] and ids.count(p["player_id"]) > 1})
print(f"\nPlayers listed twice (two clubs this season): {', '.join(twice) or 'none'}")

# 3. Normalize each feature the way its shape asks for.
minutes = [p["minutes"] for p in players]
lo, hi = min(minutes), max(minutes)
rated = [p for p in players if p["avg_rating"] is not None and p["minutes"] >= 90]
r = summary([p["avg_rating"] for p in rated])

def vector(p):
    return [
        round((p["minutes"] - lo) / (hi - lo), 3),            # linear scaling: fixed bounds, no outliers
        round(math.log(1 + p["goals"]), 3),                    # log scaling: a few scorers, a long tail of zeros
        round((p["avg_rating"] - r["mean"]) / r["sd"], 3) if p["avg_rating"] is not None else 0.0,  # z-score: bell-shaped
        1.0 if p["avg_rating"] is not None else 0.0,           # a flag instead of a magic value for "no rating"
    ]

print("\nFeature vectors [minutes, goals, rating, has_rating]:")
for p in players[:5]:
    print(f"{p['player']:>22}: {vector(p)}")

# 4. Bins: equal width against quantiles, on minutes.
def counts(values, edges):
    out = [0] * (len(edges) - 1)
    for x in values:
        i = next((j - 1 for j in range(1, len(edges)) if x < edges[j]), len(edges) - 2)
        out[i] += 1
    return out

k = 5
equal = [lo + (hi - lo) * i / k for i in range(k + 1)]
v = sorted(minutes)
quantile = [v[0]] + [v[(i * len(v)) // k] for i in range(1, k)] + [v[-1]]
print(f"\nminutes in {k} equal bins:    {counts(minutes, equal)}  edges {[round(e) for e in equal]}")
print(f"minutes in {k} quantile bins: {counts(minutes, quantile)}  edges {quantile}")

Give the model its x²

The second script is the polynomial transform from the previous page. It fits a draw model twice, once with x and once with x and x², then prints both log losses and the draw chance at gaps from −2 to +2.

  1. Run it. Does w₂ come out negative, and how much does the log loss drop?
  2. Try three leagues. In which one does the hump show most clearly?
  3. Add a third feature, x³. Does it help, or is it just fitting noise? Chapter 7 gives you the tools to tell.
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))

table = get(f"/standings?league_id={LEAGUE}")
gd = {t["team_id"]: (t["goals_for"] - t["goals_against"]) / t["played"] for t in table if t["played"]}
played = get(f"/fixtures?league_id={LEAGUE}&status=FT&limit=200")

# x: home minus away goal difference per game. y: 1 for a draw.
data = [(gd[m["home_team_id"]] - gd[m["away_team_id"]], 1 if m["home_goals"] == m["away_goals"] else 0)
        for m in played if m["home_team_id"] in gd and m["away_team_id"] in gd]

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

def fit(rows, steps=3000, rate=0.3):
    """Logistic regression on rows of (features, label). Returns [b, w1, w2, ...]."""
    w = [0.0] * (len(rows[0][0]) + 1)
    for _ in range(steps):
        grad = [0.0] * len(w)
        for f, y in rows:
            error = sigmoid(w[0] + sum(wi * xi for wi, xi in zip(w[1:], f))) - y
            grad[0] += error
            for i, xi in enumerate(f):
                grad[i + 1] += error * xi
        w = [wi - rate * g / len(rows) for wi, g in zip(w, grad)]
    return w

def log_loss(rows, w):
    total = 0
    for f, y in rows:
        p = sigmoid(w[0] + sum(wi * xi for wi, xi in zip(w[1:], f)))
        total -= y * math.log(p) + (1 - y) * math.log(1 - p)
    return total / len(rows)

line = [([x], y) for x, y in data]           # one feature: x
curve = [([x, x * x], y) for x, y in data]   # a synthetic feature: x squared

w_line, w_curve = fit(line), fit(curve)
print(f"{len(data)} matches, {sum(y for _, y in data)} draws")
print(f"x only:     b = {w_line[0]:.3f}  w1 = {w_line[1]:.3f}                 log loss {log_loss(line, w_line):.4f}")
print(f"x and x^2:  b = {w_curve[0]:.3f}  w1 = {w_curve[1]:.3f}  w2 = {w_curve[2]:.3f}   log loss {log_loss(curve, w_curve):.4f}\n")

for gap in (-2, -1, 0, 1, 2):
    p_line = sigmoid(w_line[0] + w_line[1] * gap)
    p_curve = sigmoid(w_curve[0] + w_curve[1] * gap + w_curve[2] * gap * gap)
    print(f"gap {gap:+d}:  draw chance {p_line:.0%} with x only, {p_curve:.0%} with x^2")

Check yourself

The first script makes goals into ln(1 + goals). Why the + 1?
Quantile bins for goals come out strange: several edges are 0. Why?

What the chapter adds up to

Every number needs a look before it goes into a model: its shape, its outliers, the mistakes hiding in it. Then the treatment follows from the shape. Chapter 6 does the same for categories, such as positions, clubs and leagues, which have to become numbers before any model can use them.

Leagues