Machine learning with football · Chapter 2 · Linear regression

Programming exercise

The same training loop in about 25 lines of Python, run on the live table from this site.

Estimated time: 10 minutes · page 7 of 7

Train it in Python

Everything the board does fits in a short script. You need Python 3 and nothing else. The script downloads the same table the board shows, from this site's public API, and runs full-batch gradient descent on it.

  1. Pick a league on the board. The code below follows it.
  2. Copy the code into a file called line.py and run python line.py.
  3. Press Show best line on the board and compare w and b with what the script prints.
  4. Change learning_rate to 1.1 and run it again. Then 0.01.
import json
import urllib.request

# The table from the board. Change league_id to try another league.
URL = "https://tactical-insights.com/api/standings?league_id=1"
rows = json.load(urllib.request.urlopen(URL))

# One example per team: x = goal difference per game, y = points per game.
data = [((r["goals_for"] - r["goals_against"]) / r["played"], r["points"] / r["played"])
        for r in rows if r["played"]]

def mse(w, b):
    return sum((w * x + b - y) ** 2 for x, y in data) / len(data)

# Hyperparameters: you pick these.
learning_rate = 0.1
epochs = 200

# Parameters: training finds these.
w, b = 0.0, 0.0

for epoch in range(1, epochs + 1):
    # The gradient: which way the loss falls, for w and for b.
    dw = sum(2 * (w * x + b - y) * x for x, y in data) / len(data)
    db = sum(2 * (w * x + b - y) for x, y in data) / len(data)
    w -= learning_rate * dw
    b -= learning_rate * db
    if epoch % 20 == 0:
        print(f"epoch {epoch:3}   w = {w:.3f}   b = {b:.3f}   loss = {mse(w, b):.4f}")

Two features and mini-batches

The second script splits goal difference into goals for and goals against, each with its own weight, and trains in mini-batches of 5 that are shuffled every epoch. Run it and look at three things: the sign of w2, how close w1 and w2 are in size, and whether the loss settles. Then try learning_rate = 0.02, and batch_size = 20.

import json
import random
import urllib.request

URL = "https://tactical-insights.com/api/standings?league_id=1"
rows = json.load(urllib.request.urlopen(URL))

# Two features now: goals for per game (x1) and goals against per game (x2).
data = [(r["goals_for"] / r["played"], r["goals_against"] / r["played"], r["points"] / r["played"])
        for r in rows if r["played"]]

def mse(w1, w2, b):
    return sum((w1 * x1 + w2 * x2 + b - y) ** 2 for x1, x2, y in data) / len(data)

learning_rate = 0.1
epochs = 500
batch_size = 5

w1, w2, b = 0.0, 0.0, 0.0

for epoch in range(1, epochs + 1):
    random.shuffle(data)  # new mini-batches every epoch
    for start in range(0, len(data), batch_size):
        batch = data[start:start + batch_size]
        errors = [w1 * x1 + w2 * x2 + b - y for x1, x2, y in batch]
        w1 -= learning_rate * sum(2 * e * x1 for e, (x1, _, _) in zip(errors, batch)) / len(batch)
        w2 -= learning_rate * sum(2 * e * x2 for e, (_, x2, _) in zip(errors, batch)) / len(batch)
        b -= learning_rate * sum(2 * e for e in errors) / len(batch)
    if epoch % 100 == 0:
        print(f"epoch {epoch:3}   w1 = {w1:.3f}   w2 = {w2:.3f}   b = {b:.3f}   loss = {mse(w1, w2, b):.4f}")

Check yourself

Your script prints w and b after 200 epochs. Where on the board should they be?
With two features, goals for and goals against per game, what sign does the weight of goals against get?
In the second script the loss goes up and down between prints, even after 500 epochs. Why?

What the line says

Once trained, the two numbers mean something in football. w is the price of a goal: in these leagues one extra goal of difference per game is worth about 0.5 to 0.7 points per game. b is roughly what an average team earns. With those two you can predict a team's points from its goal difference alone, and the teams sitting far above the line are winning more than their goals say they should.

Chapter 3 moves on to logistic regression, which predicts a probability, like the chance of a home win.

Leagues