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.
- Pick a league on the board. The code follows it.
- Save it as
features.pyand runpython features.py. - Which feature fails the outlier test most clearly?
- 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}")