Lecture 8
Introduction to Machine Learning
KU Leuven, campuses Diepenbeek and Geel
Academic year 2026–2027
recurrent layers
the same cell at every step
squared error
cross-entropy when a sequence gets a class
Adam
through time
Exercise 4 forecasts the load of one client with a recurrent network, using all three blocks.
Block 1
\(\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\).
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.
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
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)
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.
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.
h_last.num_layers=2, the states of the first layer are the inputs of the second. The leading dimension of h_last counts the layers.Checkpoint
Block 2
The length of the sequence plays the role of the depth of lecture 5, with the same matrix in every factor.
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.
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.
\(\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.
recurrent layers, gated
the model changed
squared error
the forecast of lecture 1
Adam
backpropagation runs through time
Checkpoint
Break
Block 3
nn.GRU, and the targets a column.| test, July to December 2014 | MAE (MW) |
|---|---|
| persistence: the current hour | 16.7 |
| the same hour yesterday | 7.8 |
| the same hour last week | 12.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.
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])
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.
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.
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.
Checkpoint
recurrent layers
the same cell at every step
squared error
cross-entropy when a sequence gets a class
Adam
through time
All three books are free to read online.
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.
Unsupervised learning: structure without labels.