Sequence Models for Text: RNN and CNN Classifiers
A bag of words ignores order. "not good, just boring" and "not boring, just good" contain exactly the same words and get the same features. Linear models on TF-IDF partly patch this with word pairs, but a pair only covers two adjacent words. Before transformers, two neural families read text as a sequence: recurrent networks (LSTM, GRU) that carry a state from word to word, and 1-D convolutional networks that slide learned -gram detectors over the sentence.
You built both cells and the training machinery in the deep-learning course: LSTM and GRU in Practice for the gates and PyTorch's layout, Training Sequence Models for padding, masks and pack_padded_sequence. This lesson applies them to sentence classification on real movie reviews and asks the question you should always ask: do they beat the linear baseline?
Three ways to turn a sentence into one vector
All three models start the same way: words become ids from a vocabulary, ids become vectors through an nn.Embedding (Embedding Layers), and a sentence of words becomes a matrix . They differ in how they reduce to one vector for the classifier .
Embedding bag (average). . This is fastText's classifier. It is fast and strong, but it is still a bag: order is lost unless you add -gram tokens.
Recurrent. with an LSTM or GRU cell, and , the state after the last real word. A bidirectional LSTM runs a second cell from right to left and concatenates both final states, so the sentence's start and end both get a short path to .
Convolutional (Kim 2014). A filter of width is a weight tensor that scores every window of consecutive words, and max-over-time pooling keeps its best score anywhere in the sentence:
With filters, . Each filter becomes a learned, soft -gram detector ("not good", "a waste of"), and the max makes it position-invariant: it does not matter where in the sentence the phrase occurs.
Max-over-time pooling in NumPy
The first example hand-sets one width-2 filter on 3-dimensional toy embeddings (dimension 0 = negator, 1 = positive word, 2 = negative word) so that it fires on "negator followed by a positive word". It reports the maximum and which window produced it.
import numpy as np
# 3-d toy embeddings: dimension 0 = "negator", 1 = "positive word", 2 = "negative word"
emb = {"<pad>": [0, 0, 0], "the": [0, 0, 0], "film": [0, 0, 0], "was": [0, 0, 0], "plot": [0, 0, 0],
"not": [1, 0, 0], "good": [0, 1, 0], "great": [0, 1, 0], "bad": [0, 0, 1], "but": [0, 0, 0], "so": [0, 0, 0]}
# one filter of width 2: fires on "negator followed by a positive word"
W = np.array([[2.0, 0.0, 0.0], # weights for the first word of the window
[0.0, 2.0, -1.0]]) # weights for the second word
b = -2.5
def conv_max(words, pad_to=8, mask=True, relu=True):
X = np.array([emb[w] for w in words + ["<pad>"] * (pad_to - len(words))], dtype=float)
a = np.array([np.sum(W * X[t:t + 2]) + b for t in range(len(X) - 1)]) # one value per window
if relu:
a = np.maximum(a, 0)
if mask:
a[len(words) - 1:] = -np.inf # windows that touch padding
t = int(np.argmax(a))
return round(float(a[t]), 2), " ".join((words + ["<pad>"] * 8)[t:t + 2])
for s in ["the film was not good", "not good", "the plot was good but not great", "the film was good"]:
print(f"{s:34s} max {conv_max(s.split())}")
print("without ReLU or mask:")
for s in ["the film was good", "so bad"]:
print(f"{s:34s} masked {conv_max(s.split(), relu=False)}, unmasked {conv_max(s.split(), relu=False, mask=False)}")the film was not good max (1.5, 'not good')
not good max (1.5, 'not good')
the plot was good but not great max (1.5, 'not great')
the film was good max (0.0, 'the film')
without ReLU or mask:
the film was good masked (-0.5, 'was good'), unmasked (-0.5, 'was good')
so bad masked (-3.5, 'so bad'), unmasked (-2.5, 'bad <pad>')
The filter gives 1.5 wherever "not good" or "not great" occurs, at the start, the end or the middle of the sentence, and stays silent (0.0) on "the film was good". The last two lines show why the padding mask matters. Sentences in a batch are padded to the same length with a zero vector, and a window of padding scores exactly the bias . Without ReLU, for "so bad" the best real window scores , so the unmasked maximum, , comes from the padding window bad <pad>. The model's output then depends on how long the other sentences in the batch were. Set padded positions to before the max (with ReLU the scores are and a zero from padding is harmless only by luck).
Why order matters: an embedding bag with and without bigrams
The second example trains the average-embedding model with plain NumPy SGD on templated reviews such as "the cast was really not dull" (positive). 40 % of the sentences are negated, so the label is the adjective's polarity flipped by "not". It trains twice: on words, and on words plus bigram tokens such as not_dull (fastText's wordNgrams=2).
import numpy as np
rng = np.random.default_rng(0)
pos, neg = ["good", "great", "funny", "moving", "clever"], ["bad", "dull", "boring", "weak", "silly"]
nouns, fill = ["film", "plot", "cast", "ending", "script"], ["the", "was", "really", "quite", "very"]
def make(n):
data = []
for _ in range(n):
positive, negated = rng.random() < 0.5, rng.random() < 0.4
adj = rng.choice(pos if positive else neg)
words = ["the", rng.choice(nouns), "was", rng.choice(fill[2:])] + (["not"] if negated else []) + [adj]
data.append((words, int(positive != negated), negated))
return data
def features(words, bigrams):
toks = words + ([a + "_" + b for a, b in zip(words, words[1:])] if bigrams else [])
return toks
def train_bag(data, bigrams, d=8, epochs=20, lr=0.05):
vocab = sorted({t for w, _, _ in data for t in features(w, bigrams)})
idx = {t: i for i, t in enumerate(vocab)}
E = rng.normal(0, 0.1, (len(vocab), d)); w = rng.normal(0, 0.1, d); b = 0.0
for _ in range(epochs):
for words, y, _ in data:
ids = [idx[t] for t in features(words, bigrams)]
h = E[ids].mean(0) # the embedding-bag average
p = 1 / (1 + np.exp(-(h @ w + b)))
g = p - y # d loss / d logit for log loss
gE = g * w / len(ids)
w -= lr * g * h; b -= lr * g
np.add.at(E, ids, -lr * gE)
def predict(words):
ids = [idx[t] for t in features(words, bigrams) if t in idx]
return int(E[ids].mean(0) @ w + b > 0)
return predict
train, test = make(600), make(400)
for bigrams in (False, True):
predict = train_bag(train, bigrams)
for name, part in [("plain", [x for x in test if not x[2]]), ("negated", [x for x in test if x[2]])]:
acc = np.mean([predict(w) == y for w, y, _ in part])
print(f"{'words + bigrams' if bigrams else 'words only':15s} {name:8s} test sentences: accuracy {acc:.3f} (n = {len(part)})")words only plain test sentences: accuracy 0.845 (n = 251)
words only negated test sentences: accuracy 0.235 (n = 149)
words + bigrams plain test sentences: accuracy 1.000 (n = 251)
words + bigrams negated test sentences: accuracy 1.000 (n = 149)
With words only, the model reaches 0.845 on plain test sentences and 0.235 on negated ones, worse than chance: it learns "dull is negative", which is right without "not" and wrong with it. An average of word vectors is a linear function of the word counts, so it cannot represent "polarity flipped by not". Adding bigram tokens makes not_dull its own feature, and both groups reach 1.000. A CNN with width-2 filters or an LSTM gets the same ability without a hand-made list of -grams. On this toy problem everyone with bigrams wins; on real text the question is whether the extra capacity pays for itself.
The baseline on real reviews
The real data is the rotten_tomatoes sentence-polarity set: lower-cased, tokenised movie-review sentences labelled 1 (positive) or 0 (negative). All models in this lesson use the same 2,000 training sentences and 500 validation sentences (fixed seeded shuffles of the official splits). The hyperparameters were fixed before looking at the validation scores, and none of them was tuned on these 500 sentences, so validation accuracy is an honest estimate here. With 500 sentences its standard error is about , so differences below about 0.04 are noise.
from datasets import load_dataset
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
train = ds["train"].shuffle(seed=0).select(range(2000))
val = ds["validation"].shuffle(seed=0).select(range(500))
print("train:", len(train), "positive share", round(sum(train["label"]) / len(train), 3),
"| validation:", len(val), "positive share", round(sum(val["label"]) / len(val), 3))
print("example:", train[0]["text"][:90], "->", train[0]["label"])
for ngram in [(1, 1), (1, 2)]:
vec = TfidfVectorizer(ngram_range=ngram, min_df=2, sublinear_tf=True)
Xtr = vec.fit_transform(train["text"]) # fitted on the training sentences only
clf = LogisticRegression(C=4, max_iter=1000).fit(Xtr, train["label"])
acc = accuracy_score(val["label"], clf.predict(vec.transform(val["text"])))
print(f"TF-IDF {ngram} + logistic regression: {Xtr.shape[1]} features, validation accuracy {acc:.3f}")train: 2000 positive share 0.486 | validation: 500 positive share 0.494
example: this is pure , exciting moviemaking . you won't exactly know what's happening but you'll b -> 1
TF-IDF (1, 1) + logistic regression: 3175 features, validation accuracy 0.702
TF-IDF (1, 2) + logistic regression: 6123 features, validation accuracy 0.702
TF-IDF with logistic regression gets 0.702 with words alone and 0.702 with words and word pairs, both vectorizers fitted on the training sentences only (with ; Text Classification used and got 0.696, a difference of 3 sentences). That is the number to beat.
An LSTM classifier
The vocabulary is built from the training sentences only (words seen at least twice, plus <pad> = 0 and <unk> = 1). pack_padded_sequence makes the LSTM skip the padding, so h holds the state after each sentence's real last word in both directions; enforce_sorted=False lets the batch stay in its original order.
import torch, torch.nn as nn
from collections import Counter
from datasets import load_dataset
torch.manual_seed(0)
ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
train = ds["train"].shuffle(seed=0).select(range(2000))
val = ds["validation"].shuffle(seed=0).select(range(500))
counts = Counter(w for t in train["text"] for w in t.split()) # vocabulary from training text only
itos = ["<pad>", "<unk>"] + sorted(w for w, c in counts.items() if c >= 2)
stoi = {w: i for i, w in enumerate(itos)}
def batchify(texts, labels, max_len=50):
ids = [[stoi.get(w, 1) for w in t.split()[:max_len]] for t in texts]
lengths = torch.tensor([len(x) for x in ids])
X = torch.zeros(len(ids), int(lengths.max()), dtype=torch.long) # 0 = <pad>
for i, x in enumerate(ids):
X[i, :len(x)] = torch.tensor(x)
return X, lengths, torch.tensor(labels)
Xtr, Ltr, ytr = batchify(train["text"], train["label"])
Xva, Lva, yva = batchify(val["text"], val["label"])
def fit(model, epochs, lr=2e-3, bs=32):
opt = torch.optim.Adam(model.parameters(), lr=lr)
g = torch.Generator().manual_seed(0)
for ep in range(epochs):
model.train()
for b in torch.randperm(len(ytr), generator=g).split(bs):
loss = nn.functional.cross_entropy(model(Xtr[b], Ltr[b]), ytr[b])
opt.zero_grad(); loss.backward(); opt.step()
model.eval()
with torch.no_grad():
tr = (model(Xtr, Ltr).argmax(1) == ytr).float().mean().item()
va = (model(Xva, Lva).argmax(1) == yva).float().mean().item()
print(f"epoch {ep + 1}: train acc {tr:.3f}, validation acc {va:.3f}")
from torch.nn.utils.rnn import pack_padded_sequence
class LSTMClassifier(nn.Module):
def __init__(self, V, d=64, hidden=64):
super().__init__()
self.emb = nn.Embedding(V, d, padding_idx=0)
self.lstm = nn.LSTM(d, hidden, batch_first=True, bidirectional=True)
self.drop = nn.Dropout(0.3)
self.out = nn.Linear(2 * hidden, 2)
def forward(self, X, lengths):
packed = pack_padded_sequence(self.emb(X), lengths, batch_first=True, enforce_sorted=False)
_, (h, _) = self.lstm(packed) # h: (2 directions, batch, hidden), real last steps only
return self.out(self.drop(torch.cat([h[0], h[1]], dim=1)))
print("vocabulary:", len(itos), "| unknown share in validation:", round((Xva == 1).sum().item() / Lva.sum().item(), 3))
model = LSTMClassifier(len(itos))
print("parameters:", sum(p.numel() for p in model.parameters()))
fit(model, epochs=6)vocabulary: 3154 | unknown share in validation: 0.182
parameters: 268674
epoch 1: train acc 0.612, validation acc 0.560
epoch 2: train acc 0.716, validation acc 0.600
epoch 3: train acc 0.818, validation acc 0.612
epoch 4: train acc 0.940, validation acc 0.626
epoch 5: train acc 0.983, validation acc 0.622
epoch 6: train acc 0.995, validation acc 0.642
Two things stand out. First, 18.2 % of the validation tokens are <unk>: with 2,000 sentences, many words of the validation sentences were never seen twice in training. Second, the model overfits fast: training accuracy is 0.995 after 6 epochs while validation accuracy creeps up to 0.642. It has 268,674 parameters, and the embedding table alone holds of them, learned from 2,000 sentences.
A 1-D CNN classifier
The CNN uses 64 filters for each of the widths 2, 3 and 4, padding so that short sentences still have windows, and the same mask before the max as the NumPy version.
import torch, torch.nn as nn
from collections import Counter
from datasets import load_dataset
torch.manual_seed(0)
ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
train = ds["train"].shuffle(seed=0).select(range(2000))
val = ds["validation"].shuffle(seed=0).select(range(500))
counts = Counter(w for t in train["text"] for w in t.split()) # vocabulary from training text only
itos = ["<pad>", "<unk>"] + sorted(w for w, c in counts.items() if c >= 2)
stoi = {w: i for i, w in enumerate(itos)}
def batchify(texts, labels, max_len=50):
ids = [[stoi.get(w, 1) for w in t.split()[:max_len]] for t in texts]
lengths = torch.tensor([len(x) for x in ids])
X = torch.zeros(len(ids), int(lengths.max()), dtype=torch.long) # 0 = <pad>
for i, x in enumerate(ids):
X[i, :len(x)] = torch.tensor(x)
return X, lengths, torch.tensor(labels)
Xtr, Ltr, ytr = batchify(train["text"], train["label"])
Xva, Lva, yva = batchify(val["text"], val["label"])
def fit(model, epochs, lr=2e-3, bs=32):
opt = torch.optim.Adam(model.parameters(), lr=lr)
g = torch.Generator().manual_seed(0)
for ep in range(epochs):
model.train()
for b in torch.randperm(len(ytr), generator=g).split(bs):
loss = nn.functional.cross_entropy(model(Xtr[b], Ltr[b]), ytr[b])
opt.zero_grad(); loss.backward(); opt.step()
model.eval()
with torch.no_grad():
tr = (model(Xtr, Ltr).argmax(1) == ytr).float().mean().item()
va = (model(Xva, Lva).argmax(1) == yva).float().mean().item()
print(f"epoch {ep + 1}: train acc {tr:.3f}, validation acc {va:.3f}")
class CNNClassifier(nn.Module):
def __init__(self, V, d=64, filters=64, widths=(2, 3, 4)):
super().__init__()
self.emb = nn.Embedding(V, d, padding_idx=0)
self.convs = nn.ModuleList(nn.Conv1d(d, filters, k, padding=k - 1) for k in widths)
self.drop = nn.Dropout(0.5)
self.out = nn.Linear(filters * len(widths), 2)
def forward(self, X, lengths):
e = self.emb(X).transpose(1, 2) # (batch, d, time) for Conv1d
pooled = []
for conv in self.convs:
a = torch.relu(conv(e))[:, :, :X.shape[1]] # windows ending at positions 0..T-1
mask = torch.arange(X.shape[1])[None, None, :] >= lengths[:, None, None]
pooled.append(a.masked_fill(mask, float("-inf")).max(dim=2).values) # max over time
return self.out(self.drop(torch.cat(pooled, dim=1)))
model = CNNClassifier(len(itos))
print("parameters:", sum(p.numel() for p in model.parameters()))
fit(model, epochs=6)parameters: 239298
epoch 1: train acc 0.581, validation acc 0.504
epoch 2: train acc 0.858, validation acc 0.608
epoch 3: train acc 0.901, validation acc 0.612
epoch 4: train acc 0.936, validation acc 0.610
epoch 5: train acc 0.962, validation acc 0.620
epoch 6: train acc 0.975, validation acc 0.644
The CNN reaches 0.644, the same as the LSTM within noise. It is also the cheaper model to run: the convolutions over all positions are computed in parallel, while the LSTM has to step through the sentence one word at a time.
The honest comparison
| Model (2,000 training sentences) | Validation accuracy (500 sentences) |
|---|---|
| TF-IDF words + logistic regression | 0.702 |
| TF-IDF words and pairs + logistic regression | 0.702 |
| Bidirectional LSTM, embeddings from scratch | 0.642 |
| 1-D CNN, widths 2-4, embeddings from scratch | 0.644 |
The neural models lose by about 0.06, three standard errors. That is the typical result with little data and embeddings learned from scratch: the network must learn what every word means from 2,000 sentences, while TF-IDF only has to learn one weight per word. The neural models were state of the art on this data set in their time for two reasons that are both missing here: they were trained on all 8,530 sentences, and their embeddings were pretrained on billions of words (word2vec in Kim's CNN). Pretraining is the whole story of the rest of this course. A frozen sentence encoder already helps (Sentence Embeddings), and a fine-tuned BERT does better still (Fine-Tuning BERT for Text Classification).
Where RNNs and CNNs still earn their place: on-device models with tight latency or memory budgets, streaming input (an RNN processes one token at a time with constant memory), character-level models for noisy text, and as small, fast heads on top of frozen pretrained features.
Pitfalls
- Vocabulary from all data. Building the word index on train and test together leaks test words into the model; build it on training text, map the rest to
<unk>. - Unmasked padding. Mean pooling over padded positions, max pooling without a mask, or taking
output[:, -1]of a padded RNN all read padding. Use packing,lengths - 1indexing or masks. - Choosing the epoch on the test set. Here the number of epochs was fixed in advance. Picking the best epoch from the curve means tuning on that data; use a separate split for early stopping.
- Comparing against no baseline. A neural model without a TF-IDF + linear baseline on the same split tells you nothing. On small data the baseline often wins.
- Truncation.
max_len=50cuts long inputs; check the length distribution before choosing it (here 4 of the 2,000 training sentences are longer, and the mean is about 21 words). - Accuracy differences within noise. With 500 evaluation sentences, 0.642 against 0.644 is a tie.
Practice
- For the CNN, count the parameters of one
Conv1d(64, 64, 3)layer, and check that the total printed by the example is . - In the NumPy CNN, what would change if the padding embedding were not the zero vector but a learned vector?
- The words-only embedding bag scored 0.235 on negated sentences. Why is that worse than chance, and what would a constant classifier score on that group?
- Name two changes that would most likely close the gap between the LSTM and the TF-IDF baseline, and one that would not.
- Why does the LSTM example use
hfromself.lstm(packed)rather than the last time step of the padded output?
Answers
- One layer: . All three: . Embedding , output layer . Total , as printed.
- A padding window would no longer score exactly but plus the filter applied to the learned padding vector, an arbitrary value that training could even push up. Without a mask, padding could then win the max, and the prediction would depend on how much padding the batch added.
padding_idx=0keeps the padding row at zero and out of the gradient; the mask makes the result independent of padding in every case. - On a negated sentence the correct label is the opposite of the adjective's polarity, and the model mostly predicts the adjective's polarity, so it is systematically wrong rather than randomly wrong. A constant classifier would score the share of the majority label in that group, about 0.5.
- Likely to help: pretrained word embeddings (or a pretrained encoder), and training on all 8,530 sentences. Probably not: a bigger LSTM, which only overfits faster (training accuracy is already 0.995).
- With padding, the padded output's last step is the state after reading padding for every sentence shorter than the batch maximum. The packed LSTM's
his the state at each sentence's real last token (and, for the backward direction, after reading the sentence from its real end).
Test yourself
What does max-over-time pooling give a CNN text classifier?
- The ability to model arbitrarily long dependencies
- Position invariance: a filter's best match counts wherever the phrase occurs
- A smaller vocabulary
- Normalised probabilities
Why did the words-only embedding bag fail on negated sentences?
- The learning rate was too high
- An average of word vectors is linear in the word counts and cannot express that 'not' flips the adjective's polarity
- The vocabulary was too small
- It had no bias term
On 2,000 rotten_tomatoes sentences, which model scored best on the 500 validation sentences?
- Bidirectional LSTM
- 1-D CNN
- TF-IDF + logistic regression
- All within 0.01
Why is the padding mask needed before max pooling?
- To make training faster
- Padding windows score the bias, which can beat every real window when scores are negative, so the output would depend on the other sentences in the batch
- Because PyTorch requires it
- To reduce the number of parameters