{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "8a66e56d",
   "metadata": {},
   "source": [
    "# 🔁 Recurrent networks in Python\n",
    "\n",
    "In the chapter [Recurrent Neural Networks](https://ai.kuleuven.be/aivooriedereen/recurrente-neurale-netwerken), 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](https://pytorch.org): a counter in Brussels that counts the cyclists who pass, day and night.\n",
    "\n",
    "You will:\n",
    "\n",
    "1. 🚲 load four and a half years of counts, hour by hour;\n",
    "2. ✂️ split them in time, and 📏 measure three rules of thumb to beat;\n",
    "3. 🧠 train a GRU that reads the counts hour by hour;\n",
    "4. 📈 measure it once on the year that came after, and see on which days it goes wrong.\n",
    "\n",
    "**Prior knowledge**: the chapter [Recurrent Neural Networks](https://ai.kuleuven.be/aivooriedereen/recurrente-neurale-netwerken). The training function comes from the [neural networks notebook](https://ai.kuleuven.be/aivooriedereen/en/notebook/neural-networks). You can run the whole notebook without changing a single line.\n",
    "\n",
    "**Estimated time**: about 30 minutes.\n",
    "\n",
    "*This notebook is part of [AI voor Iedereen](https://ai.kuleuven.be/aivooriedereen/en) (KU Leuven). The latest version is always at [ai.kuleuven.be/aivooriedereen/en/notebook/recurrent-networks](https://ai.kuleuven.be/aivooriedereen/en/notebook/recurrent-networks), and you can open it directly in [Google Colab](https://colab.research.google.com/drive/13uAjokcIp1YeKN3Z2F2yQdtKO9maLq1f?usp=sharing).*"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d7e57e80",
   "metadata": {},
   "source": [
    "## 🚀 First time in a notebook?\n",
    "\n",
    "Then the short [introductory notebook](https://ai.kuleuven.be/aivooriedereen/en/notebook/python-basics) explains everything step by step. The most important things:\n",
    "\n",
    "1. **Make your own copy**: *File → Save a copy in Drive* (in the menu at the top left), and work in that copy.\n",
    "2. **Run a cell** by clicking in it and pressing **Shift+Enter**, or with the ▶ button to its left. The result appears below the cell.\n",
    "3. **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.\n",
    "\n",
    "**Prefer not to use Google?** Download [the notebook file](https://ai.kuleuven.be/aivooriedereen/notebooks/recurrent-networks.ipynb) and open it in [Jupyter](https://jupyter.org/install) or [Visual Studio Code](https://code.visualstudio.com/docs/datascience/jupyter-notebooks), with PyTorch (`torch`), pandas and matplotlib installed."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5527b29d",
   "metadata": {},
   "source": [
    "## 🐍 Python in this notebook\n",
    "\n",
    "New to Python? The [introductory notebook](https://ai.kuleuven.be/aivooriedereen/en/notebook/python-basics) explains the basics: variables, lists, loops and functions. The [neural networks notebook](https://ai.kuleuven.be/aivooriedereen/en/notebook/neural-networks) explains tensors, layers and training. On top of those, this notebook uses:\n",
    "\n",
    "| Code | Meaning |\n",
    "| --- | --- |\n",
    "| `pd.read_csv(url)` | Reads a table with pandas, here straight from a web address. |\n",
    "| `bikes.resample(\"h\").sum()` | Adds up the counts per hour. |\n",
    "| `bikes.loc[\"2025-01\":\"2025-06\"]` | The hours from January to June 2025. |\n",
    "| `bikes.shift(24)` | Moves the series 24 hours on: next to every hour comes the count of the same hour a day earlier. |\n",
    "| `np.eye(24)[hours]` | For every hour, a row of 24 zeros with a 1 in the column of its hour of the day. |\n",
    "| `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. |\n",
    "| `nn.MSELoss()` | The mean squared error: the loss for predicting a number. |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b170a4c4",
   "metadata": {},
   "source": [
    "## 🚲 Loading a bike counter\n",
    "\n",
    "Brussels Mobility counts the cyclists at 18 places in Brussels, every quarter of an hour, and [puts the counts online](https://data.mobility.brussels/bike/api/counts/), 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.\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "code",
   "id": "75cf33f3",
   "metadata": {},
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import torch\n",
    "from torch import nn\n",
    "\n",
    "COUNTER = \"CEK049\"     # the counter on the Boulevard Général Jacques (VUB)\n",
    "counts = pd.read_csv(\"https://data.mobility.brussels/bike/api/counts/?request=history&outputFormat=csv\"\n",
    "                     f\"&featureID={COUNTER}&startDate=20220101&endDate=20260630\")\n",
    "print(counts.head(3), \"\\n\")\n",
    "\n",
    "quarters = (pd.to_datetime(counts[\"Date\"]).dt.tz_localize(\"UTC\")\n",
    "            + pd.to_timedelta(15 * (counts[\"Time gap\"] - 1), unit=\"min\"))      # quarter 1 starts at 0:00\n",
    "bikes = counts.set_index(quarters)[\"Count\"].resample(\"h\").sum(min_count=1)      # the cyclists per hour\n",
    "bikes = bikes.tz_convert(\"Europe/Brussels\").loc[\"2022\":\"2026-06\"]             # in Belgian time\n",
    "print(\"hours without a count:\", list(bikes[bikes.isna()].index.strftime(\"%d %b %Y %H:%M\")))\n",
    "bikes = bikes.interpolate()        # fill them with the value halfway between their neighbors\n",
    "print(f\"{len(bikes)} hours, on average {bikes.mean():.0f} cyclists per hour\")\n",
    "\n",
    "bikes.loc[\"2024-10-07\":\"2024-10-13\"].plot(figsize=(12, 3.5), ylabel=\"cyclists per hour\", xlabel=\"\")\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "6c52fd64",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8edcf633",
   "metadata": {},
   "source": [
    "## ✂️ Splitting in time\n",
    "\n",
    "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](https://ai.kuleuven.be/aivooriedereen/recurrente-neurale-netwerken#hoe-leert-een-recurrent-netwerk). 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](https://ai.kuleuven.be/aivooriedereen/en/model-evaluation#data-leakage). We use three periods:\n",
    "\n",
    "- **learning**: 2022 to 2024, three years to learn from;\n",
    "- **checking**: January to June 2025, to decide during training which epoch is best;\n",
    "- **testing**: July 2025 to June 2026, a whole year, measured once at the very end."
   ]
  },
  {
   "cell_type": "code",
   "id": "0c226a2e",
   "metadata": {},
   "source": [
    "learn = bikes.loc[:\"2024\"]\n",
    "check = bikes.loc[\"2025-01\":\"2025-06\"]\n",
    "test = bikes.loc[\"2025-07\":]\n",
    "\n",
    "plt.figure(figsize=(12, 3.5))\n",
    "for period, color in [(learn, \"#3b82f6\"), (check, \"#8b5cf6\"), (test, \"#f97316\")]:\n",
    "    plt.plot(period.resample(\"D\").sum(), color=color, linewidth=0.8)      # cyclists per day\n",
    "plt.legend([\"learning\", \"checking\", \"testing\"])\n",
    "plt.ylabel(\"cyclists per day\")\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "0a123d13",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "## 📏 Measuring three rules of thumb\n",
    "\n",
    "Before training a network, [measure what simple rules of thumb get](https://ai.kuleuven.be/aivooriedereen/recurrente-neurale-netwerken#wanneer-niet-gebruiken). For every hour, the three rules predict:\n",
    "\n",
    "- the count of the hour before;\n",
    "- the count of the same hour yesterday;\n",
    "- the count of the same hour a week earlier.\n",
    "\n",
    "`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."
   ]
  },
  {
   "cell_type": "code",
   "id": "1628a311",
   "metadata": {},
   "source": [
    "rules = {\n",
    "    \"same as the previous hour\": bikes.shift(1),\n",
    "    \"same hour yesterday\": bikes.shift(24),\n",
    "    \"same hour last week\": bikes.shift(168),\n",
    "}\n",
    "\n",
    "\n",
    "def mean_error(prediction, period):\n",
    "    # How many cyclists per hour a prediction is off, on average, over the hours of one period\n",
    "    return (prediction - bikes).loc[period.index].abs().mean()\n",
    "\n",
    "\n",
    "for name, prediction in rules.items():\n",
    "    print(f\"{name:27s} {mean_error(prediction, check):5.1f} cyclists per hour off\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "c6ec540f",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3dab3861",
   "metadata": {},
   "source": [
    "## 🧠 Training a GRU\n",
    "\n",
    "The GRU gets 32 numbers for every hour:\n",
    "\n",
    "- the count, divided by the average hour of the learning years, so that the network works with numbers around 1;\n",
    "- the hour of the day: 24 columns, with a 1 in the column of this hour;\n",
    "- the day of the week: 7 columns, with a 1 in the column of this day.\n",
    "\n",
    "The [network in the chapter](https://ai.kuleuven.be/aivooriedereen/recurrente-neurale-netwerken#meer-neuronen-de-verborgen-toestand) 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."
   ]
  },
  {
   "cell_type": "code",
   "id": "4d9cfe47",
   "metadata": {},
   "source": [
    "scale = learn.mean()                                  # the average hour of 2022 to 2024\n",
    "hours = np.eye(24)[bikes.index.hour]                  # a 1 in the column of the hour of the day\n",
    "days = np.eye(7)[bikes.index.dayofweek]               # a 1 in the column of the day of the week (0 is Monday)\n",
    "inputs = torch.tensor(np.column_stack([bikes / scale, hours, days]), dtype=torch.float32)\n",
    "print(inputs.shape)                                   # a row of 32 numbers for every hour"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "563f10bf",
   "metadata": {},
   "source": [
    "The network [learns](https://ai.kuleuven.be/aivooriedereen/recurrente-neurale-netwerken#hoe-leert-een-recurrent-netwerk) 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.\n",
    "\n",
    "`Forecaster` is the network itself: a [GRU](https://ai.kuleuven.be/aivooriedereen/recurrente-neurale-netwerken#gru-en-lstm) with a memory of 32 numbers, and a layer that reads a prediction from that memory after every hour."
   ]
  },
  {
   "cell_type": "code",
   "id": "2b869a0d",
   "metadata": {},
   "source": [
    "def windows(period):\n",
    "    # Windows of one week, one starting every day of the period: the 168 hours that go in,\n",
    "    # and for every hour the count of the next hour, the answer the network has to give\n",
    "    first = bikes.index.get_loc(period.index[0])                   # the position of the first hour of the period\n",
    "    starts = range(first, first + len(period) - 168, 24)\n",
    "    X = torch.stack([inputs[s:s + 168] for s in starts])\n",
    "    y = torch.stack([inputs[s + 1:s + 169, 0] for s in starts])     # column 0: the count\n",
    "    return X, y\n",
    "\n",
    "\n",
    "class Forecaster(nn.Module):\n",
    "    # A GRU that reads the hours one by one, and after every hour predicts the count of the next hour\n",
    "    def __init__(self, numbers_per_hour, memory):\n",
    "        super().__init__()\n",
    "        self.gru = nn.GRU(numbers_per_hour, memory, batch_first=True)\n",
    "        self.out = nn.Linear(memory, 1)\n",
    "\n",
    "    def forward(self, hours):\n",
    "        memory, _ = self.gru(hours)                # the memory after every hour\n",
    "        return self.out(memory).squeeze(-1)        # a prediction after every hour\n",
    "\n",
    "\n",
    "X_learn, y_learn = windows(learn)\n",
    "X_check, y_check = windows(check)\n",
    "print(len(X_learn), \"windows to learn from,\", len(X_check), \"to check\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "9d1bea6a",
   "metadata": {},
   "source": [
    "`train` and `plot_curves` are the functions from the [neural networks notebook](https://ai.kuleuven.be/aivooriedereen/en/notebook/neural-networks#training-in-minibatches), 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."
   ]
  },
  {
   "cell_type": "code",
   "id": "931fc88c",
   "metadata": {},
   "source": [
    "import copy\n",
    "import time\n",
    "from torch.utils.data import DataLoader, TensorDataset\n",
    "\n",
    "\n",
    "def train(model, X, y, X_val, y_val, epochs, learning_rate=0.001):\n",
    "    # Trains on X and y in minibatches and measures both losses after every epoch;\n",
    "    # at the end, the model gets the weights of the epoch with the lowest validation loss\n",
    "    batches = DataLoader(TensorDataset(X, y), batch_size=128, shuffle=True)\n",
    "    optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n",
    "    loss_function = nn.MSELoss()                 # the mean squared error, for predicting a number\n",
    "    history = {\"training\": [], \"validation\": [], \"seconds\": []}\n",
    "    best_loss = float(\"inf\")\n",
    "    for epoch in range(epochs):\n",
    "        start = time.perf_counter()\n",
    "        for X_batch, y_batch in batches:\n",
    "            loss = loss_function(model(X_batch), y_batch)\n",
    "            optimizer.zero_grad()\n",
    "            loss.backward()\n",
    "            optimizer.step()\n",
    "        history[\"seconds\"].append(time.perf_counter() - start)\n",
    "        with torch.no_grad():\n",
    "            history[\"training\"].append(loss_function(model(X), y).item())\n",
    "            history[\"validation\"].append(loss_function(model(X_val), y_val).item())\n",
    "        # the best epoch so far: keep a copy of its weights\n",
    "        if history[\"validation\"][-1] < best_loss:\n",
    "            best_loss = history[\"validation\"][-1]\n",
    "            best_weights = copy.deepcopy(model.state_dict())\n",
    "            history[\"best_epoch\"] = epoch + 1\n",
    "    model.load_state_dict(best_weights)\n",
    "    return history\n",
    "\n",
    "\n",
    "def plot_curves(history):\n",
    "    # The two learning curves, with a dashed line at the epoch whose weights train kept\n",
    "    epochs = range(1, len(history[\"training\"]) + 1)\n",
    "    plt.plot(epochs, history[\"training\"], label=\"learning years\")\n",
    "    plt.plot(epochs, history[\"validation\"], label=\"checking months\")\n",
    "    plt.axvline(history[\"best_epoch\"], color=\"grey\", linestyle=\"--\", label=\"lowest validation loss\")\n",
    "    plt.xlabel(\"epoch\")\n",
    "    plt.ylabel(\"loss (mean squared error)\")\n",
    "    plt.legend()\n",
    "    plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "772232f6",
   "metadata": {},
   "source": [
    "torch.manual_seed(0)\n",
    "forecaster = Forecaster(inputs.shape[1], 32)\n",
    "history = train(forecaster, X_learn, y_learn, X_check, y_check, epochs=60, learning_rate=0.01)\n",
    "print(f\"{sum(p.numel() for p in forecaster.parameters())} weights, trained in {sum(history['seconds']):.0f} seconds; \"\n",
    "      f\"lowest validation loss after epoch {history['best_epoch']}\")\n",
    "plot_curves(history)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "bade65f2",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 📜 Reading the whole series in one run\n",
    "\n",
    "To predict, the network doesn't need windows: [the same GRU can read a series of any length](https://ai.kuleuven.be/aivooriedereen/recurrente-neurale-netwerken#dezelfde-neuron-telkens-opnieuw). 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."
   ]
  },
  {
   "cell_type": "code",
   "id": "39cf55e3",
   "metadata": {},
   "source": [
    "with torch.no_grad():\n",
    "    after_every_hour = forecaster(inputs.unsqueeze(0))[0] * scale     # one run over all hours\n",
    "gru = pd.Series(after_every_hour.numpy(), index=bikes.index).shift(1).clip(lower=0)\n",
    "print(f\"GRU: {mean_error(gru, check):.1f} cyclists per hour off in the checking months\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "cb65d68f",
   "metadata": {},
   "source": [
    "On the checking months, the GRU is about **11** cyclists per hour off: less than half of the best rule of thumb.\n",
    "\n",
    "## 📈 Measuring once on the test year\n",
    "\n",
    "Only now, with everything decided, comes the test year: July 2025 to June 2026, which neither the network nor we have looked at."
   ]
  },
  {
   "cell_type": "code",
   "id": "15cb3887",
   "metadata": {},
   "source": [
    "results = {name: mean_error(prediction, test) for name, prediction in rules.items()}\n",
    "results[\"GRU\"] = mean_error(gru, test)\n",
    "for name, error in results.items():\n",
    "    print(f\"{name:27s} {error:5.1f} cyclists per hour off\")\n",
    "print(f\"\\non average, {test.mean():.0f} cyclists per hour passed in the test year\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "c1f45397",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### 🔍 Looking at the worst days\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "code",
   "id": "c815cc35",
   "metadata": {},
   "source": [
    "week = slice(\"2026-05-25\", \"2026-05-31\")\n",
    "plt.figure(figsize=(12, 4))\n",
    "plt.plot(bikes.loc[week], color=\"black\", label=\"counted\")\n",
    "plt.plot(rules[\"same hour last week\"].loc[week], color=\"grey\", linestyle=\":\", label=\"same hour last week\")\n",
    "plt.plot(gru.loc[week], color=\"#f97316\", label=\"GRU\")\n",
    "plt.ylabel(\"cyclists per hour\")\n",
    "plt.legend()\n",
    "plt.show()\n",
    "\n",
    "errors = (gru - bikes).loc[test.index].abs()\n",
    "per_day = errors.groupby(errors.index.date).mean()\n",
    "for day, error in per_day.nlargest(5).items():\n",
    "    print(f\"{day:%a %d %b %Y}: {error:4.0f} cyclists per hour off, {bikes.loc[str(day)].sum():5.0f} cyclists that day\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "3d321996",
   "metadata": {},
   "source": [
    "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:\n",
    "\n",
    "- **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.\n",
    "- **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.\n",
    "\n",
    "The second worst day, Sunday 21 September 2025, was the [car-free Sunday](https://www.police.be/5343/fr/node/5542): 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.\n",
    "\n",
    "None of this was in the inputs: the network only knows the counts, the hour and the day of the week."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "696ae453",
   "metadata": {},
   "source": [
    "## 🧰 Your own time series\n",
    "\n",
    "The recipe:\n",
    "\n",
    "1. 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.\n",
    "2. 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.\n",
    "3. Give the network the series, divided by its average, and everything you know in advance: the calendar, holidays, the weather forecast.\n",
    "4. Train on windows that hold at least one full rhythm (a week, for hours), with a prediction after every step, using `train` and `plot_curves`. Then let the network read the whole series in one run, and measure once on the test period.\n",
    "\n",
    "`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](https://ai.kuleuven.be/aivooriedereen/recurrente-neurale-netwerken#rnn-tegen-gru-en-lstm) when a network has to remember something for a long time. And as the chapter advises, also try a simple model on a [window](https://ai.kuleuven.be/aivooriedereen/recurrente-neurale-netwerken#een-venster-op-het-verleden): 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.\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "003ee83f",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "*By [Thomas Winters](https://thomaswinters.be) for [AI voor Iedereen](https://ai.kuleuven.be/aivooriedereen/en), KU Leuven. The latest version of this notebook: [ai.kuleuven.be/aivooriedereen/en/notebook/recurrent-networks](https://ai.kuleuven.be/aivooriedereen/en/notebook/recurrent-networks).*"
   ]
  }
 ],
 "metadata": {
  "aivi": {
   "chapters": [
    "recurrente-neurale-netwerken"
   ],
   "language": "en",
   "title": "Recurrent networks in Python"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
