Home Topics RNN & LSTM

RNN & LSTM

Processing sequential and temporal data

6 hours 12 examples Advanced
Beginner

What is RNN?

A Recurrent Neural Network (RNN) is a neural network designed for sequential data. Unlike feedforward networks, RNNs have memory - they maintain a hidden state that captures information from previous inputs.

The Key Difference

Regular NNs process each input independently. RNNs remember previous inputs, making them perfect for sequences like text, audio, and time series.

Language Models

Time Series

Audio/Speech

Intermediate

The Vanishing Gradient Problem

Simple RNNs struggle with long sequences. Gradients shrink exponentially as they propagate back through time, making it hard to learn long-range dependencies.

The Problem

In a sentence like "The cat, which sat on the mat and ate the fish, was happy" - the RNN might forget "cat" by the time it reaches "was".

Intermediate

LSTM Networks

Long Short-Term Memory (LSTM) networks solve the vanishing gradient problem using a gating mechanism to control information flow.

LSTM Gates

Forget Gate

Decides what to discard from memory.

Input Gate

Decides what new information to add.

Output Gate

Decides what to output from memory.

Advanced

GRU (Gated Recurrent Unit)

GRU is a simplified version of LSTM with fewer gates. Often performs similarly with less computation.

LSTM vs GRU

LSTM

  • • 3 gates (forget, input, output)
  • • More parameters
  • • Better for complex sequences

GRU

  • • 2 gates (reset, update)
  • • Fewer parameters
  • • Faster to train
Advanced

Build an LSTM

lstm_sentiment.py
from tensorflow.keras import layers, models

# LSTM for sentiment analysis
model = models.Sequential([
    # Embedding layer for text
    layers.Embedding(input_dim=10000, output_dim=128),
    
    # LSTM layer
    layers.LSTM(64, return_sequences=True),
    layers.LSTM(32),  # Stacked LSTM
    
    # Dense output
    layers.Dense(16, activation='relu'),
    layers.Dropout(0.3),
    layers.Dense(1, activation='sigmoid')  # Binary
])

model.compile(optimizer='adam',
              loss='binary_crossentropy',
              metrics=['accuracy'])

model.summary()

Next: Generative Adversarial Networks

Learn how GANs create stunning new content.