Lecture 8

Recurrent neural networks

Introduction to Machine Learning
KU Leuven, campuses Diepenbeek and Geel
Academic year 2026–2027

Where lecture 7 stopped

Two panels. Left, lecture 7: a five by five grid with a three by three filter drawn at two positions, one filter at every position. Right, today: four identical cells reading x 1 to x 4 one step at a time, each passing a state to the next, one cell at every step.
Lecture 7 built structure for space: the same filter at every position of an image. A sequence has its order in time, and today's layer applies the same cell at every step, passing on a memory.

Sequences

Three sequences stacked. Top, three days of electricity load, one value per hour, rising each morning and falling each night. Middle, 40 milliseconds of the vibration of a faulty bearing, 12,000 values per second, with three sharp impulses. Bottom, a sentence of twelve words, one word per step.
A sequence is a list of steps whose order carries information: hours of load, samples of a vibration, words of a sentence. Today's data is the load.

Today in three choices

Model

recurrent layers

the same cell at every step

Loss

squared error

cross-entropy when a sequence gets a class

Optimiser

Adam

through time

The plan

  1. Recurrence
  2. Training through time
  3. Sequence tasks and forecasting

Exercise 4 forecasts the load of one client with a recurrent network, using all three blocks.

Block 1

Recurrence

Electricity load

The hourly load of the total over the clients for two weeks, Monday 4 to Sunday 17 February 2013. Every day the load falls to between 90 and 98 MW at night, stays near 200 MW through the day, and peaks at about 225 MW at 19:00.
Two weeks of February 2013 of the hourly load of 312 clients, recorded in Portuguese local time, 2012 to 2014: 203 MW on average, low at night and high by day, and each day much like the one before.

The patterns in the load

Three panels over the training years 2012 and 2013. Left, the mean load by hour of the day: about 104 MW at 4:00 and 280 MW at 18:00, with the weekend curve almost on top of the weekday curve. Middle, the mean load by day of the week: between 201 and 208 MW on every day. Right, the monthly mean from 2012 to 2014: high in summer, up to 267 MW in August 2012, and near 170 MW in winter and spring.
A strong daily cycle, from 104 MW at 4:00 to 280 MW at 18:00, and a yearly one, highest in summer. The day of the week hardly matters: every day of the week averages between 201 and 208 MW.

How much the past says

The autocorrelation of the hourly load against the lag from 0 to 200 hours. It swings between about minus 0.53 at 12 hours and its odd multiples and about 0.97 at every multiple of 24 hours. It is 0.99 at a day and 0.96 at a week.
The load correlates at 0.99 with the load a day earlier and at −0.53 with the load half a day earlier. The hours that matter most lie 24 hours apart.

A window into an MLP

A window of 12 hours, drawn for 48. The same pattern of three hours appears late in one window, at hours 9 to 11, and earlier in another, at hours 4 to 6. Each hour meets its own weight of the dense layer, w 1 to w 12, so the two copies of the pattern meet different weights.
An MLP on the last 48 hours has a weight per hour and per unit, and a fixed length. A pattern learned late in the window is unknown early in it: a dense layer shares nothing across time.

The hidden state

A recurrent cell. The input x t enters a tanh box through the weights W x, with the bias b. The output h t leaves at the top, and a loop feeds it back into the box one step later through the weights W h, as h t minus 1.
\[ \vh_t = \tanh\big(\vx_t \mW_x + \vh_{t-1} \mW_h + \vb\big) \]

\(\vh_t\) summarises everything read so far, in \(H\) numbers.

One example per row, as the layers of lecture 5: \(\vx_t\) is \(1 \times C\), \(\vh_t\) is \(1 \times H\), and \(\vh_0 = \mathbf 0\).

The cell is a dense layer

The recurrent cell as one dense layer. The input x t, of 1 by C, and the previous state h t minus 1, of 1 by H, are joined into one row of 1 by C plus H. A dense layer with tanh and weights of C plus H by H turns it into h t, of 1 by H, which returns as h t minus 1 at the next step.
Join the input and the previous state into one row, and the cell is the dense layer of lecture 5 with tanh. \(\mW_x\) and \(\mW_h\) are the two blocks of its weight matrix.

Unrolling: step 1

Step 1 of the unrolled cell: from h 0 equal to 0 and x 1 the first cell computes h 1. The cells of the later steps are drawn as empty outlines.
The first step reads \(\vx_1\) and the zero state.

Unrolling: step 2

Step 2 of the unrolled cell: the second cell reads x 2 and h 1 and computes h 2 with the same weights as step 1. Steps 3 to 48 are empty outlines.
The second step reads \(\vx_2\) and \(\vh_1\), with the same weights.

Unrolling

The cell unrolled over 48 steps. Starting from h 0 equal to 0, the cells read x 1, x 2, x 3 and so on to x 48, each passing its hidden state to the next. The prediction y hat equals h 48 times w plus c is read from the last state. The same weights W x, W h and b are used at every step.
Unrolled over a window, a recurrent layer is a network of 48 layers that share one set of weights.

One step by hand

A recurrent cell with one unit, worked by hand, with w x equal to 1, w h equal to 0.5, b equal to 0 and h 0 equal to 0, on the inputs 1, 0, 0. Step 1: z equals 1, h 1 equals tanh of 1, 0.76. Step 2: z equals 0.5 times 0.76, 0.38, and h 2 equals 0.36. Step 3: z equals 0.18 and h 3 equals 0.18.
One unit, one input of 1 followed by zeros. The state keeps a trace of the input, which halves at every step, since \(w_h = 0.5\).

Your turn

Exercise: the same cell with w h equal to 2, w x equal to 1, b equal to 0 and h 0 equal to 0, on the inputs 1, 0, 0. The states h 1, h 2 and h 3 are drawn with a question mark.
The same cell with \(w_h = 2\). Compute \(h_1\), \(h_2\) and \(h_3\).

Answer: the state settles near 1

Answer: with w h equal to 2, step 1 gives z equal to 1 and h 1 equal to 0.76, step 2 gives z equal to 1.52 and h 2 equal to 0.91, step 3 gives z equal to 1.82 and h 3 equal to 0.95.
With \(w_h = 2\) the input is kept, and the state climbs to where tanh is flat: a later input would hardly move it.

Weight sharing

The unrolled cell with its weights marked. Every input arrow, from x 1 to x 48, carries the same W x, and every state arrow carries the same W h. One set of weights, W x, W h and b, serves all 48 steps.
The weights that read hour 1 also read hour 48, so a pattern is recognised at any time, as a filter recognises it at any position.

The parameter count

\[ \underbrace{C H}_{\mW_x} + \underbrace{H^2}_{\mW_h} + \underbrace{H}_{\vb} \text{ parameters} \]

whatever the length of the sequence.

The RNN forecaster of block 3 holds 1,153 parameters, with its output layer and PyTorch's second bias, for a window of 48 hours or of a year.

Parameters against the window

The number of parameters against the window length, 24, 48, 96, 168 and 336 hours. An MLP with 32 hidden units grows from 833 to 10,817 parameters. The RNN of 32 units stays at 1,153 and the GRU at 3,393 at every length.
An MLP with 32 units grows with the window, from 1,601 parameters at 48 hours to 10,817 at two weeks. The recurrent layers do not grow at all.

The recurrence in numpy

Pseudocode

h ← 0, a vector of H zeros
for t = 1 … L:
  z ← xₜ Wₓ + h Wₕ + b
  h ← tanh(z)
  store h as hₜ
return h₁ … h_L, L × H

numpy

def rnn_forward(X, Wx, Wh, b):
    h = np.zeros(Wh.shape[0])
    H = []
    for x in X:
        z = x @ Wx + h @ Wh + b
        h = np.tanh(z)
        H.append(h)
    return np.array(H)

A prediction from the last state

\[ \yhat = \vh_L \vw + c \]
\[ \loss = \frac{1}{n} \sum_{i=1}^{n} \big(y_i - \yhat_i\big)^2 \]

The output layer is the linear regression of lecture 1, on features that the recurrence computed.

For the class of a sequence: a softmax and cross-entropy instead, as in lecture 3.

nn.RNN

rnn = nn.RNN(input_size=1,
             hidden_size=16,
             batch_first=True)
X = torch.zeros(64, 48, 1)
H, h_last = rnn(X)
H.shape       # 64 × 48 × 16
h_last.shape  # 1 × 64 × 16

Sequences enter as N × L × C: batch, length, channels.

The layer returns every hidden state, and the last one again on its own.

The shapes

Shapes of nn.RNN with batch_first=True. The input X is a stack of 64 sequences of 48 steps with one channel, 64 by 48 by 1. The output H holds a state of 16 numbers at every step of every sequence, 64 by 48 by 16. Its last column is returned again as h_last, of 1 by 64 by 16.
The input stacks 64 windows of 48 hours. The output holds 16 numbers per hour and window; the last hour, in red, comes back as h_last.

Stacked layers

Two stacked recurrent layers. Layer 1 reads x 1 to x 48 and passes its states along its row and up to layer 2, whose states feed the prediction y hat from the last step. With num_layers=2, h_last holds one last state per layer.
With num_layers=2, the states of the first layer are the inputs of the second. The leading dimension of h_last counts the layers.

A hidden state over two days

Top, the load of 7 and 8 July 2014, low at night and near 300 to 350 MW by day. Bottom, three hidden units of the trained RNN over the same 48 hours. After the first few hours all three sit near minus 1 while the load is high and near plus 1 while it is low.
Three hidden units of the RNN of block 3, reading two days of load. After a few hours they sit near −1 while the load is high and near +1 while it is low.

Every unit over a week

Top, the load from Monday 7 to Sunday 13 July 2014, seven daily peaks between 300 and 380 MW. Bottom, a heat map of all 32 hidden units of the trained RNN over the same week, sorted by their correlation with the load, in red for plus 1 and blue for minus 1. Most rows switch colour once a day in step with the load; the weekend looks like the weekdays.
All 32 units of the RNN over a week. Most of them repeat a daily rhythm, each at its own phase; none marks the weekend, which the load does not mark either.

Checkpoint

An RNN with 16 hidden units reads 48 hours of load, one number per hour. How many parameters does its recurrent layer hold, and how many for a window of a week?

Answer: 288 for any length

W x is a row of 1 by 16 weights, 16 in all; W h is a grid of 16 by 16, 256 weights; b is a row of 16. Together 288 parameters, for a window of 48 hours and for a week. nn.RNN reports 304, since it keeps two bias vectors.
\(1 \cdot 16 + 16^2 + 16 = 288\), for 48 hours and for a week. nn.RNN reports 304, since PyTorch keeps two bias vectors.

Block 2

Training through time

Backpropagation through time

The unrolled network from h 0 through step 1, step 2 and so on to step 48, then the prediction y hat and the loss. A red backward path runs from the loss back through the prediction, step 48 and so on to step 2 and step 1, one step at a time. Below: the gradients of W x, W h and b are summed over the steps.
Backpropagation on the unrolled network: the gradient flows back from the loss through every step, and the gradients of the shared weights are summed over the steps.

The gradient of Wh is a sum

Bars of the norm of the part of the gradient of W h that each step contributes, for the trained RNN on 512 test windows, against the steps back from 0 to 47, relative to the largest. The last step gives 1, one step back 0.90, five steps back 0.26 and ten steps back 0.22. There is a small bump of about 0.04 at 23 and 24 steps back, and from 25 steps back every bar is below 0.03.
The trained RNN on 512 test windows: the part of the gradient of \(\mW_h\) from each step. The last steps dominate. A day back, 23 and 24 steps, a small bump adds about 4%; from 25 steps back, each step adds less than 3% of the largest part.

One factor per step

The factor after k steps against k from 0 to 50, on a log scale, for 1.2, 1.0 and 0.8 per step. 1.2 to the k grows to about 9,100 at 50 steps, 1.0 stays at 1, and 0.8 to the k falls to about 1.4 times 10 to the minus 5.
A factor of 0.8 per step leaves \(10^{-5}\) after 50 steps; 1.2 per step gives 9,100. Only exactly 1 stays put.

A product over steps

\[ \frac{\partial \vh_t}{\partial \vh_{t-1}} = \operatorname{diag}\big(1 - \vh_t^2\big) \, \mW_h\T \]
\[ \frac{\partial \vh_L}{\partial \vh_t} = \prod_{s=t+1}^{L} \operatorname{diag}\big(1 - \vh_s^2\big) \, \mW_h\T \]
\[ L - t \text{ factors: below 1 the gradient vanishes, above 1 it explodes} \]

The length of the sequence plays the role of the depth of lecture 5, with the same matrix in every factor.

The tanh in every factor

tanh of z and its derivative 1 minus tanh squared, for z from minus 4 to 4. tanh rises from minus 1 to 1; the derivative is 1 at z equal to 0 and falls to 0.07 at plus or minus 2 and lower beyond, where the regions are shaded and marked saturated.
The derivative of tanh is 1 at zero, 0.07 at ±2, and smaller still where the unit saturates beyond. A saturated unit blocks the gradient whatever \(\mW_h\) is.

Vanishing and exploding

The gradient norm of the last hidden state with respect to each input, relative to the last step, against the steps back from 0 to 59, on a log scale. For an RNN whose recurrent weights are scaled by 0.8 it falls to about 6 times 10 to the minus 3 at 20 steps, 10 to the minus 4 at 40 and 5 times 10 to the minus 7 at 59. For the scale 1.2 it stays between about 0.5 and 2 for 40 steps, then grows to 23 at 59 steps.
A plain RNN with its recurrent weights scaled by 0.8 keeps 10⁻⁴ of the gradient at 40 steps back. Scaled by 1.2, the gradient grows to 23 times its size at 59 steps.

An explosion in training

The training loss on the scaled load against the step, 1 to 300, on a log scale, for the RNN forecaster with its recurrent weights scaled by 2, trained by SGD with a learning rate of 0.1. Without clipping, the loss passes 10 to the 30 by step 28 and becomes NaN at step 32, where the curve ends. Clipped at 1.0, the loss stays near 1 and falls to about 0.1 by step 300.
The RNN forecaster with \(\mW_h\) scaled by 2, trained by SGD at a rate of 0.1. Without clipping the loss passes 10³⁰ and is NaN at step 32. With the gradient norm clipped at 1.0, it trains.

Clipping

loss.backward()
nn.utils.clip_grad_norm_(
    model.parameters(), 1.0)
opt.step()

Exploding gradients: cap the norm of all gradients together before the step.

It fixes only explosions: a vanishing gradient has nothing to rescale.

Clipping keeps the direction

Clipping a gradient by its norm, in two dimensions. The gradient g has norm 3 and points up and to the right. A dashed circle marks the threshold, norm 1.0. The clipped gradient g divided by 3 points in the same direction and ends on the circle.
A gradient of norm 3 is divided by 3: same direction, norm 1. A gradient inside the circle is left alone.

Windows cut the depth

Two ways to cut a long series. Top, our windows: two windows of six hours, shifted by one hour, each start from h 0 equal to 0, and the backward pass, in red, stays inside each window. Bottom, truncated backpropagation through time: the series is cut into chunks, the state is carried across the border by the forward arrow, and the backward pass stops at the border.
With windows of 48 hours, the gradient crosses at most 48 steps. The price: nothing further back can be learned, and the same hour last week lies 168 steps back.

Does a longer window help?

The test MAE of the GRU for windows of 24, 48, 96 and 168 hours, three seeds each, with the mean as a bar. At 24 hours 4.8 to 5.6 MW, at 48 hours 5.5 to 5.7, at 96 hours 5.2 to 5.5, at 168 hours 5.0 to 5.6. The spread over seeds is as large as the differences between lengths.
The GRU with windows of a day to a week, three seeds each. The seeds differ as much as the lengths do: on this load, a longer window buys nothing measurable.

Gates

\[ \vz_t = \sigma\big(\vx_t \mW_{xz} + \vh_{t-1} \mW_{hz} + \vb_z\big) \]

A gate is a sigmoid between 0 and 1, computed from the input and the state.

It multiplies a vector elementwise: 1 lets it pass, 0 blocks it.

The network learns when to open and when to close its gates, through the same loss.

A gate with numbers

A gate applied to a state of four numbers, 2.0, minus 1.0, 0.5 and 3.0. The gate values are 0.98, 0.02, 0.50 and 0.90, shaded by size. Their elementwise product passes on 1.96, minus 0.02, 0.25 and 2.70.
Each number of the state has its own gate value. The first passes almost whole, the second is blocked, the third is halved.

The GRU

A GRU cell. The previous state h t minus 1 runs along the top, multiplied by the update gate z, and added to the candidate h tilde t multiplied by 1 minus z, which gives h t. The update gate, the reset gate r and the tanh candidate read h t minus 1 and x t; the reset gate feeds the candidate.
The gated recurrent unit: an update gate \(\vz_t\) mixes the old state and a candidate, and a reset gate \(\mathbf r_t\) decides how much of the old state the candidate reads.

The GRU in equations

\[ \tilde{\vh}_t = \tanh\big(\vx_t \mW_{xh} + (\mathbf r_t \odot \vh_{t-1}) \mW_{hh} + \vb_h\big) \]
\[ \vh_t = \vz_t \odot \vh_{t-1} + (1 - \vz_t) \odot \tilde{\vh}_t \]

\(\mathbf r_t\) is a gate of the same form as \(\vz_t\), with its own weights. With \(\vz_t\) near 1 the state passes unchanged, and so does its gradient.

The GRU at its extremes

The GRU at its two extremes. Left, z equal to 1: the previous state passes straight to h t, and the candidate is ignored, so the state and its gradient pass unchanged. Right, z equal to 0 and r equal to 1: the new state is the tanh of x t and h t minus 1, the update of the plain RNN.
With \(\vz_t = 1\) the cell copies its state. With \(\vz_t = 0\) and \(\mathbf r_t = 1\) it is the plain RNN of block 1. Between the two, the gates choose per unit and per step.

Gates carry the gradient

The gradient figure of the slide Vanishing and exploding with a third curve, a GRU whose update gate starts near 1. Its gradient falls slowly and smoothly, to about 0.08 at 40 steps back and 0.03 at 59 steps, far above the RNN scaled by 0.8.
A GRU whose update gate starts near 1 keeps 3% of the gradient at 59 steps back, where the RNN scaled by 0.8 keeps 5 · 10⁻⁷.

Unless the gates start half open

The gradient norm against the steps back, on a log scale, for the RNN scaled by 0.8, the GRU whose update gate starts near 1, and a GRU at PyTorch's default initialisation. The default GRU falls fastest: about 4 times 10 to the minus 5 at 20 steps back, 2 times 10 to the minus 8 at 40 and about 10 to the minus 11 at 59.
At PyTorch's default start, \(\vz_t\) is near 0.5 and the untrained GRU keeps only 2 · 10⁻⁸ of the gradient at 40 steps back, less than the RNN scaled by 0.8. Gates help once training has opened them.

What the trained gates do

Top, the load of 7 and 8 July 2014. Bottom, the update gate z of three units of the trained GRU over the same 48 hours. The gates rise in the evening, stay near 1 through the night, drop towards 0 when the load rises in the morning, and stay low through much of the day.
The update gate of three units of the trained GRU. They rise in the evening and stay near 1, keeping the state, through the night; they fall near 0, overwriting it, when the morning rise begins.

What the trained models read

The mean absolute derivative of the forecast with respect to each hour of the window, relative to the last hour, on a log scale, for the trained RNN and GRU over 2,000 test windows. Both fall to about 0.2 to 0.3 one hour back and to about 0.05 three hours back, then to about 0.01 at 24 hours back and 0.001 at 47.
How much each hour of the window moves the forecast. Both models lean on the last two or three hours; the hour 24 hours back weighs about 1% of the last hour.

The LSTM

An LSTM cell. A cell state runs along the top from c t minus 1 to c t, multiplied by the forget gate f and added to the candidate g multiplied by the input gate i. The output gate o multiplies the tanh of the cell state, which gives h t. The gates and the candidate read h t minus 1 and x t.
The long short-term memory keeps a cell state, passed on by a product with the forget gate and a sum. The output gate decides how much of it shows in \(\vh_t\).

Like a residual connection

Two panels. Left, the residual block of lecture 7: x passes through F and is added to itself along a red skip path, which gives h. Right, the GRU: h t minus 1 is multiplied by z and added to the candidate times 1 minus z along a red path, which gives h t. In both, the red path passes no squashing nonlinearity.
Lecture 7 through depth, \(\vh = \vx + F(\vx)\); today through time, a kept state plus a candidate. Both give the gradient a path with no squashing nonlinearity, and gating learns how much of it to open.

The frame holds

Model

recurrent layers, gated

the model changed

Loss

squared error

the forecast of lecture 1

Optimiser

Adam

backpropagation runs through time

Checkpoint

A gradient crosses 50 steps, and each step scales it by 0.9. What fraction is left, and what if each step scales it by 1.1?

Answer: 0.005 and 117

The fraction of the gradient left after k steps, from 0 to 50, on a log scale, for 0.9 and 1.1 per step. 0.9 to the 50 is about 0.005 and 1.1 to the 50 about 117.
0.9⁵⁰ ≈ 0.005 and 1.1⁵⁰ ≈ 117: a factor of 10% per step either way becomes a factor of a hundred over 50 steps.

Break

Ten minutes

Block 3

Sequence tasks and forecasting

Shapes of sequence tasks

Three shapes of tasks, inputs below the cells and outputs above. Many to one: three inputs, one output at the last cell, for the fault of a bearing or the next hour from 48 hours. Many to many: an output at every cell, for a label per hour. Sequence to sequence: three cells read the inputs, then two further cells write two outputs, for a translation.
A recurrent layer returns a state at every step. Which states are read, and when the input ends, give the shape of the task.

Windows

A row of hourly squares. In example 1, a window of hours in blue is the input and the next hour in red is the target. In example 2 the same window is moved one hour to the right. A window holds 48 hours.
Every hour becomes the target of one example, with the 48 hours before it as input: 17,496 training examples from 2012 and 2013.

Windows as a tensor

Windows cut from a series of hours, drawn with windows of six hours for 48. Row 1 holds hours 1 to 6 with target hour 7, row 2 hours 2 to 7 with target 8, row 3 hours 3 to 8 with target 9, and so on. Stacked, the windows form X of 17,496 by 48 by 1 and the targets t of 17,496 by 1.
Each row is the series shifted by one hour. Stacked, the windows are the N × L × C input of nn.GRU, and the targets a column.

A chronological split

The daily mean load from 2012 to 2014, between about 100 and 300 MW, higher in summer. 2012 and 2013 are coloured as training, January to June 2014 as validation, and July to December 2014 as test.
Train on 2012 and 2013, choose on the first half of 2014, test once on the second half. The mean and the spread used for scaling come from the training span alone.

Baselines first

test, July to December 2014MAE (MW)
persistence: the current hour16.7
the same hour yesterday7.8
the same hour last week12.5

A baseline costs one line of code and sets the bar a model must clear.

Persistence does worst here: the load changes fast from one hour to the next, while each day repeats the day before.

The baselines over one day

Three panels for Saturday 1 November 2014, each with the load as a solid line and one baseline as a dashed line. Persistence, the hour before, lags the load by an hour and misses by 16.5 MW on average. The same hour yesterday follows the load closely, 7.3 MW. The same hour last week has the shape with larger misses, 12.5 MW.
Saturday 1 November 2014. Persistence is always an hour late, last week drifts from the level, and yesterday follows the load most closely.

A GRU forecaster

The model

class Forecaster(nn.Module):
    def __init__(self, cell):
        super().__init__()
        self.cell = cell
        self.out = nn.Linear(
            cell.hidden_size, 1)

    def forward(self, x):
        H, _ = self.cell(x)
        return self.out(H[:, -1])

A GRU of 32 units

gru = nn.GRU(input_size=1,
             hidden_size=32,
             batch_first=True)
model = Forecaster(gru)

3,393 parameters. The same class takes an nn.RNN or an nn.LSTM.

Training it

loss_fn = nn.MSELoss()
opt = torch.optim.Adam(
    model.parameters(), lr=1e-3)
history = train(model, loader,
    loss_fn, opt, epochs=10,
    val_loader=val_loader)

The loop of lecture 6, with the squared error.

With nn.MSELoss, train records the losses and no accuracy.

The learning curves

The mean squared error of the scaled load against the epoch, 1 to 10, on a log scale. The training loss falls from 0.20 to 0.008. The validation loss falls from 0.037 and stays between 0.006 and 0.008 from epoch 4.
The training loss falls from 0.20 to 0.008 over 10 epochs; the validation loss levels off between 0.006 and 0.008 from epoch 4.

A week of forecasts

The load from Monday 7 to Sunday 13 July 2014, hourly, between about 100 and 380 MW, with the GRU forecast one hour ahead and the same hour of the day before. The GRU lies within 21 MW of the load throughout. The same hour yesterday misses by up to 57 MW on the Tuesday, whose peak is higher than Monday's, and by 20 to 33 MW on the other days.
One hour ahead, the GRU follows the load closely, while the same hour yesterday misses the days that differ from the day before.

Where in the day the errors fall

Bars of the test MAE by hour of the day of the target, for the same hour yesterday and the GRU. Yesterday errs by 3 to 5 MW at night and 9 to 12 MW through the day. The GRU errs by 2 to 7 MW in most hours, but by 8 to 15 MW from 8:00 to 10:00. It does worse than yesterday at 5:00, 6:00, 8:00, 9:00 and 10:00, and better in every other hour.
From 11:00 to 4:00 the GRU beats yesterday in every hour. In the morning rise yesterday does better, at 5:00, 6:00 and from 8:00 to 10:00; at 8:00 the GRU misses by 15.0 MW against 4.2.

The error over the test half-year

The daily MAE from July to December 2014 for the same hour yesterday and the GRU. Yesterday varies between about 2 and 22 MW and jumps to 66 and 75 MW on 25 and 26 December. The GRU stays between about 3 and 9 MW, with 11 to 12 MW at Christmas.
Yesterday fails on the days that differ from the day before, most of all at Christmas: 66 and 75 MW. The GRU, which sees how the day started, misses by 11 to 12 MW.

The scores

Horizontal bars of the test MAE in MW, July to December 2014. Persistence 16.7, the same hour yesterday 7.8, the same hour last week 12.5. Models trained three times, with the seeds as dots: a 1-D CNN 4.9 to 5.8, the RNN 5.8 to 6.2, the GRU 5.5 to 5.7, and an MLP on the window 4.0 to 4.7.
The GRU cuts the error of the best baseline by more than a quarter and beats the plain RNN on every seed, by 0.1 to 0.7 MW. An MLP on the same window, with 1,601 parameters, does better still: 4.0 to 4.7 MW.

Beyond the next hour

Two ways to forecast 24 hours. Top, recursive: the GRU forecasts y hat 1 from 48 hours, and each forecast is fed back as the newest input of the next step, up to y hat 24. Bottom, direct: one GRU reads 48 hours and gives 24 outputs at once.
Forecasting the next 24 hours: feed each forecast back as the next input, so that errors accumulate, or give the model 24 outputs and predict all hours at once.

Fed its own forecasts

The test MAE against the hours ahead, 1 to 24, for the same hour yesterday and the GRU fed its own forecasts. Yesterday stays at 7.7 MW at every horizon. The GRU starts at 5.5 MW one hour ahead and 7.6 two hours ahead, passes yesterday at three hours with 8.7, and climbs to 13.4 MW at 24 hours.
The GRU trained for one hour, used recursively: it beats yesterday 1 and 2 hours ahead, 5.5 and 7.6 MW against 7.7, and loses from 3 hours on, up to 13.4. Yesterday needs no model and does not degrade.

Attention

Six positions x 1 to x 6 connected to one output by lines whose width is the attention weight, made up for the drawing: 0.04, 0.06, 0.10, 0.45, 0.25 and 0.10. The weights are computed from the positions themselves and sum to 1.
An output reads all positions at once, as a weighted sum. The weights are computed from the positions themselves and sum to 1; those drawn here are made up.

Attention by hand

Attention worked by hand on four positions. The scores are 0.0, 2.0, 1.0 and 0.5. The softmax turns them into the weights 0.08, 0.58, 0.21 and 0.13, which sum to 1. With the values 10, 30, 20 and 40, the output is the weighted sum 27.6.
Scores, a softmax, a weighted sum. The position with the highest score, 2.0, gets 58% of the weight, and the output 27.6 lies nearest its value, 30.

One step from every position

Two panels. Top, recurrence: x 1 reaches the output through 48 steps, run one after another. Bottom, attention: x 1 to x 48 each connect to the output directly, every path is one step long, and all positions are computed at once.
Through a recurrence, hour 1 reaches the output after 48 steps, computed in order. Through attention, every hour is one step away, and all are computed at once.

Transformers

  • no recurrence: layers of attention and small MLPs,
  • every position in parallel, so training uses the whole GPU,
  • the model behind the next-word prediction of lecture 1.

For short sensor windows, a GRU, a 1-D CNN or an MLP on the window remains a strong and cheap choice.

Understanding Deep Learning treats transformers in chapter 12.

From Elman to the transformer

A timeline of five steps. 1990, Elman: the simple recurrent network, with a state fed back. 1997, the LSTM of Hochreiter and Schmidhuber, with a gated cell state; the forget gate was added in 2000 by Gers and colleagues. 2014, the GRU of Cho and colleagues, with two gates and no cell state. 2014, attention, by Bahdanau and colleagues, where the decoder looks back at the input. 2017, the transformer of Vaswani and colleagues: attention without recurrence.
Recurrent cells grew gates to carry their gradient; attention then removed the need to carry anything step by step.

Checkpoint

Why is a time series split by date and not at random, and what would a random split do to the test error?

Answer: it rewards memorising

Bars of the test MAE under the split by date and a random split of the windows of the same sizes. The same hour yesterday: 7.8 by date, 7.1 random. A nearest-neighbour regressor, which copies the target of the closest training window: 7.3 by date, 5.8 random. The GRU over three seeds: 5.5 to 5.7 by date, 5.4 to 5.9 random.
Split at random, a nearest neighbour, which copies the closest training window, drops from 7.3 to 5.8 MW. The GRU scores alike under both splits; the leak rewards models that can memorise.

Takeaways

  1. A recurrent layer applies the same cell at every step and carries a hidden state.
  2. Backpropagation through time multiplies one factor per step, so gradients vanish or explode.
  3. Gates give the gradient an additive path through time.
  4. A forecast is judged against a baseline, on a chronological split.
  5. Attention replaced recurrence in the models that followed.

Which one when

Four rows matching data to a first model. A fixed window with enough examples: an MLP on the window. Local patterns at any position: a 1-D CNN. Any length, with a state to carry: a GRU or an LSTM. Long sequences with much data and computing: a transformer. Then compare with a baseline, on a split by date.
A first model for a sequence, by what the data look like. On today's load, the MLP on the window was the best of the four models we trained: MLP, 1-D CNN, RNN and GRU.

Lecture 8 in three choices

Model

recurrent layers

the same cell at every step

Loss

squared error

cross-entropy when a sequence gets a class

Optimiser

Adam

through time

Further reading

All three books are free to read online.

Next

Exercise 4

This week: a convolution in numpy, a CNN on Fashion-MNIST with train, then a GRU forecast of one client's load against persistence.

It uses lectures 7 and 8.

Lecture 9

Unsupervised learning: structure without labels.