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%.
- Pick a league on the board. The code follows it.
- Save it as
network.pyand runpython network.py. - Which network is best on the validation matches, and is it the one with the lowest training loss?
- Find the backpropagation lines. Why does
1.0 if z1[j] > 0 else 0.0appear 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%}")