Machine learning with football · Chapter 8 · Neural networks

Programming exercise

A neural network and a softmax written from scratch in Python, tested on matches they have never seen.

Estimated time: 15 minutes · page 7 of 7

A network from scratch

The first script writes a neural network in plain Python, about forty lines. It has two inputs, one hidden layer of ReLU neurons and a sigmoid output, with backpropagation written out by hand. It trains networks with 0, 4 and 16 hidden neurons to predict draws, using team strengths from the earlier matches only, and checks each on the latest 20%.

  1. Pick a league on the board. The code follows it.
  2. Save it as network.py and run python network.py.
  3. Which network is best on the validation matches, and is it the one with the lowest training loss?
  4. Find the backpropagation lines. Why does 1.0 if z1[j] > 0 else 0.0 appear there?
import json
import math
import random
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))

# Honest setup: the latest 20% of matches are kept back, and each team's strength
# (goal difference per game) comes from the earlier 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)
goals, games = {}, {}
for m in played[:cut]:
    for team, d 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) + d
        games[team] = games.get(team, 0) + 1

def rows(matches):
    # Two inputs: home strength and away strength. Label: 1 for a draw.
    return [([goals[m["home_team_id"]] / games[m["home_team_id"]], goals[m["away_team_id"]] / games[m["away_team_id"]]],
             1 if m["home_goals"] == m["away_goals"] else 0)
            for m in matches if m["home_team_id"] in goals and m["away_team_id"] in goals]

train, validation = rows(played[:cut]), rows(played[cut:])

def sigmoid(z):
    return 1 / (1 + math.exp(-max(-30, min(30, z))))

def relu(z):
    return max(0.0, z)

class Network:
    """Two inputs, one hidden layer of ReLU neurons, one sigmoid output. hidden=0 is plain logistic regression."""

    def __init__(self, hidden, seed=1):
        rnd = random.Random(seed)
        self.hidden = hidden
        self.w1 = [[rnd.uniform(-1, 1) for _ in range(2)] for _ in range(hidden)]
        self.b1 = [0.0] * hidden
        self.w2 = [rnd.uniform(-1, 1) for _ in range(hidden or 2)]  # with no hidden layer the output reads the inputs
        self.b2 = 0.0

    def forward(self, x):
        z1 = [w[0] * x[0] + w[1] * x[1] + b for w, b in zip(self.w1, self.b1)]
        a1 = [relu(z) for z in z1] if self.hidden else x
        return z1, a1, sigmoid(sum(w * a for w, a in zip(self.w2, a1)) + self.b2)

    def step(self, data, rate):
        g1 = [[0.0, 0.0] for _ in range(self.hidden)]
        gb1 = [0.0] * self.hidden
        g2 = [0.0] * len(self.w2)
        gb2 = 0.0
        for x, y in data:
            z1, a1, p = self.forward(x)
            error = p - y                     # the output error, as in logistic regression
            gb2 += error
            for j, a in enumerate(a1):
                g2[j] += error * a
            for j in range(self.hidden):      # backpropagation: pass the error back through each ReLU
                d = error * self.w2[j] * (1.0 if z1[j] > 0 else 0.0)
                g1[j][0] += d * x[0]
                g1[j][1] += d * x[1]
                gb1[j] += d
        n = len(data)
        self.w2 = [w - rate * g / n for w, g in zip(self.w2, g2)]
        self.b2 -= rate * gb2 / n
        self.w1 = [[w[0] - rate * g[0] / n, w[1] - rate * g[1] / n] for w, g in zip(self.w1, g1)]
        self.b1 = [b - rate * g / n for b, g in zip(self.b1, gb1)]

    def loss(self, data):
        return -sum(y * math.log(self.forward(x)[2]) + (1 - y) * math.log(1 - self.forward(x)[2]) for x, y in data) / len(data)

print(f"{len(train)} training and {len(validation)} validation matches, {sum(y for _, y in train)} training draws\n")
for hidden in (0, 4, 16):
    net = Network(hidden)
    for _ in range(3000):
        net.step(train, 0.3)
    weights = (3 * hidden + hidden + 1) if hidden else 3
    print(f"hidden neurons {hidden:>2} ({weights:>2} parameters): training {net.loss(train):.4f}   validation {net.loss(validation):.4f}")

net = Network(4)
for _ in range(3000):
    net.step(train, 0.3)
print("\ndraw chance from the 4-neuron network:")
for home, away in ((0, 0), (1, 1), (-1, -1), (1, -1), (-1, 1)):
    print(f"   home strength {home:+d}, away strength {away:+d}: {net.forward([home, away])[2]:.0%}")

Softmax by hand

The second script predicts all three results. It trains a softmax and a one-vs-all model side by side, prints both for one example match with their sums, then tests the softmax on the latest matches against "always home win" and a three-way coin flip.

  1. Run it. Does one-vs-all add up to 100%?
  2. How often does softmax pick the right result, compared with always saying home win?
  3. Give the softmax a hidden layer, reusing the network from the first script. Does it help on the test matches?
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))

played = sorted(get(f"/fixtures?league_id={LEAGUE}&status=FT&limit=200"), key=lambda m: m["fixture_date"])
cut = int(len(played) * 0.8)
goals, games = {}, {}
for m in played[:cut]:
    for team, d 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) + d
        games[team] = games.get(team, 0) + 1

NAMES = ["home win", "draw", "away win"]

def rows(matches):
    out = []
    for m in matches:
        if m["home_team_id"] in goals and m["away_team_id"] in goals:
            x = [goals[m["home_team_id"]] / games[m["home_team_id"]], goals[m["away_team_id"]] / games[m["away_team_id"]]]
            c = 0 if m["home_goals"] > m["away_goals"] else 1 if m["home_goals"] == m["away_goals"] else 2
            out.append((x, c))
    return out

train, test = rows(played[:cut]), rows(played[cut:])

def softmax(scores):
    top = max(scores)
    e = [math.exp(s - top) for s in scores]
    return [v / sum(e) for v in e]

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

def scores(w, x):
    return [row[0] + row[1] * x[0] + row[2] * x[1] for row in w]

# Softmax: one score per class, turned into probabilities that add up to 1, all trained together.
soft = [[0.0, 0.0, 0.0] for _ in range(3)]
# One-vs-all: three separate yes/no models, each with its own sigmoid.
ova = [[0.0, 0.0, 0.0] for _ in range(3)]
for _ in range(2000):
    gs = [[0.0] * 3 for _ in range(3)]
    go = [[0.0] * 3 for _ in range(3)]
    for x, c in train:
        p_soft = softmax(scores(soft, x))
        p_ova = [sigmoid(s) for s in scores(ova, x)]
        for k in range(3):
            target = 1 if k == c else 0
            for i, xi in enumerate([1, x[0], x[1]]):
                gs[k][i] += (p_soft[k] - target) * xi
                go[k][i] += (p_ova[k] - target) * xi
    soft = [[w - 0.3 * g / len(train) for w, g in zip(row, grow)] for row, grow in zip(soft, gs)]
    ova = [[w - 0.3 * g / len(train) for w, g in zip(row, grow)] for row, grow in zip(ova, go)]

print("one match between an average home side and a strong visitor (strengths 0 and +1):")
x = [0, 1]
p_ova = [sigmoid(s) for s in scores(ova, x)]
p_soft = softmax(scores(soft, x))
print("   one-vs-all: " + ", ".join(f"{n} {p:.0%}" for n, p in zip(NAMES, p_ova)) + f"   (sum {sum(p_ova):.0%})")
print("   softmax:    " + ", ".join(f"{n} {p:.0%}" for n, p in zip(NAMES, p_soft)) + f"   (sum {sum(p_soft):.0%})\n")

correct = sum(1 for x, c in test if max(range(3), key=lambda k: softmax(scores(soft, x))[k]) == c)
log_loss = -sum(math.log(softmax(scores(soft, x))[c]) for x, c in test) / len(test)
always_home = sum(1 for _, c in test if c == 0)
print(f"{len(test)} test matches: softmax picks the right result in {correct} ({correct / len(test):.0%}),")
print(f"'always home win' in {always_home} ({always_home / len(test):.0%}). Softmax test log loss {log_loss:.3f}, a three-way coin flip {math.log(3):.3f}")

Check yourself

In the first script, the 16-neuron network has the lowest training loss and often the worst validation loss. Why?
In the second script, why does softmax always add up to 100% while one-vs-all does not?

What the chapter adds up to

A neural network is neurons in layers, each a small linear model followed by a nonlinear activation, trained by backpropagation. It can find patterns no single line can, such as where draws cluster, without being told which features to cross. That flexibility needs data. On a hundred matches it overfits quickly, so chapter 7's habits matter more than ever: a validation set, early stopping, regularization. Google's course goes on from here to embeddings, large language models and production systems.

Leagues