Sequential NLP
Module Completed: February 2022
π― Module Overview
Sequential models process text as ordered sequences, capturing contextual dependencies that statistical approaches miss. This module covers Recurrent Neural Networks (RNN), Long Short-Term Memory (LSTM), Bidirectional LSTMs, and the attention mechanism that underpins modern transformers. The project applies these to sentiment analysis and sarcasm detection.
π Topics Covered
Why Sequential Models?
Bag-of-Words and TF-IDF lose word order β "good, not bad" and "bad, not good" have identical BoW representations. Sequential models process words in order, maintaining a hidden state that carries context from earlier positions:
- "I loved it" β context built left to right
- "I didn't love it" β the "didn't" modifies what follows β only captured with sequence awareness
Recurrent Neural Networks (RNN)
An RNN processes input tokens one at a time, maintaining a hidden state h:
hβ = tanh(WβΒ·xβ + WβΒ·hβββ + b)
The hidden state acts as a "memory" passing information from step to step. One set of weights shared across all time steps (parameter efficiency).
Problems with Vanilla RNN:
- Vanishing Gradient β gradients shrink exponentially as they backpropagate through many time steps; early tokens are "forgotten"
- Exploding Gradient β gradients grow unboundedly; clipped with
gradient_clipping - Struggles with long-range dependencies (e.g., subject-verb agreement across a long sentence)
Long Short-Term Memory (LSTM)
LSTM introduces a cell state (Cβ) alongside the hidden state, with three learned gates that control information flow:
| Gate | Formula | Role |
|---|---|---|
| Forget Gate | Ο(WfΒ·[hβββ, xβ] + bf) | Decides what to erase from cell state |
| Input Gate | Ο(WiΒ·[hβββ, xβ] + bi) | Decides what new info to write to cell state |
| Output Gate | Ο(WoΒ·[hβββ, xβ] + bo) | Decides what part of cell state to output as hβ |
| Cell State Update | Cβ = fβCβββ + iβtanh(WcΒ·[hβββ,xβ]+bc) | Gated update of long-term memory |
Gates use sigmoid (Ο) β output between 0 and 1 β acting as a soft switch. LSTM can maintain context over hundreds of time steps.
GRU (Gated Recurrent Unit)
Simplified LSTM with only 2 gates (Reset + Update):
- Fewer parameters β trains faster; often comparable performance to LSTM
GRU(units)in Keras
Bidirectional LSTM
Processes sequence both left-to-right AND right-to-left; concatenates both hidden states:
- Forward LSTM: sees past context
- Backward LSTM: sees future context
- Together: each token's representation is informed by its full surrounding context
- Especially powerful for classification tasks (sentiment, NER, sarcasm)
Bidirectional(LSTM(units))
Sequence Padding
RNNs require fixed-length input sequences:
pad_sequences(sequences, maxlen=500, padding='pre')β pad at the start (pre-padding is standard for LSTM)- Shorter sequences get zero-padding; longer sequences are truncated
maxlenis a hyperparameter: too short = information lost; too long = slower training, more padding noise
Embedding Layer
Learns dense word representations as part of the network (unlike pre-computed Word2Vec):
Embedding(vocab_size, embedding_dim, input_length=maxlen)- Converts integer token IDs to dense vectors; trained end-to-end with the rest of the model
- More flexible than static embeddings β learned for the specific task
Pre-trained Embeddings (GloVe)
Global Vectors for Word Representation β trained on global word-word co-occurrence statistics from large corpora:
- Captures semantic relationships as vector offsets
embedding_dim = 100or 300 common; load from pre-trained.txtfile- Build weight matrix from GloVe vectors β initialise Embedding layer with
weights=[embedding_matrix],trainable=False - Especially useful when training data is limited
Attention Mechanism
Core innovation that led to the Transformer architecture:
- Instead of compressing the entire input into a single fixed-length context vector, attention allows the model to "look back" at all encoder hidden states when generating each output token
- Attention Score = how relevant each encoder hidden state is to the current decoder position
- Attention Weights = softmax over scores β probability distribution over input positions
- Context Vector = weighted sum of encoder hidden states using attention weights
- Used in Neural Machine Translation (NMT):
NMT with Attention.ipynb
Neural Machine Translation (NMT) with Attention
- Encoder β LSTM processes source sentence; outputs all hidden states + final context
- Decoder β LSTM generates target sentence token by token; attention weights computed at each step to focus on relevant source tokens
- Overcomes fixed-length bottleneck of seq2seq without attention
Advanced Language Models (Overview)
- ELMo (Embeddings from Language Models) β context-aware embeddings from bidirectional LSTMs; same word gets different embeddings depending on context
- BERT (Bidirectional Encoder Representations from Transformers) β transformer-based; pre-trained with Masked Language Modelling + Next Sentence Prediction; fine-tuned for downstream tasks; context flows in both directions simultaneously
- GPT β autoregressive transformer; pre-trained on next-word prediction; strong text generation
- Transformer Architecture β multi-head self-attention; no recurrence β parallelisable; position encodings replace positional information from sequential processing
π Project β Sequential NLP: Sentiment & Sarcasm Classification (NLP-2)
Submitted: 20 February 2022
Part 1 β IMDB Movie Review Sentiment Analysis (LSTM)
Domain: Digital Content & Entertainment
Business Problem: Classify 50,000 IMDB movie reviews as positive or negative sentiment.
Dataset:
- 50,000 reviews, pre-encoded as integer sequences (word index = frequency rank)
- Vocabulary size: 10,000 most frequent words; index 0 = unknown word (OOV)
maxlen = 500tokens; pre-padded sequences
Model Architecture:
Embedding(10000, embedding_dim, input_length=500)
β LSTM(units)
β Dense(1, sigmoid)
Loss: Binary Crossentropy | Optimiser: Adam
Results:
| Config | Training Acc | Validation Acc | Test Acc |
|---|---|---|---|
| Baseline LSTM | ~98.4% | ~86.9% | ~85.2% |
| LSTM + longer maxlen | Minimal improvement | Minimal improvement | β |
| LSTM + more units | Minimal improvement | β | β |
| LSTM + stop word removal | No improvement | β | β |
Findings:
- Baseline LSTM achieved good test accuracy (~85%)
- Model slightly overfitted (train 98% vs val 87%) β all 3 tuning attempts had minimal impact
- Main route to further improvement: increase training data size
Part 2 β News Headline Sarcasm Detection (Bidirectional LSTM + GloVe)
Domain: Social Media Analytics
Business Problem: Classify news headlines as sarcastic (The Onion) or genuine (HuffPost).
Dataset:
- 28,619 headlines (theonion.com + huffingtonpost.com)
- Target:
is_sarcastic(binary); 12 duplicate headlines removed - Feature:
headlinetext only (article_linkdropped)
Preprocessing:
clean_headlineβ tokenisation + lemmatisation + stemming applied- WordCloud generated for visual EDA
- Sequences converted to integer indices (word-to-index mapping)
- Vocabulary size computed from corpus
- Padding applied to uniform sequence length
Embedding:
- GloVe pre-trained embeddings loaded β weight matrix built for vocabulary
- Embedding layer initialised with GloVe weights (
trainable=False)
Model Architecture:
Embedding(vocab_size, glove_dim, weights=[glove_matrix], trainable=False)
β Bidirectional(LSTM(units))
β Dense(1, sigmoid)
Loss: Binary Crossentropy | Optimiser: Adam
Results:
- Limited epochs run (technical constraint)
- Bidirectional LSTM + GloVe intended to leverage both left and right context + pre-trained semantic knowledge
- Accuracy improvable with 10β15 epochs and larger LSTM units
π Key Learnings
- Sequential models capture order; BoW does not β "not good" and "good not" are identical to BoW but opposite in meaning; LSTM preserves this distinction
- LSTM gates = selective memory β forget gate prevents irrelevant old information from persisting; input gate controls what new information matters; output gate controls what to expose
- Pre-padding is standard for LSTM β padding at the start means the actual text (more informative) is closest to the LSTM output
- Bidirectional LSTM for classification β full context (past + future) gives richer representations for tasks like sentiment and sarcasm where the whole sentence matters
- GloVe embeddings help with small datasets β initialising with pre-trained weights gives the model semantic head start;
trainable=Falseprevents forgetting during fine-tuning - Overfitting in LSTMs β adding Dropout after LSTM layers or using recurrent dropout is more effective than just tuning review length or units
- Attention > fixed context vector β seq2seq without attention compresses everything into one vector; attention lets the decoder look at the full input, dramatically improving translation quality
- BERT is bidirectional at training time β unlike stacked Bidirectional LSTMs, BERT's transformer attention sees all positions simultaneously, not just left or right
π οΈ Tools & Libraries
import re
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from wordcloud import WordCloud
import nltk
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer, WordNetLemmatizer
import tensorflow as tf
from tensorflow import keras
from keras.models import Sequential, Model
from keras.layers import (Embedding, LSTM, GRU, Dense, Dropout,
Bidirectional, Attention)
from keras.optimizers import Adam
from keras.preprocessing.sequence import pad_sequences
from keras.preprocessing.text import Tokenizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, confusion_matrix