Classify the test matches
The first script reuses chapter 3's honest setup. It keeps back the latest 20% of matches as a test and describes each team only by the matches before. Then it scores the test matches and prints the confusion matrix, accuracy, precision and recall at five thresholds, plus the AUC.
- Pick a league on the board. The code follows it.
- Save it as
classify.pyand runpython classify.py. - Find the threshold with the best accuracy, and the one with the best precision. Are they the same?
- Compare the AUC with the board's. The board scores every match and peeks, so it should look better.
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))
# The honest setup from chapter 3: the latest 20% of matches are the test,
# and each team's goal difference per game comes from the other 80% only.
played = sorted(get(f"/fixtures?league_id={LEAGUE}&status=FT&limit=200"), key=lambda m: m["fixture_date"])
cut = int(len(played) * 0.8)
train_matches, test_matches = played[:cut], played[cut:]
goals, games = {}, {}
for m in train_matches:
for team, scored, conceded in ((m["home_team_id"], m["home_goals"], m["away_goals"]),
(m["away_team_id"], m["away_goals"], m["home_goals"])):
goals[team] = goals.get(team, 0) + scored - conceded
games[team] = games.get(team, 0) + 1
gd = {team: goals[team] / games[team] for team in goals}
def examples(matches):
return [(gd[m["home_team_id"]] - gd[m["away_team_id"]], 1 if m["home_goals"] > m["away_goals"] else 0)
for m in matches if m["home_team_id"] in gd and m["away_team_id"] in gd]
train, test = examples(train_matches), examples(test_matches)
def sigmoid(z):
return 1 / (1 + math.exp(-z))
w, b = 0.0, 0.0
for _ in range(500):
errors = [sigmoid(w * x + b) - y for x, y in train]
w -= 0.5 * sum(e * x for e, (x, _) in zip(errors, train)) / len(train)
b -= 0.5 * sum(errors) / len(train)
# The model's home win chance for every test match, next to what happened.
scored = [(sigmoid(w * x + b), y) for x, y in test]
def confusion(threshold):
tp = sum(1 for p, y in scored if p > threshold and y == 1)
fp = sum(1 for p, y in scored if p > threshold and y == 0)
fn = sum(1 for p, y in scored if p <= threshold and y == 1)
tn = sum(1 for p, y in scored if p <= threshold and y == 0)
return tp, fp, fn, tn
def ratio(a, b):
return f"{a / b:.2f}" if b else " n/a"
print(f"{len(test)} test matches, {sum(y for _, y in scored)} home wins\n")
print("threshold TP FP FN TN accuracy precision recall")
for threshold in (0.3, 0.4, 0.5, 0.6, 0.7):
tp, fp, fn, tn = confusion(threshold)
print(f" {threshold:.1f} {tp:3} {fp:3} {fn:3} {tn:3} {ratio(tp + tn, len(scored))} {ratio(tp, tp + fp)} {ratio(tp, tp + fn)}")
# AUC: how often a real home win got a higher score than a match without one.
wins = [p for p, y in scored if y == 1]
others = [p for p, y in scored if y == 0]
pairs = sum(1 if a > o else 0.5 if a == o else 0 for a in wins for o in others)
print(f"\nAUC = {pairs / (len(wins) * len(others)):.2f} (0.5 is a coin flip, 1.0 is perfect)")