Lab: Sentiment Classification with Embeddings and an LSTM
Generate a seeded review dataset in which negation and "but" make word order matter, score TF-IDF plus logistic regression with unigrams to trigrams, train an Embedding plus LSTM classifier with packed sequences over three seeds on the same split, measure what ignoring the padding costs, and weigh the gain against training time.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Generate the reviews
- Step 2: The bag-of-words baseline
- Step 3: Vocabulary, padding and DataLoaders
- Step 4: The Embedding + LSTM classifier
- Step 5: Train over three seeds
- Step 6: What ignoring the padding costs
- Step 7: Weigh the gain against the cost
- Check your understanding
- Apply it
- Review prompt
Lessons of Sequence Models & RNNs
- From Text and Time Series to Tensors Concept · 20 min
- Recurrent Networks and Their Gates Concept · 20 min
- Lab: Sentiment Classification with Embeddings and an LSTM Lab · 30 min
- Worked Example: Forecasting with a GRU Without Peeking at the Future Worked example · 25 min
- Why Recurrence Hit a Wall: Long Dependencies and Attention Concept · 15 min
- Check: Sequences, Gates and Masks Knowledge check · 6 questions
What you will learn
- Prepare sequence data for training: tokenize text into ids with padding and masks, or window a time series with a leakage-free temporal split.
- Train an embedding plus LSTM or GRU model for sequence classification or forecasting in PyTorch and compare it with a non-sequential baseline such as bag-of-words or lag features.
Prerequisites: Deep Learning Fundamentals
01. Goal and setup
In this lab you train a sentiment classifier twice: once as a bag of words, which ignores word order, and once as a recurrent network that reads the words in order. You then decide, with numbers, whether the second model earns its extra cost. The data is generated by a seeded script, so you can see exactly where word order matters. Short templated reviews have one clause ("the acting was very clumsy") or two joined by "but", where the clause after "but" decides the label. A third of the clauses are negated with "not", "not very" or "never". To mimic annotators who disagree, about 8% of the labels are flipped at random.
You need Python 3.12, PyTorch 2 (CPU build), scikit-learn 1.9 and pandas. Training runs on one CPU thread and takes under a minute per command. Results are seeded; the last digit can differ on other CPUs or library versions. The data pipeline follows from text and time series to tensors, and the training loop follows your first PyTorch training loop.
sentiment-lab/
├── data.py step 1: generate and split the reviews into data/*.csv
├── baseline.py step 2: TF-IDF + logistic regression
├── text.py step 3: vocabulary, padding and DataLoaders
├── model.py step 4: Embedding + LSTM classifier
├── train.py steps 5-6: training over three seeds
└── cost.py step 7: weights and time of both modelsmkdir sentiment-lab && cd sentiment-lab
python3.12 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install "torch==2.15.*" --index-url https://download.pytorch.org/whl/cpu
python -m pip install "scikit-learn==1.9.*" "pandas==3.*"02. Step 1: Generate the reviews
Each review gets a kind so that you can score models separately on single clauses, contrasts and negations. The script drops exact duplicates before splitting, so no test review appears word for word in training, and splits 2,400 / 800 / 800 at random. A random split is fine here because the reviews are independent; it would not be for a time series. The flip column records which labels were flipped. It is kept out of the CSV files, as real annotation noise would be, and only its share is printed.
import csv
import os
import random
ASPECTS = ["plot", "acting", "music", "dialogue", "ending", "pacing", "cast", "sound"]
POS = ["good", "great", "clever", "moving", "gripping", "charming", "superb"]
NEG = ["dull", "weak", "clumsy", "boring", "flat", "messy", "tedious"]
OPENERS = ["", "honestly", "i thought", "for me", "overall", "to be fair"]
HEDGES = ["", "at first", "in places", "mostly", "for a while", "on the whole"]
NOISE = 0.08 # share of flipped labels
def clause(rng, positive):
"""One clause and its polarity; a third of clauses are negated."""
aspect, negated = rng.choice(ASPECTS), rng.random() < 1 / 3
adj = rng.choice(POS if positive != negated else NEG)
middles = ["not", "not very", "never"] if negated else ["", "very", "really"]
middle = rng.choice(middles)
words = ["the", aspect, "was", middle, adj, rng.choice(HEDGES)]
return " ".join(w for w in words if w)
def review(rng):
label = rng.random() < 0.5 # True = positive
if rng.random() < 0.5:
kind, body = "single", clause(rng, label)
else: # the clause after "but" decides
kind = "contrast"
body = clause(rng, not label) + " but " + clause(rng, label)
text = " ".join(w for w in [rng.choice(OPENERS), body] if w)
negated = any(f" {w} " in f" {text} " for w in ("not", "never"))
flipped = rng.random() < NOISE # annotators do not always agree
return text, int(label != flipped), kind + ("+neg" if negated else ""), flipped
def make_splits(n=4000, seed=0):
rng, seen, rows = random.Random(seed), set(), []
while len(rows) < n:
text, label, kind, flipped = review(rng)
if text not in seen: # no exact duplicates across splits
seen.add(text)
rows.append({"text": text, "label": label, "kind": kind, "flip": flipped})
return {"train": rows[:2400], "val": rows[2400:3200], "test": rows[3200:]}
if __name__ == "__main__":
os.makedirs("data", exist_ok=True)
for name, rows in make_splits().items():
with open(f"data/{name}.csv", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["text", "label", "kind"],
extrasaction="ignore") # "flip" stays secret
writer.writeheader()
writer.writerows(rows)
pos = sum(r["label"] for r in rows) / len(rows)
flip = sum(r["flip"] for r in rows) / len(rows)
print(f"{name:5s} {len(rows)} reviews, {pos:.1%} positive, {flip:.1%} flipped")
short = [r for r in make_splits()["train"] if len(r["text"]) <= 70]
for r in short[:4]: # a few examples that fit a line
print(f'{r["label"]} {r["kind"]:13s} {r["text"]}')python data.pytrain 2400 reviews, 50.2% positive, 7.8% flipped
val 800 reviews, 49.0% positive, 9.6% flipped
test 800 reviews, 50.5% positive, 7.5% flipped
1 single honestly the ending was really gripping for a while
0 single+neg the dialogue was never great mostly
1 single+neg honestly the cast was not very weak at first
0 single i thought the pacing was weak on the wholeThe classes are balanced, and 7.5% of the test labels are flipped. No model can predict a coin flip, so about 92.5% is the best test accuracy anyone can expect on this data, and 90.4% on validation. Keep those ceilings in mind when you read the scores.
03. Step 2: The bag-of-words baseline
TF-IDF turns a text into a long vector with one entry per word or n-gram (a run of n consecutive words): how often it occurs in the text, weighted down if it occurs in many texts. Logistic regression then learns one weight per entry. With unigrams, "good but dull" and "dull but good" are the same vector; bigrams and trigrams keep a little local order. The script tries all three and chooses the regularisation strength C on the validation set; the test set is scored once per setting, after that choice.
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
train, val, test = (pd.read_csv(f"data/{s}.csv") for s in ("train", "val", "test"))
def fit(ngrams, C):
model = make_pipeline(TfidfVectorizer(ngram_range=ngrams),
LogisticRegression(C=C, max_iter=2000))
return model.fit(train.text, train.label)
for ngrams in [(1, 1), (1, 2), (1, 3)]:
# choose C on the validation set; the test set is used once, at the end
scores = {C: fit(ngrams, C).score(val.text, val.label) for C in (0.1, 1, 10, 100)}
best_C = max(scores, key=scores.get)
model = fit(ngrams, best_C)
hit = model.predict(test.text) == test.label
by_kind = hit.groupby(test.kind).mean()
print(f"ngrams {ngrams}: best C {best_C:<5} val {scores[best_C]:.3f}"
f" test {hit.mean():.3f} n_features {len(model[0].vocabulary_)}")
print(" by kind:", " ".join(f"{k} {v:.3f}" for k, v in by_kind.items()))python baseline.pyngrams (1, 1): best C 1 val 0.557 test 0.539 n_features 45
by kind: contrast 0.508 contrast+neg 0.484 single 0.846 single+neg 0.108
ngrams (1, 2): best C 10 val 0.641 test 0.686 n_features 239
by kind: contrast 0.560 contrast+neg 0.516 single 0.893 single+neg 0.748
ngrams (1, 3): best C 100 val 0.735 test 0.725 n_features 1020
by kind: contrast 0.586 contrast+neg 0.530 single 0.893 single+neg 0.914The breakdown by kind tells the story. On plain single clauses the three settings score 0.85 to 0.89. With unigrams, negated single clauses score 0.108: the model votes for each adjective's usual polarity, and negation reverses it. Bigrams catch "not good" but not "not very good"; trigrams catch both and reach 0.914. Contrasts stay between 0.48 and 0.59 whatever the n-gram range, because swapping the two clauses leaves almost the same set of n-grams, and the adjective that decides the label can sit five words after "but". Overall the best baseline, trigrams, scores 0.725 on test.
04. Step 3: Vocabulary, padding and DataLoaders
The recurrent model needs ids, not counts. text.py builds the vocabulary from the training texts only, with <pad> = 0 and <unk> = 1, and a collate function turns a list of examples into a right-padded id tensor, the true lengths and float labels. Passing collate_fn to the DataLoader is how PyTorch batches examples of different lengths. Only the training loader shuffles, with a seeded generator.
from collections import Counter
import pandas as pd
import torch
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import DataLoader
PAD, UNK = 0, 1
def build_vocab(texts, min_freq=2):
counts = Counter(w for t in texts for w in t.split())
words = sorted(w for w, c in counts.items() if c >= min_freq)
return {"<pad>": PAD, "<unk>": UNK} | {w: i for i, w in enumerate(words, start=2)}
def encode(text, vocab):
return torch.tensor([vocab.get(w, UNK) for w in text.split()])
def collate(batch):
ids, labels = zip(*batch)
lengths = torch.tensor([len(x) for x in ids])
return pad_sequence(ids, batch_first=True, padding_value=PAD), lengths, \
torch.tensor(labels, dtype=torch.float32)
def loaders(batch_size=64, seed=0):
train, val, test = (pd.read_csv(f"data/{s}.csv") for s in ("train", "val", "test"))
vocab = build_vocab(train.text) # training texts only
def rows(df):
return [(encode(t, vocab), y) for t, y in zip(df.text, df.label)]
gen = torch.Generator().manual_seed(seed)
return (vocab,
DataLoader(rows(train), batch_size, shuffle=True, collate_fn=collate,
generator=gen),
DataLoader(rows(val), 256, collate_fn=collate),
DataLoader(rows(test), 256, collate_fn=collate), test.kind)
if __name__ == "__main__":
vocab, train, val, _, _ = loaders()
ids = torch.cat([x for x, _ in val.dataset])
print("vocabulary size:", len(vocab), " unknown share in val:",
f"{(ids == UNK).float().mean().item():.4f}")
x, lengths, y = next(iter(train))
print("batch ids:", tuple(x.shape), " first lengths:", lengths[:6].tolist())
print("first labels:", y[:6].tolist())
print("pads in this batch:", f"{(x == PAD).float().mean().item():.1%}")python text.pyvocabulary size: 49 unknown share in val: 0.0000
batch ids: (64, 19) first lengths: [14, 9, 10, 13, 6, 9]
first labels: [1.0, 1.0, 0.0, 0.0, 0.0, 0.0]
pads in this batch: 38.0%There are 49 ids, and no validation word is unknown because the templates use a closed set of words; real reviews would show a few per cent. In this batch, 38% of the positions are padding: the longest review sets the width at 19, and a 6-word review carries 13 pads.
05. Step 4: The Embedding + LSTM classifier
The model has three layers. nn.Embedding turns each id into a 16-number vector; padding_idx=0 keeps the pad vector at zero. An LSTM with 32 hidden units reads the vectors in order. The batch is packed with the true lengths, so h_n[-1] is each review's state after its own last word, and a linear layer turns that state into one logit, a raw score where positive means "positive review". The pack=False branch reads output[:, -1] from the unpacked batch instead; step 6 uses it to measure what that shortcut costs.
import torch
from torch import nn
from torch.nn.utils.rnn import pack_padded_sequence
class LSTMClassifier(nn.Module):
def __init__(self, vocab_size, emb_dim=16, hidden=32, pack=True):
super().__init__()
self.pack = pack
self.emb = nn.Embedding(vocab_size, emb_dim, padding_idx=0)
self.lstm = nn.LSTM(emb_dim, hidden, batch_first=True)
self.head = nn.Linear(hidden, 1) # one logit: positive vs negative
def forward(self, ids, lengths):
if not self.pack: # the bug: read the last slot
output, _ = self.lstm(self.emb(ids))
return self.head(output[:, -1]).squeeze(1)
packed = pack_padded_sequence(self.emb(ids), lengths, batch_first=True,
enforce_sorted=False)
_, (h_n, _) = self.lstm(packed) # h_n: (1, batch, hidden)
return self.head(h_n[-1]).squeeze(1) # state at each true last token
if __name__ == "__main__":
from text import loaders
torch.manual_seed(0)
vocab, train, _, _, _ = loaders()
model = LSTMClassifier(len(vocab))
x, lengths, y = next(iter(train))
print(model)
print("parameters:", sum(p.numel() for p in model.parameters()))
print("logits:", tuple(model(x, lengths).shape))python model.pyLSTMClassifier(
(emb): Embedding(49, 16, padding_idx=0)
(lstm): LSTM(16, 32, batch_first=True)
(head): Linear(in_features=32, out_features=1, bias=True)
)
parameters: 7217
logits: (64,)The 7,217 weights are 49 × 16 for the embedding, 4 × (16 × 32 + 32 × 32 + 2 × 32) = 6,400 for the four LSTM gates, and 33 for the head. The output has one logit per review, which matches the float labels for BCEWithLogitsLoss.
06. Step 5: Train over three seeds
train.py trains for six epochs with AdamW, clips the gradient norm at 1.0, keeps the epoch with the best validation accuracy, and scores that model on the test set. It repeats the whole run for seeds 0, 1 and 2, which change the initial weights and the batch order but not the data. One run can be lucky or unlucky; three show how much of a result is noise.
import copy
import sys
import torch
from torch import nn
from model import LSTMClassifier
from text import loaders
@torch.no_grad()
def predict(model, loader):
model.eval()
return torch.cat([(model(x, n) > 0).float() == y for x, n, y in loader])
def run(seed, epochs=6, pack=True):
torch.manual_seed(seed)
vocab, train, val, test, kinds = loaders(seed=seed)
model = LSTMClassifier(len(vocab), pack=pack)
opt = torch.optim.AdamW(model.parameters(), lr=3e-3)
loss_fn = nn.BCEWithLogitsLoss()
best_acc = -1.0
for epoch in range(1, epochs + 1):
model.train()
for x, lengths, y in train:
loss = loss_fn(model(x, lengths), y)
opt.zero_grad()
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
val_acc = predict(model, val).float().mean().item()
if val_acc > best_acc: # keep the best epoch on validation
best_acc, best_epoch = val_acc, epoch
best_state = copy.deepcopy(model.state_dict())
model.load_state_dict(best_state)
hit = predict(model, test).numpy()
by_kind = {k: hit[(kinds == k).to_numpy()].mean() for k in sorted(kinds.unique())}
return best_epoch, best_acc, hit.mean(), by_kind
if __name__ == "__main__":
torch.set_num_threads(1) # small model: one thread is enough
pack = "--no-pack" not in sys.argv # --no-pack: read the last slot
accs = []
for seed in (0, 1, 2):
epoch, val_acc, test_acc, by_kind = run(seed, pack=pack)
accs.append(test_acc)
print(f"seed {seed}: best epoch {epoch} val {val_acc:.3f}"
f" test {test_acc:.3f}")
print(" by kind:", " ".join(f"{k} {v:.3f}" for k, v in by_kind.items()))
accs = torch.tensor(accs)
print(f"test accuracy over 3 seeds: mean {accs.mean():.3f},"
f" min {accs.min():.3f}, max {accs.max():.3f}")python train.pyseed 0: best epoch 5 val 0.904 test 0.917
by kind: contrast 0.890 contrast+neg 0.917 single 0.925 single+neg 0.942
seed 1: best epoch 5 val 0.904 test 0.925
by kind: contrast 0.895 contrast+neg 0.926 single 0.929 single+neg 0.957
seed 2: best epoch 5 val 0.905 test 0.922
by kind: contrast 0.895 contrast+neg 0.926 single 0.925 single+neg 0.950
test accuracy over 3 seeds: mean 0.922, min 0.917, max 0.925All three seeds land between 0.917 and 0.925 on test, at the noise ceiling, and contrasts now score about 0.89 to 0.93 instead of about 0.55. The LSTM has learned the two rules that the n-grams could not express: a negation reverses the next adjective even across "very", and the clause after "but" wins. Validation accuracy stops at 0.904 or 0.905 for every seed, which is the validation ceiling from step 1.
07. Step 6: What ignoring the padding costs
Now run the same training with the shortcut from step 4: no packing, and the classifier reads the state at the last slot of the padded batch. For every review shorter than the longest one in its batch, that state has passed through pad steps after the last real word.
python train.py --no-packseed 0: best epoch 6 val 0.864 test 0.874
by kind: contrast 0.895 contrast+neg 0.903 single 0.929 single+neg 0.698
seed 1: best epoch 6 val 0.892 test 0.912
by kind: contrast 0.895 contrast+neg 0.922 single 0.929 single+neg 0.892
seed 2: best epoch 6 val 0.868 test 0.875
by kind: contrast 0.895 contrast+neg 0.866 single 0.834 single+neg 0.935
test accuracy over 3 seeds: mean 0.887, min 0.874, max 0.912The mean drops from 0.922 to 0.887, and the spread across seeds widens from 0.008 to 0.038. The damage is uneven: for seed 0, short negated reviews fall to 0.698, because they carry the most pads. An LSTM can partly learn to hold its state through zero inputs, which is why some seeds recover, but you would be relying on luck. Packing or gathering at the true length costs nothing extra to run.
08. Step 7: Weigh the gain against the cost
cost.py fits the best baseline and trains one LSTM, then times both on the test set. Times depend on the machine and its load, so the output below is illustrative.
import time
import pandas as pd
import torch
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from model import LSTMClassifier
from text import loaders
from train import predict, run
torch.set_num_threads(1)
train, test = pd.read_csv("data/train.csv"), pd.read_csv("data/test.csv")
t0 = time.perf_counter()
lr = make_pipeline(TfidfVectorizer(ngram_range=(1, 3)),
LogisticRegression(C=100, max_iter=2000))
lr.fit(train.text, train.label)
t1 = time.perf_counter()
lr.predict(test.text)
t2 = time.perf_counter()
run(0) # train once: 6 epochs, as in train.py
t3 = time.perf_counter()
vocab, _, _, test_loader, _ = loaders()
model = LSTMClassifier(len(vocab)) # timing only: the weights do not matter
t4 = time.perf_counter()
predict(model, test_loader)
t5 = time.perf_counter()
n_lr = lr[1].coef_.size + 1
n_lstm = sum(p.numel() for p in model.parameters())
for name, n, fit_s, pred_s in [("TF-IDF + LR", n_lr, t1 - t0, t2 - t1),
("LSTM", n_lstm, t3 - t2, t5 - t4)]:
print(f"{name:12s} {n:5d} weights fit {fit_s:6.2f} s predict 800 {pred_s:.3f} s")python cost.pyTF-IDF + LR 1021 weights fit 0.28 s predict 800 0.033 s
LSTM 7217 weights fit 12.03 s predict 800 0.044 sOn our machine, the LSTM took about 40 times longer to train, and predicting 800 reviews took a few hundredths of a second with either model. In exchange it gained about 20 points of accuracy over the best baseline, and the gain held for all three seeds; that easily pays for itself. Be honest about why: this dataset was built so that half the reviews need word order. On real sentiment data, a well-tuned TF-IDF baseline often comes within a point or two of a recurrent model, and then the answer can reverse, especially if the gap is no larger than the spread across seeds. The method is what carries over: the same split, a baseline tuned as carefully as the model, several seeds, a per-kind breakdown, and the cost written next to the gain.
09. Check your understanding
10. Apply it
The practice project asks for exactly this comparison on a task of your choice. Take it further with these files.
- Change
NOISEto 0 and to 0.2, rerun steps 1, 2 and 5, and explain how the ceiling moves both models. - Replace the contrast template with a third single clause, so word order stops mattering, and see whether the LSTM still beats trigrams by more than the spread across seeds.
- Write half a page for a reviewer: the accuracy of both models with their range over seeds, the training and prediction cost, and your recommendation.
11. Review prompt
Without looking back, explain what TF-IDF with n-grams can and cannot represent about word order; describe the three layers of the classifier and the shape that comes out of each; say why the vocabulary is built on training texts only and what collate returns; explain what packing changes and what happened without it; and list what you need before claiming that a sequence model beats a baseline, including the cost.
References
- PyTorch docs: torch.nn.LSTM
- PyTorch docs: torch.nn.utils.rnn.pack_padded_sequence
- scikit-learn User Guide: Text feature extraction (tf-idf)
- Baselines and Bigrams: Simple, Good Sentiment and Topic Classification (Wang and Manning)
- Dive into Deep Learning: Sentiment Analysis Using Recurrent Neural Networks
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.