Learn PyTorch · 8/12

Recurrent Neural Networks (RNNs) for Sequence Data

8 min read

Recurrent Neural Networks (RNNs) for Sequence Data

Welcome, future PyTorch wizard! 🧙‍♂️ Get ready to dive into the world of Recurrent Neural Networks (RNNs). These are the specialized tools in your deep learning toolkit for understanding data that comes in sequences, like sentences, stock prices, or even DNA.

What's the Big Deal with Sequential Data?

The Problem: Imagine you're reading a book, but you have no memory of the previous words you just read. Each word would be a standalone piece of information, and you'd miss the entire story! This is the challenge with standard neural networks; they don't have a built-in way to remember past information. For example, in the sentences "The sky is blue" and "The ocean is blue," the meaning of "blue" is straightforward. But in "I feel blue," the context of "feel" completely changes its meaning.

The Solution: RNNs are designed with a "memory" that allows them to persist information. As they process a sequence, they keep a hidden state that captures what has been seen so far. This makes them perfect for tasks where context is everything.


1. Handling Sequential Data and Word Embeddings (nn.Embedding)

Before our RNN can work its magic, we need to convert our text into numbers. But not just any numbers! We need numbers that capture the meaning and relationships between words. This is where word embeddings come in.

What are Word Embeddings?

Think of word embeddings as a way to represent words as multi-dimensional vectors. Words with similar meanings will have similar vectors and be "closer" to each other in this vector space. For example, the vectors for "cat" and "dog" would be closer than the vectors for "cat" and "car." This allows our model to understand the nuances of language.

PyTorch's nn.Embedding Layer

PyTorch makes creating and using word embeddings super easy with the nn.Embedding layer. It's essentially a lookup table where each word in your vocabulary is mapped to a dense vector.

How it works:

  1. Build a Vocabulary: You'll start by creating a vocabulary of all the unique words in your dataset.
  2. Assign Indices: Each unique word is given a unique integer index.
  3. Create the Embedding Layer: You then create an nn.Embedding layer, telling it the size of your vocabulary and the desired dimension for your embedding vectors.

Let's see some code:

python
import torch 
import torch.nn as nn 

# Create a sample vocabulary 
vocab = {'hello': 0, 'world': 1, 'I': 2, 'love': 3, 'PyTorch': 4} 
vocab_size = len(vocab) 
embedding_dim = 10 

# Create the embedding layer 
embedding_layer = nn.Embedding(vocab_size, embedding_dim) 

# Convert a sentence to a tensor of indices 
sentence = "I love PyTorch" 
indices = torch.tensor([vocab[word] for word in sentence.split()], dtype=torch.long) 

# Get the embeddings 
word_embeddings = embedding_layer(indices) 

print("Indices:", indices) 
print("Embeddings shape:", word_embeddings.shape) 

Under the Hood: The nn.Embedding layer maintains a weight matrix of shape (vocab_size, embedding_dim). When you pass in a tensor of indices, it simply looks up the corresponding rows in this matrix. These weights are initially random but are learned and adjusted during the training process to better represent the relationships between words.

Fun Fact: The idea of representing words as vectors became widely popular with the development of the Word2Vec algorithm by Google in 2013.


2. Implementing Basic RNNs and LSTMs (nn.RNN, nn.LSTM)

Now that our words are in a numerical format that captures meaning, let's get to the heart of sequence modeling with RNNs and LSTMs.

The Basic RNN (nn.RNN)

The simplest type of recurrent neural network. At each step in a sequence, it takes the current input and the hidden state from the previous step to produce an output and a new hidden state.

Imagine you're watching a movie: 🎬 Your understanding of the current scene is heavily influenced by the scenes that came before it. The RNN's hidden state acts like your memory of the movie so far.

PyTorch in Action (nn.RNN):

python
import torch 
import torch.nn as nn 

input_size = 10  # Dimension of our word embeddings 
hidden_size = 20 # The size of the hidden state 
num_layers = 1   # Number of stacked RNN layers 

# Create an RNN layer 
rnn_layer = nn.RNN(input_size, hidden_size, num_layers, batch_first=True) 

# Create some dummy input data (batch_size, sequence_length, input_size) 
input_tensor = torch.randn(5, 3, 10) 

# Initialize the hidden state (num_layers, batch_size, hidden_size) 
h0 = torch.randn(num_layers, 5, hidden_size) 

# Pass the input and hidden state to the RNN 
output, hn = rnn_layer(input_tensor, h0) 

print("Output shape:", output.shape) 
print("Final hidden state shape:", hn.shape) 

A Major Hurdle: Vanishing and Exploding Gradients: Simple RNNs struggle with learning long-term dependencies. This is because, during backpropagation, the gradients can either shrink to near zero (vanish) or grow uncontrollably (explode). This makes it difficult for the model to learn relationships between distant elements in a sequence.

Long Short-Term Memory (LSTM) Networks (nn.LSTM)

LSTMs are a special kind of RNN designed to overcome the vanishing gradient problem. They have a more complex internal structure that includes a "cell state" and "gates" (input, forget, and output) that regulate the flow of information.

Think of an LSTM as having a more sophisticated memory system: It can choose to forget irrelevant information, store new important information, and decide what part of its memory is relevant for the current output. This allows it to remember things for much longer periods.

PyTorch Implementation (nn.LSTM):
The implementation is very similar to nn.RNN, but we now have a cell state to manage.

python
import torch 
import torch.nn as nn 

input_size = 10 
hidden_size = 20 
num_layers = 1 

# Create an LSTM layer 
lstm_layer = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True) 

input_tensor = torch.randn(5, 3, 10) 

# Initialize the hidden and cell states 
h0 = torch.randn(num_layers, 5, hidden_size) 
c0 = torch.randn(num_layers, 5, hidden_size) 

output, (hn, cn) = lstm_layer(input_tensor, (h0, c0)) 

print("Output shape:", output.shape) 
print("Final hidden state shape:", hn.shape) 
print("Final cell state shape:", cn.shape) 

Industry Standard: LSTMs and another variant called Gated Recurrent Units (GRUs) are the workhorses for most sequence-related tasks in the industry due to their ability to handle long-term dependencies effectively. Simple RNNs are rarely used in practice.


3. Dealing with Variable-Length Sequences (Packing and Padding)

The Problem: When processing a batch of sequences (like sentences), they will almost always have different lengths. However, PyTorch's RNNs expect all sequences in a batch to be of the same length.

The Solution: We use a technique called padding. We determine the length of the longest sequence in the batch and add a special "padding" token (usually 0) to the end of all shorter sequences until they are all the same length.

But wait, there's more! We don't want our RNN to treat these padded values as real data. To solve this, we use packing.

Padding and Packing in PyTorch

PyTorch has a set of handy utilities for this: pad_sequence and pack_padded_sequence.

  1. pad_sequence: Takes a list of tensors of varying lengths and pads them to the same length.
  2. pack_padded_sequence: Creates a PackedSequence object that tells the RNN to ignore the padded elements during computation.

Let's walk through an example:

python
import torch 
from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence 

# Sentences of varying lengths 
seq1 = torch.tensor([1, 2, 3, 4]) 
seq2 = torch.tensor([5, 6]) 
seq3 = torch.tensor([7, 8, 9]) 

sequences = [seq1, seq2, seq3] 

# Pad the sequences 
padded_sequences = pad_sequence(sequences, batch_first=True, padding_value=0) 
print("Padded Sequences:\n", padded_sequences) 

# Let's assume we've embedded these sequences 
embedding_dim = 10 
embedding_layer = nn.Embedding(10, embedding_dim) 
embedded_sequences = embedding_layer(padded_sequences) 

# Get the original lengths 
sequence_lengths = torch.tensor([len(s) for s in sequences]) 

# Pack the padded sequences (enforce_sorted=False is important if your data isn't pre-sorted by length) 
packed_input = pack_padded_sequence(embedded_sequences, sequence_lengths, batch_first=True, enforce_sorted=False) 
print("\nPacked Input:\n", packed_input) 

Why is this essential? Ignoring the padded elements not only prevents incorrect calculations but also makes your model more efficient by avoiding unnecessary computations. This is a standard and critical step in any serious NLP pipeline.


4. Building a Practical Text Classification Model

Let's put all these pieces together to build a model that can classify text, such as determining if a movie review is positive or negative.

Our Model's Architecture:

  1. Embedding Layer: Converts the input text into numerical vectors.
  2. LSTM Layer: Processes the sequence of embeddings to capture contextual information.
  3. Linear Layer: Takes the final hidden state from the LSTM and maps it to our output classes.

Let's build it!

python
import torch 
import torch.nn as nn 
from torch.nn.utils.rnn import pack_padded_sequence 

class TextClassifier(nn.Module): 
    def __init__(self, vocab_size, embedding_dim, hidden_dim, output_dim): 
        super(TextClassifier, self).__init__() 
        self.embedding = nn.Embedding(vocab_size, embedding_dim) 
        self.lstm = nn.LSTM(embedding_dim, hidden_dim, num_layers=1, batch_first=True) 
        self.fc = nn.Linear(hidden_dim, output_dim) 

    def forward(self, text, text_lengths): 
        embedded = self.embedding(text) 
        packed_embedded = pack_padded_sequence(embedded, text_lengths.cpu(), batch_first=True, enforce_sorted=False) 
        packed_output, (hidden, cell) = self.lstm(packed_embedded) 
        # We use the final hidden state of the LSTM for our prediction 
        return self.fc(hidden.squeeze(0)) 

# --- A simplified example of how to use the model --- 
vocab_size = 1000 
embedding_dim = 100 
hidden_dim = 256 
output_dim = 2  # e.g., positive or negative 

model = TextClassifier(vocab_size, embedding_dim, hidden_dim, output_dim) 

# Dummy data for a batch of 3 sentences of varying lengths 
text_batch = torch.tensor([[10, 45, 23, 0], [101, 5, 0, 0], [8, 99, 32, 1]]) 
text_lengths = torch.tensor([3, 2, 4]) 

predictions = model(text_batch, text_lengths) 
print("Model Predictions:\n", predictions) 

What's going on in the forward method?

  1. The input text is passed through the embedding layer.
  2. The embeddings are packed to handle the different sequence lengths.
  3. The packed embeddings are fed into the LSTM.
  4. We take the final hidden state from the LSTM (hidden.squeeze(0)) as a summary of the entire sequence.
  5. This summary is passed through a linear layer to produce the final classification scores.

Congratulations! 🎉 You now have the foundational knowledge to tackle a wide range of sequence modeling problems with PyTorch.


References for Further Reading

Challenge

Challenge: Build a PyTorch LSTM Text Classifier

You are tasked with creating a neural network for text classification using PyTorch. Your model should process sequences of word indices and output raw prediction scores (logits) for different classes.

Requirements:

  1. Define a class named TextClassifier that inherits from torch.nn.Module.
  2. The __init__ method must accept the following parameters: vocab_size, embedding_dim, hidden_dim, and output_dim.
  3. Inside the __init__ method, you must initialize the following three layers in this specific order:
    • An nn.Embedding layer to convert word indices into dense vectors.
    • An nn.LSTM layer to process the sequence of embeddings. This layer must be configured to expect input tensors where the batch dimension comes first.
    • An nn.Linear layer that will act as the final classification head.
  4. Implement the forward method, which takes a single argument: a tensor of batched text indices.
  5. Inside the forward method, define the data flow:
    • Pass the input indices through the embedding layer.
    • Feed the resulting embeddings into the LSTM layer.
    • From the output of the LSTM, isolate the final hidden state from the last layer.
    • Pass only this final hidden state to the linear layer to get the logits.
    • Return the logits.

Expected result

Your completed code should define the TextClassifier class with fully implemented __init__ and forward methods. The __init__ method correctly instantiates nn.Embedding, nn.LSTM (with batch_first=True), and nn.Linear layers. The forward method correctly processes the input through these layers, extracts the final hidden state from the LSTM's tuple output, and passes it to the linear layer.

python
import torch
import torch.nn as nn

class TextClassifier(nn.Module):
    def __init__(self, vocab_size, embedding_dim, hidden_dim, output_dim):
        super(TextClassifier, self).__init__()
        self.embedding = nn.Embedding(vocab_size, embedding_dim)
        self.lstm = nn.LSTM(embedding_dim, hidden_dim, batch_first=True)
        self.fc = nn.Linear(hidden_dim, output_dim)

    def forward(self, text_indices):
        # text_indices shape: (batch_size, seq_length)
        embedded = self.embedding(text_indices)
        # embedded shape: (batch_size, seq_length, embedding_dim)

        # The LSTM returns output, and a tuple of the final hidden and cell states
        # lstm_out shape: (batch_size, seq_length, hidden_dim)
        # hidden shape: (num_layers, batch_size, hidden_dim)
        lstm_out, (hidden, cell) = self.lstm(embedded)

        # We use the hidden state from the last time step of the last layer
        # Squeezing is not necessary but can be done if num_layers is 1
        final_hidden_state = hidden[-1]

        # Pass the final hidden state to the fully connected layer
        output = self.fc(final_hidden_state)
        # output shape: (batch_size, output_dim)
        return output
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.