Een fietsteller aan de VUB in Brussel, uur per uur, vier en een half jaar lang: de reeks in de tijd splitsen, drie vuistregels meten, een GRU in PyTorch trainen die de tellingen uur per uur leest, en zien op welke dagen hij zich vergist.
Uitvoeren in Google ColabColab vereist een Google-account, maar je kan de notebook ook .
Hoofdstuk nog niet online. Deze notebook is af, maar het hoofdstuk waar ze bij hoort staat nog niet online. Links naar dat hoofdstuk werken dus misschien nog niet, en voorlopig is ze geen examenleerstof.
Leesmodus. Hieronder staat de hele notebook, met de uitvoer van de code erbij. Je kan de volledige inhoud dus gewoon hier lezen. Om code aan te passen en de gevolgen te zien, kan je naar Google Colab (externe link) gaan.
In the chapter Recurrent Neural Networks, a recurrent network predicted how many shared bikes would be taken in the next hour: it read the series hour by hour and kept a memory of what it had seen. This notebook does the same with real data, in PyTorch (externe link): a counter in Brussels that counts the cyclists who pass, day and night.
You will:
- 🚲 load four and a half years of counts, hour by hour;
- ✂️ split them in time, and 📏 measure three rules of thumb to beat;
- 🧠 train a GRU that reads the counts hour by hour;
- 📈 measure it once on the year that came after, and see on which days it goes wrong.
Prior knowledge: the chapter Recurrent Neural Networks. The training function comes from the neural networks notebook. You can run the whole notebook without changing a single line.
Estimated time: about 30 minutes.
This notebook is part of AI voor Iedereen (KU Leuven). The latest version is always at ai.kuleuven.be/aivooriedereen/en/notebook/recurrent-networks, and you can open it directly in Google Colab (externe link).
🚀 First time in a notebook?
Then the short introductory notebook explains everything step by step. The most important things:
- Make your own copy: File → Save a copy in Drive (in the menu at the top left), and work in that copy.
- Run a cell by clicking in it and pressing Shift+Enter, or with the ▶ button to its left. The result appears below the cell.
- Run the cells in order, from top to bottom, because a cell uses what the cells above it made. Does something behave strangely? Choose Runtime → Restart session and run everything again from the top.
Prefer not to use Google? Download the notebook file and open it in Jupyter (externe link) or Visual Studio Code (externe link), with PyTorch (torch), pandas and matplotlib installed.
🐍 Python in this notebook
New to Python? The introductory notebook explains the basics: variables, lists, loops and functions. The neural networks notebook explains tensors, layers and training. On top of those, this notebook uses:
| Code | Meaning |
|---|---|
pd.read_csv(url) | Reads a table with pandas, here straight from a web address. |
bikes.resample("h").sum() | Adds up the counts per hour. |
bikes.loc["2025-01":"2025-06"] | The hours from January to June 2025. |
bikes.shift(24) | Moves the series 24 hours on: next to every hour comes the count of the same hour a day earlier. |
np.eye(24)[hours] | For every hour, a row of 24 zeros with a 1 in the column of its hour of the day. |
nn.GRU(32, 32, batch_first=True) | A GRU layer: 32 numbers come in at every step, and it keeps a memory of 32 numbers. batch_first=True says that the windows come first and the hours second. |
nn.MSELoss() | The mean squared error: the loss for predicting a number. |
🚲 Loading a bike counter
Brussels Mobility counts the cyclists at 18 places in Brussels, every quarter of an hour, and puts the counts online (externe link), free and without a key. We take the counter on the Boulevard Général Jacques, next to the campus of the VUB in Ixelles, from January 2022 to June 2026.
Every row is a quarter of an hour: the date, the number of the quarter (1 is from 0:00 to 0:15) and the number of cyclists. The quarters are in UTC, the time of Greenwich, one or two hours behind Belgian time, so the code converts them to Belgian time while it adds up the four quarters of every hour.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import torch
from torch import nn
COUNTER = "CEK049" # the counter on the Boulevard Général Jacques (VUB)
counts = pd.read_csv("https://data.mobility.brussels/bike/api/counts/?request=history&outputFormat=csv"
f"&featureID={COUNTER}&startDate=20220101&endDate=20260630")
print(counts.head(3), "\n")
quarters = (pd.to_datetime(counts["Date"]).dt.tz_localize("UTC")
+ pd.to_timedelta(15 * (counts["Time gap"] - 1), unit="min")) # quarter 1 starts at 0:00
bikes = counts.set_index(quarters)["Count"].resample("h").sum(min_count=1) # the cyclists per hour
bikes = bikes.tz_convert("Europe/Brussels").loc["2022":"2026-06"] # in Belgian time
print("hours without a count:", list(bikes[bikes.isna()].index.strftime("%d %b %Y %H:%M")))
bikes = bikes.interpolate() # fill them with the value halfway between their neighbors
print(f"{len(bikes)} hours, on average {bikes.mean():.0f} cyclists per hour")
bikes.loc["2024-10-07":"2024-10-13"].plot(figsize=(12, 3.5), ylabel="cyclists per hour", xlabel="")
plt.show()Date Time gap Count Average speed 0 2022-01-01 1 3 22 1 2022-01-01 2 14 17 2 2022-01-01 3 6 19 hours without a count: ['30 Oct 2022 23:00', '29 Oct 2023 23:00', '27 Oct 2024 23:00', '26 Oct 2025 23:00'] 39406 hours, on average 90 cyclists per hour
A week in October 2024: on every weekday a sharp peak at 8:00 and a wider one at 17:00 and 18:00, and a calmer weekend. Four hours have no count at all: one a year, each on the evening the clocks go back to winter time. interpolate fills them in.
✂️ Splitting in time
Before anything else, put the test data aside. For a time series, that means: never shuffle the hours, but learn from the past and test on what came after. If the network learns from Tuesday 9:00 and is then tested on Tuesday 8:00, it has already half seen the answer: a data leak. We use three periods:
- learning: 2022 to 2024, three years to learn from;
- checking: January to June 2025, to decide during training which epoch is best;
- testing: July 2025 to June 2026, a whole year, measured once at the very end.
learn = bikes.loc[:"2024"]
check = bikes.loc["2025-01":"2025-06"]
test = bikes.loc["2025-07":]
plt.figure(figsize=(12, 3.5))
for period, color in [(learn, "#3b82f6"), (check, "#8b5cf6"), (test, "#f97316")]:
plt.plot(period.resample("D").sum(), color=color, linewidth=0.8) # cyclists per day
plt.legend(["learning", "checking", "testing"])
plt.ylabel("cyclists per day")
plt.show()Every year has the same rhythm: busy in the autumn and the spring, quiet at Christmas and in the summer holidays. And in 2025, more people cycled here than in the three years before.
📏 Measuring three rules of thumb
Before training a network, measure what simple rules of thumb get. For every hour, the three rules predict:
- the count of the hour before;
- the count of the same hour yesterday;
- the count of the same hour a week earlier.
shift moves the series 1, 24 or 168 hours on, and mean_error measures how many cyclists per hour a prediction is off, on average, over the hours of one period. For now, we only measure on the checking months: the test year waits until the end.
rules = {
"same as the previous hour": bikes.shift(1),
"same hour yesterday": bikes.shift(24),
"same hour last week": bikes.shift(168),
}
def mean_error(prediction, period):
# How many cyclists per hour a prediction is off, on average, over the hours of one period
return (prediction - bikes).loc[period.index].abs().mean()
for name, prediction in rules.items():
print(f"{name:27s} {mean_error(prediction, check):5.1f} cyclists per hour off")same as the previous hour 36.3 cyclists per hour off same hour yesterday 30.0 cyclists per hour off same hour last week 24.5 cyclists per hour off
The best rule is the same hour last week: about 25 cyclists per hour off, against 30 for the same hour yesterday and 36 for the previous hour. A Saturday looks more like the Saturday before than like the Friday before it. And the previous hour never sees a rush coming: at 7:00, it doesn't know that 8:00 is the busiest hour of the day.
🧠 Training a GRU
The GRU gets 32 numbers for every hour:
- the count, divided by the average hour of the learning years, so that the network works with numbers around 1;
- the hour of the day: 24 columns, with a 1 in the column of this hour;
- the day of the week: 7 columns, with a 1 in the column of this day.
The network in the chapter only got the counts, and had to work out by itself what time it was. The calendar is known in advance anyway, so we simply give it.
scale = learn.mean() # the average hour of 2022 to 2024
hours = np.eye(24)[bikes.index.hour] # a 1 in the column of the hour of the day
days = np.eye(7)[bikes.index.dayofweek] # a 1 in the column of the day of the week (0 is Monday)
inputs = torch.tensor(np.column_stack([bikes / scale, hours, days]), dtype=torch.float32)
print(inputs.shape) # a row of 32 numbers for every hourtorch.Size([39406, 32])
The network learns from windows of one week (168 hours), with a new window starting every day. It reads a window hour by hour, and after every hour it predicts the count of the next hour; one step later, it knows how far off it was. windows cuts the windows of one period out of the inputs, with for every hour the count of the hour after it: the answer the network has to give.
Forecaster is the network itself: a GRU with a memory of 32 numbers, and a layer that reads a prediction from that memory after every hour.
def windows(period):
# Windows of one week, one starting every day of the period: the 168 hours that go in,
# and for every hour the count of the next hour, the answer the network has to give
first = bikes.index.get_loc(period.index[0]) # the position of the first hour of the period
starts = range(first, first + len(period) - 168, 24)
X = torch.stack([inputs[s:s + 168] for s in starts])
y = torch.stack([inputs[s + 1:s + 169, 0] for s in starts]) # column 0: the count
return X, y
class Forecaster(nn.Module):
# A GRU that reads the hours one by one, and after every hour predicts the count of the next hour
def __init__(self, numbers_per_hour, memory):
super().__init__()
self.gru = nn.GRU(numbers_per_hour, memory, batch_first=True)
self.out = nn.Linear(memory, 1)
def forward(self, hours):
memory, _ = self.gru(hours) # the memory after every hour
return self.out(memory).squeeze(-1) # a prediction after every hour
X_learn, y_learn = windows(learn)
X_check, y_check = windows(check)
print(len(X_learn), "windows to learn from,", len(X_check), "to check")1089 windows to learn from, 174 to check
train and plot_curves are the functions from the neural networks notebook, with one change: the loss is nn.MSELoss(), because the network predicts a number instead of a class (so there is no accuracy to measure either). train shuffles the windows of the learning years, which is fine: inside every window, the hours stay in their order, and the checking and testing periods stay apart.
import copy
import time
from torch.utils.data import DataLoader, TensorDataset
def train(model, X, y, X_val, y_val, epochs, learning_rate=0.001):
# Trains on X and y in minibatches and measures both losses after every epoch;
# at the end, the model gets the weights of the epoch with the lowest validation loss
batches = DataLoader(TensorDataset(X, y), batch_size=128, shuffle=True)
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
loss_function = nn.MSELoss() # the mean squared error, for predicting a number
history = {"training": [], "validation": [], "seconds": []}
best_loss = float("inf")
for epoch in range(epochs):
start = time.perf_counter()
for X_batch, y_batch in batches:
loss = loss_function(model(X_batch), y_batch)
optimizer.zero_grad()
loss.backward()
optimizer.step()
history["seconds"].append(time.perf_counter() - start)
with torch.no_grad():
history["training"].append(loss_function(model(X), y).item())
history["validation"].append(loss_function(model(X_val), y_val).item())
# the best epoch so far: keep a copy of its weights
if history["validation"][-1] < best_loss:
best_loss = history["validation"][-1]
best_weights = copy.deepcopy(model.state_dict())
history["best_epoch"] = epoch + 1
model.load_state_dict(best_weights)
return history
def plot_curves(history):
# The two learning curves, with a dashed line at the epoch whose weights train kept
epochs = range(1, len(history["training"]) + 1)
plt.plot(epochs, history["training"], label="learning years")
plt.plot(epochs, history["validation"], label="checking months")
plt.axvline(history["best_epoch"], color="grey", linestyle="--", label="lowest validation loss")
plt.xlabel("epoch")
plt.ylabel("loss (mean squared error)")
plt.legend()
plt.show()torch.manual_seed(0)
forecaster = Forecaster(inputs.shape[1], 32)
history = train(forecaster, X_learn, y_learn, X_check, y_check, epochs=60, learning_rate=0.01)
print(f"{sum(p.numel() for p in forecaster.parameters())} weights, trained in {sum(history['seconds']):.0f} seconds; "
f"lowest validation loss after epoch {history['best_epoch']}")
plot_curves(history)6369 weights, trained in 25 seconds; lowest validation loss after epoch 60
Both curves drop fast in the first ten epochs, and then slowly. The checking months stay just above the learning years: the network doesn't learn the learning years by heart. The lowest validation loss comes at the end, so training longer would still help a little, but every epoch costs time.
📜 Reading the whole series in one run
To predict, the network doesn't need windows: the same GRU can read a series of any length. So it reads all hours from January 2022 on in one run, and keeps its memory along the way. What it predicts after an hour is meant for the hour after it, so shift(1) puts every prediction next to the hour it is for. And a count is never negative, so clip turns the few negative predictions, mostly at night, into 0.
with torch.no_grad():
after_every_hour = forecaster(inputs.unsqueeze(0))[0] * scale # one run over all hours
gru = pd.Series(after_every_hour.numpy(), index=bikes.index).shift(1).clip(lower=0)
print(f"GRU: {mean_error(gru, check):.1f} cyclists per hour off in the checking months")GRU: 10.7 cyclists per hour off in the checking months
On the checking months, the GRU is about 11 cyclists per hour off: less than half of the best rule of thumb.
📈 Measuring once on the test year
Only now, with everything decided, comes the test year: July 2025 to June 2026, which neither the network nor we have looked at.
results = {name: mean_error(prediction, test) for name, prediction in rules.items()}
results["GRU"] = mean_error(gru, test)
for name, error in results.items():
print(f"{name:27s} {error:5.1f} cyclists per hour off")
print(f"\non average, {test.mean():.0f} cyclists per hour passed in the test year")same as the previous hour 37.1 cyclists per hour off same hour yesterday 29.9 cyclists per hour off same hour last week 26.3 cyclists per hour off GRU 11.4 cyclists per hour off on average, 98 cyclists per hour passed in the test year
On the test year too, the GRU is about 11 cyclists per hour off, against 26 for the best rule of thumb, the same hour last week. On average, 98 cyclists passed per hour.
🔍 Looking at the worst days
Where does the GRU go wrong? The plot shows one week of the test year, with the predictions of the GRU and of the best rule of thumb. Below it are the five days on which the GRU was furthest off.
week = slice("2026-05-25", "2026-05-31")
plt.figure(figsize=(12, 4))
plt.plot(bikes.loc[week], color="black", label="counted")
plt.plot(rules["same hour last week"].loc[week], color="grey", linestyle=":", label="same hour last week")
plt.plot(gru.loc[week], color="#f97316", label="GRU")
plt.ylabel("cyclists per hour")
plt.legend()
plt.show()
errors = (gru - bikes).loc[test.index].abs()
per_day = errors.groupby(errors.index.date).mean()
for day, error in per_day.nlargest(5).items():
print(f"{day:%a %d %b %Y}: {error:4.0f} cyclists per hour off, {bikes.loc[str(day)].sum():5.0f} cyclists that day")Sun 31 May 2026: 35 cyclists per hour off, 2901 cyclists that day Sun 21 Sep 2025: 27 cyclists per hour off, 1815 cyclists that day Thu 25 Jun 2026: 19 cyclists per hour off, 3254 cyclists that day Mon 25 May 2026: 19 cyclists per hour off, 2250 cyclists that day Thu 16 Apr 2026: 19 cyclists per hour off, 3452 cyclists that day
Most of the week, the GRU stays close to the counts, closer than the rule of thumb. Two of the five days are in this week:
- Whit Monday (25 May) is a holiday. The rule of thumb expects an ordinary Monday, with 364 cyclists at 8:00, but only 58 came. At 7:00, the GRU sees that it is unusually quiet (35 cyclists instead of 163 a week earlier) and predicts about 100 for 8:00: still too many, because the calendar it gets only says Monday.
- Sunday 31 May is the worst day of the test year. At noon, 425 cyclists passed, where a Sunday usually has about 100. The GRU follows the rise, but one hour late.
The second worst day, Sunday 21 September 2025, was the car-free Sunday (externe link): no cars in the whole Brussels region from 9:30 to 19:00. At 19:00, the counter saw 241 cyclists, against 95 a week earlier.
None of this was in the inputs: the network only knows the counts, the hour and the day of the week.
🧰 Your own time series
The recipe:
- Put your series in pandas, with one value per time step, and look at it before anything else. Fill the few gaps, and watch out for values that are not real: most counters of Brussels Mobility report 0 cyclists for days or weeks at some point, which is a broken counter or a closed bike path, not an empty street. Then split in time: learn from the past, check on what came after, and keep a test period for the very end.
- Measure the rules of thumb first: the previous step, and the same moment a day, a week or a year earlier, whichever rhythm your data has.
- Give the network the series, divided by its average, and everything you know in advance: the calendar, holidays, the weather forecast.
- Train on windows that hold at least one full rhythm (a week, for hours), with a prediction after every step, using
trainandplot_curves. Then let the network read the whole series in one run, and measure once on the test period.
nn.LSTM or a plain nn.RNN instead of nn.GRU is a change of one word. Here, the LSTM does about as well, and a plain RNN is only about one cyclist per hour worse: gates pay off when a network has to remember something for a long time. And as the chapter advises, also try a simple model on a window: a straight line on the last week of counts, with the same calendar, gets about 16 here. That beats every rule of thumb, but not the GRU.
To predict further ahead, a whole day for instance, let the last layer give 24 numbers instead of one: a prediction for each of the next 24 hours.
By Thomas Winters (externe link) for AI voor Iedereen, KU Leuven. The latest version of this notebook: ai.kuleuven.be/aivooriedereen/en/notebook/recurrent-networks.
