Worked Example: Forecasting with a GRU Without Peeking at the Future
Forecast seven days of a seeded daily demand series from the previous 28: split the windows by the dates of their targets, scale with training-period statistics only, score seasonal-naive and lag-feature ridge baselines and a GRU over three seeds on identical windows and horizon, read the errors by horizon, and decide which model to keep.
Contentsand lesson path
On this page
- The problem
- Step 1: Generate the series and fix the periods
- Step 2: Windows split by the dates of their targets
- Step 3: Two baselines
- Step 4: The GRU, over three seeds
- Step 5: Cost, and the decision
- Check your understanding
- Apply it
- Review prompt
Lessons of Sequence Models & RNNs
- From Text and Time Series to Tensors Concept · 20 min
- Recurrent Networks and Their Gates Concept · 20 min
- Lab: Sentiment Classification with Embeddings and an LSTM Lab · 30 min
- Worked Example: Forecasting with a GRU Without Peeking at the Future Worked example · 25 min
- Why Recurrence Hit a Wall: Long Dependencies and Attention Concept · 15 min
- Check: Sequences, Gates and Masks Knowledge check · 6 questions
What you will learn
- Prepare sequence data for training: tokenize text into ids with padding and masks, or window a time series with a leakage-free temporal split.
- Train an embedding plus LSTM or GRU model for sequence classification or forecasting in PyTorch and compare it with a non-sequential baseline such as bag-of-words or lag features.
Prerequisites: Deep Learning Fundamentals
01. The problem
A shop wants a forecast of daily demand for the next seven days, made each evening from the last four weeks of sales. Someone suggests a GRU, the gated recurrent layer from recurrent networks and their gates. Your job is to find out whether it is worth having, and to make sure that the answer is not flattered by information from the future.
The series is generated with a fixed seed so that you can see what is in it: 900 days with a slow upward trend, a weekly pattern with a weekend peak, a yearly cycle, and autocorrelated noise, noise in which today echoes yesterday (each day keeps 70% of the previous day's deviation). Two baselines set the bar. The seasonal-naive forecast repeats the value from exactly one week earlier. The lag-feature model is ridge regression, a linear model with a penalty on large weights, fed the last 28 values as 28 separate features. All three models see the same windows, predict the same seven days, and are scored by mean absolute error (MAE), the average size of the forecast error in units of demand.
You need Python 3.12, PyTorch 2 (CPU build), NumPy 2 and scikit-learn 1.9. The GRU trains on one CPU thread in well under a minute per seed. Results are seeded; the last digit can differ on other CPUs or library versions.
02. Step 1: Generate the series and fix the periods
The periods are decided before anything is fitted: days 0 to 599 for training, 600 to 749 for validation, and 750 to 899 for the test. Validation is used to choose settings and the best epoch; the test period is scored once, at the end.
import numpy as np
N_DAYS, WINDOW, HORIZON = 900, 28, 7
TRAIN_END, VAL_END = 600, 750 # day indices where val and test begin
def make_series(seed=0):
"""Daily demand: trend, weekly and yearly cycles, and noise that persists."""
rng = np.random.default_rng(seed)
t = np.arange(N_DAYS)
weekly = np.array([0, -4, -6, -3, 2, 14, 10])[t % 7] # weekend peaks
yearly = 15 * np.sin(2 * np.pi * t / 365.25)
noise = np.zeros(N_DAYS)
for i in range(1, N_DAYS): # AR(1): today echoes yesterday
noise[i] = 0.7 * noise[i - 1] + rng.normal(0, 4)
return 100 + 0.03 * t + weekly + yearly + noise
if __name__ == "__main__":
y = make_series()
for name, part in [("train", y[:TRAIN_END]), ("val", y[TRAIN_END:VAL_END]),
("test", y[VAL_END:])]:
print(f"{name:5s} days {len(part):3d} mean {part.mean():6.1f}"
f" min {part.min():6.1f} max {part.max():6.1f}")
by_day = [y[:TRAIN_END][d::7].mean() for d in range(7)]
print("train mean by day of the week:", np.round(by_day, 1))python series.pytrain days 600 mean 112.9 min 69.7 max 156.8
val days 150 mean 112.1 min 84.3 max 137.9
test days 150 mean 137.7 min 118.1 max 159.7
train mean by day of the week: [111.4 106.6 104.8 108.1 113. 125.5 121.2]The test period sits higher than the training period (mean 137.7 against 112.9), because the trend has kept rising and the yearly cycle peaks inside it. Its maximum, 159.7, is above anything in training. That is normal for forecasting: the future is not a random sample of the past, which is exactly why the split must follow time.
03. Step 2: Windows split by the dates of their targets
Each window has 28 input days and the following 7 target days, and is indexed by its first target day: the day after the forecast is made. A window belongs to a period only if all of its targets fall inside that period. Inputs may reach back into the previous period, because at forecast time the past is known. The scaler, a mean and a standard deviation used to standardise values, comes from days 0 to 599 only, and the assert fails loudly if a training target ever reaches the validation period.
import numpy as np
from series import HORIZON, TRAIN_END, VAL_END, WINDOW, make_series
def windows(y):
"""Inputs: 28 days. Targets: the next 7. Indexed by the first target day."""
first = np.arange(WINDOW, len(y) - HORIZON + 1)
X = np.stack([y[f - WINDOW:f] for f in first])
Y = np.stack([y[f:f + HORIZON] for f in first])
return X, Y, first
def splits(seed=0):
y = make_series(seed)
X, Y, first = windows(y)
last = first + HORIZON - 1 # last target day
parts = {"train": last < TRAIN_END, # every target in its period
"val": (first >= TRAIN_END) & (last < VAL_END),
"test": first >= VAL_END}
mean, std = y[:TRAIN_END].mean(), y[:TRAIN_END].std() # training period only
return {k: (X[m], Y[m], first[m]) for k, m in parts.items()}, (mean, std)
if __name__ == "__main__":
data, (mean, std) = splits()
for name, (X, Y, first) in data.items():
print(f"{name:5s} {len(X):3d} windows X {X.shape} Y {Y.shape}"
f" target days {first.min()}..{first.max() + HORIZON - 1}")
assert data["train"][2].max() + HORIZON - 1 < data["val"][2].min()
print(f"scaler from days 0..{TRAIN_END - 1}: mean {mean:.2f}, std {std:.2f}")python windows.pytrain 566 windows X (566, 28) Y (566, 7) target days 28..599
val 144 windows X (144, 28) Y (144, 7) target days 600..749
test 144 windows X (144, 28) Y (144, 7) target days 750..899
scaler from days 0..599: mean 112.93, std 14.65The 566 training windows predict days 28 to 599, and the six windows whose targets would straddle day 600 belong to no period at all, like six more at day 750. Validation and test get 144 windows each. With a longer horizon, or features that look ahead, you would also leave a gap between periods, as in from text and time series to tensors.
04. Step 3: Two baselines
Seasonal naive needs no training: the forecast for day t + h is the value of day t + h − 7, which for h from 1 to 7 is always one of the last seven inputs. Ridge is trained on the scaled training windows, with its penalty alpha chosen on validation. Both are scored per horizon as well, because a single average hides how quickly a forecast decays.
import numpy as np
from sklearn.linear_model import Ridge
from windows import splits
data, (mean, std) = splits()
(Xtr, Ytr, _), (Xva, Yva, _), (Xte, Yte, _) = data["train"], data["val"], data["test"]
def mae(pred, Y):
return np.abs(pred - Y).mean()
def seasonal_naive(X):
return X[:, -7:] # day t+h repeats day t+h-7, for h = 1..7
def ridge(alpha):
model = Ridge(alpha=alpha).fit((Xtr - mean) / std, (Ytr - mean) / std)
return lambda X: model.predict((X - mean) / std) * std + mean
if __name__ == "__main__":
print(f"seasonal naive val MAE {mae(seasonal_naive(Xva), Yva):.2f}"
f" test MAE {mae(seasonal_naive(Xte), Yte):.2f}")
val = {a: mae(ridge(a)(Xva), Yva) for a in (0.1, 1, 10, 100)}
best = min(val, key=val.get) # chosen on validation
print(f"ridge, alpha {best:<4} val MAE {val[best]:.2f}"
f" test MAE {mae(ridge(best)(Xte), Yte):.2f}")
for name, f in [("seasonal naive", seasonal_naive), ("ridge", ridge(best))]:
per_h = np.abs(f(Xte) - Yte).mean(axis=0)
print(f"{name:15s} test MAE by horizon:", np.round(per_h, 2))python baselines.pyseasonal naive val MAE 6.94 test MAE 5.62
ridge, alpha 1 val MAE 5.14 test MAE 4.72
seasonal naive test MAE by horizon: [5.54 5.62 5.67 5.7 5.64 5.63 5.51]
ridge test MAE by horizon: [3.08 4.05 4.63 5.11 5.32 5.42 5.45]Ridge beats seasonal naive on both periods, 4.72 against 5.62 on test. The horizon breakdown shows where: for tomorrow, ridge has an error of 3.08 because it can use the autocorrelated noise of the last few days; by day 7 that echo has faded (0.7 to the power 7 is about 0.08) and ridge is barely better than repeating last week. Seasonal naive stays at about 5.6 for every horizon, because it always copies a known value from one week back. Note also that both models score better on test than on validation. The periods differ in how noisy and how predictable they are, so errors are only comparable between models on the same period.
05. Step 4: The GRU, over three seeds
The GRU reads the 28 scaled values one day at a time (input shape (batch, 28, 1)), and a linear head turns its final hidden state into all seven forecasts at once. Predicting the whole horizon in one go, a direct multi-output forecast, avoids feeding the model's own errors back in as inputs. The loss is the L1 loss, the training form of MAE. Training uses Adam with gradient clipping and keeps the epoch with the lowest validation MAE. It runs three times, with seeds 0, 1 and 2, because a single neural network run can be several tenths better or worse than the next, and that is the same size as the differences you are trying to judge.
import copy
import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
from windows import splits
torch.set_num_threads(1)
data, (mean, std) = splits()
def tensors(name): # scale with the training-period statistics
X, Y, _ = data[name]
return (torch.tensor((X - mean) / std, dtype=torch.float32).unsqueeze(-1),
torch.tensor((Y - mean) / std, dtype=torch.float32))
class GRUForecaster(nn.Module):
def __init__(self, hidden=32, horizon=7):
super().__init__()
self.gru = nn.GRU(1, hidden, batch_first=True)
self.head = nn.Linear(hidden, horizon) # all 7 days at once
def forward(self, x): # x: (batch, 28, 1)
_, h_n = self.gru(x) # h_n: (1, batch, hidden)
return self.head(h_n[-1]) # (batch, 7)
def mae(model, X, Y): # in original units
with torch.no_grad():
return ((model(X) - Y).abs().mean() * std).item()
def train(seed, epochs=60):
torch.manual_seed(seed)
(Xtr, Ytr), (Xva, Yva) = tensors("train"), tensors("val")
loader = DataLoader(TensorDataset(Xtr, Ytr), batch_size=64, shuffle=True,
generator=torch.Generator().manual_seed(seed))
model = GRUForecaster()
opt = torch.optim.Adam(model.parameters(), lr=3e-3)
best = (float("inf"), 0, None)
for epoch in range(1, epochs + 1):
model.train()
for xb, yb in loader:
loss = nn.functional.l1_loss(model(xb), yb)
opt.zero_grad()
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
model.eval()
val = mae(model, Xva, Yva)
if val < best[0]: # best epoch on validation
best = (val, epoch, copy.deepcopy(model.state_dict()))
model.load_state_dict(best[2])
return model, best[0], best[1]
if __name__ == "__main__":
Xte, Yte = tensors("test")
results = []
for seed in (0, 1, 2):
model, val, epoch = train(seed)
test = mae(model, Xte, Yte)
with torch.no_grad():
per_h = ((model(Xte) - Yte).abs().mean(0) * std).numpy()
results.append(test)
print(f"seed {seed}: best epoch {epoch:2d} val MAE {val:.2f}"
f" test MAE {test:.2f}")
print(" test MAE by horizon:", np.round(per_h, 2))
print(f"GRU test MAE over 3 seeds: mean {np.mean(results):.2f},"
f" min {min(results):.2f}, max {max(results):.2f}")
print("GRU parameters:", sum(p.numel() for p in model.parameters()))python gru.pyseed 0: best epoch 49 val MAE 5.25 test MAE 5.60
test MAE by horizon: [4.07 5.2 6.1 6. 6.44 6.03 5.35]
seed 1: best epoch 60 val MAE 5.21 test MAE 5.13
test MAE by horizon: [3.4 4.1 5.27 5.44 5.61 6.27 5.82]
seed 2: best epoch 55 val MAE 5.23 test MAE 5.16
test MAE by horizon: [3.51 4.43 5.24 5.73 6.06 5.81 5.38]
GRU test MAE over 3 seeds: mean 5.30, min 5.13, max 5.60
GRU parameters: 3591On validation, the GRU reaches 5.21 to 5.25, close to ridge's 5.14. On test its MAE averages 5.30 and ranges from 5.13 to 5.60 depending on the seed alone. It beats seasonal naive, 5.62, but every seed loses to ridge, 4.72. Before blaming the model, check the training budget: rerun gru.py with more epochs or another learning rate and see whether the validation error moves.
06. Step 5: Cost, and the decision
The last script times one fit of each model. Times depend on the machine and its load, so the output is illustrative.
import time
from baselines import ridge
from gru import train
t0 = time.perf_counter()
ridge(1) # fit ridge on the training windows
t1 = time.perf_counter()
model, _, _ = train(0) # one GRU run: 60 epochs
t2 = time.perf_counter()
print(f"ridge fit {t1 - t0:.3f} s GRU training {t2 - t1:.1f} s")python cost.pyridge fit 0.023 s GRU training 11.9 sRidge fits in hundredths of a second; one GRU run takes seconds, hundreds of times longer, and needs three runs to judge. Here the decision is easy: keep ridge. That is not a verdict on GRUs. This series is a sum of linear patterns, and a linear model on lags suits it well. Recurrent models tend to earn their cost when there are many related series to learn from together, long and irregular patterns, or extra inputs such as prices and holidays whose effects interact. What carries over is the procedure: identical windows and horizon for every model, statistics from the training period only, a seasonal-naive floor and a tuned lag baseline, several seeds, and errors read per horizon.
07. Check your understanding
08. Apply it
For the practice project, use this example as a template for your own series or for a variant of this one.
- Make the series non-linear, for example by letting the weekend peak grow with the yearly cycle, and rerun all three models. Does the GRU now beat ridge by more than its spread across seeds?
- Add a day-of-week input to both ridge and the GRU, so that the two still see the same information.
- Write the decision as a short note: test MAE of each model with its range over seeds, the error by horizon, the training cost, and which model you would run every evening.
09. Review prompt
Without looking back, explain how a window is assigned to a period and why its target dates decide it; say which statistics must come from the training period only; describe the seasonal-naive and lag-feature baselines and what each one captures; explain what a direct multi-output forecast is; and list what you need before saying that a recurrent forecaster beats a baseline.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.