Recurrent Neural Networks

Related: 14. Natural Language Processing | 4. Deep Learning and FCNs | 6. Loss Functions and Backpropagation | 15. Regression and Text Classification with FCNs | Artificial Intelligence


Why RNNs?

FCNs (see 4. Deep Learning and FCNs) treat input as flat vectors — they discard sequential information. Word order matters in NLP: “not bad” ≠ “bad”.

RNN Architecture

An RNN processes sequences one element at a time, maintaining a hidden state that acts as memory.

At each time step :

  • Input:
  • Hidden state:
  • Output:

The same weights (, , ) are shared across all time steps.

Backpropagation Through Time (BPTT)

The RNN is “unrolled” across time steps, and gradients are computed backwards through all steps (extending 6. Loss Functions and Backpropagation to the temporal domain). This is how RNNs learn temporal dependencies.

Padding Sequences

Since neural networks expect fixed-size inputs, sequences of different lengths are padded (typically with zeros) to the same length:

[1, 2, 3]    → [0, 1, 2, 3]
[4, 5]       → [0, 0, 4, 5]
[6, 7, 8, 9] → [6, 7, 8, 9]

Word Embeddings

Instead of sparse one-hot vectors, word embeddings map each word to a dense vector where similar words have similar representations.

Embedding layer:

Embedding(vocab_size, embedding_dim, input_length=max_len)
  • vocab_size — number of distinct words
  • embedding_dim — size of each embedding vector
  • input_length — length of input sequences

Word2Vec

A method for learning word embeddings from context:

  • CBOW (Continuous Bag of Words): predicts target word from context words
  • Skip-gram: predicts context words from target word

RNN for Text Classification (IMDB)

Embedding(10000, 300, input_length=200)
→ SimpleRNN(32)
→ Dense(1, sigmoid)

The final hidden state summarises the entire input sequence into a fixed-size vector for classification. Compare this with the FCN approach in 15. Regression and Text Classification with FCNs.

Stacking RNNs: Use return_sequences=True for intermediate RNN layers to pass full sequence to the next RNN layer.

RNN for Word Prediction

Embedding(vocab_size, embedding_dim, input_length=max_len)
→ SimpleRNN(hidden_units)
→ Dense(vocab_size, softmax)

Output: probability distribution over entire vocabulary for the next word. This is a neural alternative to the N-gram language models covered in NLP.

LSTM (Long Short-Term Memory)

Standard RNNs suffer from the vanishing gradient problem — gradients decay exponentially over long sequences, making it hard to learn long-term dependencies.

LSTMs solve this with a memory cell and gates:

GateFunction
Forget gateDecides what to discard from memory
Input gateDecides what new information to store
Output gateDecides what to output from memory