Machine learning with football · Chapter 3 · Logistic regression

Programming exercise

Train the model in plain Python on the live data, predict this weekend, then find out how good it really is.

Estimated time: 15 minutes · page 4 of 4

Predict this weekend

The first script does in Python what the board does. It downloads the table and every finished match from this site's API, trains logistic regression with gradient descent on log loss, and then uses the model for inference on the next ten matches. You need Python 3 and nothing else.

  1. Pick a league on the board. The code follows it.
  2. Save the code as home.py and run python home.py.
  3. Press Show best curve on the board. Your w and b should match it.
  4. Look at the predictions. Which match does the model call closest to a coin flip, and do you agree?
  5. Set learning_rate to 0.01 and run it again. How far off is it after 300 steps?
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))

# Each team's goal difference per game, from the table.
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"]}

# One example per finished match: x = home minus away goal difference per game, y = 1 for a home win.
played = get(f"/fixtures?league_id={LEAGUE}&status=FT&limit=200")
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 log_loss(w, b):
    return -sum(y * math.log(sigmoid(w * x + b)) + (1 - y) * math.log(1 - sigmoid(w * x + b))
                for x, y in data) / len(data)

learning_rate = 0.5
steps = 300
w, b = 0.0, 0.0

for step in range(1, steps + 1):
    # For log loss the gradient is simply the error (p - y), times x for the weight.
    errors = [sigmoid(w * x + b) - y for x, y in data]
    w -= learning_rate * sum(e * x for e, (x, _) in zip(errors, data)) / len(data)
    b -= learning_rate * sum(errors) / len(data)
    if step % 50 == 0:
        print(f"step {step:3}   w = {w:.3f}   b = {b:.3f}   log loss = {log_loss(w, b):.4f}")

print(f"\n{len(data)} matches. A coin flip scores {math.log(2):.4f}.\n")

# Inference: the next matches.
upcoming = get(f"/fixtures?league_id={LEAGUE}&status=NS&limit=10")
for m in upcoming:
    if m["home_team_id"] in gd and m["away_team_id"] in gd:
        p = sigmoid(w * (gd[m["home_team_id"]] - gd[m["away_team_id"]]) + b)
        print(f"{m['fixture_date'][:10]}  {m['home_team']:>26} v {m['away_team']:<26} home win {p:.0%}")

An honest test

The first script still takes the shortcut from page 1, because the table it learns from already contains the results it trains on. The second script stops peeking. It keeps the latest 20% of matches back as a test, works out each team's goal difference from the other 80% only, and trains with four values of λ. For each one it prints the log loss on the training matches and on the test matches, next to a baseline that always predicts the training home win rate.

  1. Run it. Does the model beat the baseline on the test matches?
  2. Which λ gives the lowest test loss? Is it the same one that gives the lowest training loss?
  3. Try two or three other leagues. The answers change from league to league.
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))

# Oldest first, so the last matches can be kept back as a test.
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:]

# No peeking this time: each team's goal difference per game comes from the training matches only.
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))

def log_loss(data, w, b):
    return -sum(y * math.log(sigmoid(w * x + b)) + (1 - y) * math.log(1 - sigmoid(w * x + b))
                for x, y in data) / len(data)

def train_model(lam, learning_rate=0.5, steps=500):
    w, b = 0.0, 0.0
    for _ in range(steps):
        errors = [sigmoid(w * x + b) - y for x, y in train]
        w -= learning_rate * (sum(e * x for e, (x, _) in zip(errors, train)) / len(train) + 2 * lam * w)
        b -= learning_rate * sum(errors) / len(train)
    return w, b

# The baseline: always predict the home win rate of the training matches.
rate = sum(y for _, y in train) / len(train)
baseline = -sum(y * math.log(rate) + (1 - y) * math.log(1 - rate) for _, y in test) / len(test)
print(f"{len(train)} training matches, {len(test)} test matches")
print(f"baseline (always {rate:.0%})          test log loss {baseline:.4f}")

for lam in (0, 0.01, 0.1, 1):
    w, b = train_model(lam)
    print(f"lambda = {lam:<5}  w = {w:.3f}  b = {b:.3f}   train {log_loss(train, w, b):.4f}   test {log_loss(test, w, b):.4f}")

Check yourself

The first script gives a home win 66%. What does the other 34% cover?
In some leagues the second script ends up worse on the test matches than the baseline, while the earlier pages looked fine. Why?
Which λ should you pick?

What the curve says

The trained model gives every match a home win chance from one number, the gap between the two teams. Bookmakers do something much richer, with dozens of features, but the last step is the same idea. Chapter 4, classification, turns these probabilities into yes or no answers and asks how often they are right.

Leagues