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.
- Pick a league on the board. The code follows it.
- Save the code as
home.pyand runpython home.py. - Press Show best curve on the board. Your w and b should match it.
- Look at the predictions. Which match does the model call closest to a coin flip, and do you agree?
- Set
learning_rateto 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%}")