Summary - RNN
- Machine Learning course
- Advanced
- Lesson 52/78
- 6 min
In this group you learned RNN, hidden state, and vanishing gradients.
Summary: RNN
In this group:
- An RNN processes a sequence step by step:
h_t = tanh(W_x x_t + W_h h_(t-1) + b); the weights are shared across steps. nn.RNN:output(N, T, H),h_n(layer, N, H);batch_first=True.- Different lengths:
pad_sequence, the real length,pack_padded_sequence. - In long sequences the gradient vanishes or explodes; clipping and gated architectures are the fixes.
nn.Embeddingturns word indices into learned vectors.
Practice A two-layer RNN
Apply an nn.RNN(16, 32, num_layers=2, batch_first=True) layer to a (4, 10, 16) input. Print the output and h_n shapes on one line, then the parameter count (the second layer's input is 32).
Starter code
import torch
from torch import nn
x = torch.zeros(4, 10, 16)
# buraya yazSample solution
import torch
from torch import nn
x = torch.zeros(4, 10, 16)
rnn = nn.RNN(16, 32, num_layers=2, batch_first=True)
output, h_n = rnn(x)
print(output.shape, h_n.shape)
print(sum(p.numel() for p in rnn.parameters()))Expected output
torch.Size([4, 10, 32]) torch.Size([2, 4, 32]) 3712
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the RNN's main weakness compared with the transformer?
- Steps are processed sequentially and can't be computed in parallel Correct answer
- It has no parameters
- It can't process text
- It can't use embeddings
Explanation: Because each step waits for the previous one, exploiting GPU parallelism is hard.
2 Build a two-layer RNN.
rnn = nn.RNN(16, 32, ____=2, batch_first=True)
rnn = nn.RNN(16, 32, num_layers=2, batch_first=True)
Explanation: num_layers stacks RNN layers.
3 Match the concepts.
| Term | Meaning |
|---|---|
hidden state |
Summary of the past |
padding |
Equal length |
vanishing gradient |
Long-range problem |
embedding |
Word vectors |