Text Classification: From CNNs to Transformers
What You'll Learn
- 1Compute TextCNN feature map sizes and parameter counts from filter widths
- 2Explain hierarchical pooling for long documents and its linear cost
- 3Apply class weighting and F1 to an imbalanced label set
- 4Compare CNN, recurrent, and transformer classifiers on accuracy and latency
Classification turns a variable length document into one of a fixed label set, and the architecture choice is a trade between how much context the label needs and how cheap the forward pass must be. This lesson derives the TextCNN pooling arithmetic, the hierarchical attention scheme for long documents, the class weighting and F1 math for imbalanced data, and the point where a transformer starts to be worth its latency.
TextCNN and Static Pooling
Kim (2014) slid a set of convolutional filters over word embeddings and kept only the strongest activation per filter:
Filters of height read consecutive embeddings, so a window of 3 captures short phrases while a window of 5 captures clause fragments. Each filter produces a vector of length , and the max over that vector is a single feature:
Concatenating the pooled vectors gives a fixed width representation regardless of document length, which is why the model needs no padding decisions at the classifier and runs one convolution per window rather than one recurrence per token.
Hierarchical Models for Long Documents
Full self-attention over a 5,000 token document costs quadratic in length, so hierarchical models encode sentences separately and then pool over sentences:
where is the sentence vector from a CNN or recurrent encoder and is the importance of sentence for the document label:
The cost drops from quadratic in the token count to linear in sentences, and the weights give an inspectable explanation: a sentiment model can show which sentences moved the decision. Yang and colleagues (2016) used exactly this two level attention for document classification.
| Model | Representation | Parameters | Cost per document | Typical use |
|---|---|---|---|---|
| TextCNN | max over convolutions | about 3 million with embeddings | 1 pass, sub-millisecond | short text, spam, intent |
| Hierarchical attention | sentence CNN plus doc attention | about 4 million | linear in sentences | reviews, tickets, reports |
| BERT-base classifier | first token state plus head | 110 million plus head | 12 layers over the sequence | benchmarks, moderate latency |
| RoBERTa-large classifier | first token state plus head | 355 million | 24 layers, high latency | highest accuracy offline |
Class Imbalance and Evaluation
Real label sets rarely balance, so the loss is reweighted by the inverse frequency of each class:
with the dataset size, the number of classes, and the count for class , which multiplies the gradient of rare examples so the majority class cannot dominate. Accuracy alone hides the failure, and F1 combines precision and recall :
Worked Examples
Worked Code
import torch
import torch.nn as nn
import torch.nn.functional as F
class TextCNN(nn.Module):
def __init__(self, vocab, embed=128, num_classes=6, filters=100,
widths=(3, 4, 5), dropout=0.5):
super().__init__()
self.embed = nn.Embedding(vocab, embed, padding_idx=0)
self.convs = nn.ModuleList(
[nn.Conv1d(embed, filters, w) for w in widths])
self.dropout = nn.Dropout(dropout)
self.fc = nn.Linear(filters * len(widths), num_classes)
def forward(self, tokens):
x = self.embed(tokens).transpose(1, 2)
pooled = [F.relu(conv(x)).max(dim=2).values for conv in self.convs]
return self.fc(self.dropout(torch.cat(pooled, dim=1)))
model = TextCNN(vocab=20000, embed=128, num_classes=6)
batch = torch.randint(1, 20000, (8, 50))
print("logits:", model(batch).shape)
print("params:", sum(p.numel() for p in model.parameters()))
import numpy as np
import torch
from transformers import AutoModelForSequenceClassification, AutoTokenizer
name = "distilbert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForSequenceClassification.from_pretrained(name, num_labels=2)
model.eval()
texts = ["the plot was predictable", "a sharp and funny script"]
inputs = tokenizer(texts, padding=True, truncation=True, max_length=128,
return_tensors="pt")
with torch.no_grad():
logits = model(**inputs).logits
preds = logits.argmax(dim=-1).numpy()
def macro_f1(y_true, y_pred, num_classes=2):
f1s = []
for c in range(num_classes):
tp = int(((y_true == c) & (y_pred == c)).sum())
fp = int(((y_true != c) & (y_pred == c)).sum())
fn = int(((y_true == c) & (y_pred != c)).sum())
precision = tp / (tp + fp) if tp + fp else 0.0
recall = tp / (tp + fn) if tp + fn else 0.0
f1s.append(2 * precision * recall / (precision + recall)
if precision + recall else 0.0)
return float(np.mean(f1s))
y_true = np.array([0, 1])
print("preds:", preds, "macro F1:", macro_f1(y_true, preds))
Real-World Applications
- Intent detection: TextCNN still serves as the default in production intent systems because a single convolution pass answers in well under a millisecond on a CPU.
- Ticket routing: hierarchical attention over ticket bodies routes by topic and exposes the sentences that drove the routing decision.
- Content moderation: transformer classifiers handle policy nuance, while a cheap CNN prefilter keeps the expensive model off easy cases.
đĄEscalate only the uncertain cases
Common Mistakes
Truncating documents before checking where the answer is
Fix: Head plus tail truncation keeps both the opening claim and the final verdict inside the window.
Choosing accuracy on a 95 to 5 split
Fix: Report macro F1 and the confusion matrix, since the majority class already reaches 95 percent.
Pooling over padded positions
Fix: Zero the padding before max pooling or set padding_idx and mask the convolution output.
Best Practices
- Freeze embeddings for the first epoch so random head weights do not corrupt them
- Tune filter widths against your label granularity, since 3 to 5 suits phrase level labels
- Track macro F1, per class recall, and latency together when comparing architectures
Key Takeaways
- A filter of width h over T tokens yields T minus h plus 1 features, pooled to one scalar by max
- Hierarchical attention reduces document cost from quadratic in tokens to linear in sentences
- Inverse frequency weighting multiplies rare class gradients, with N divided by K times n_c
- F1 of 0.90 in the worked split beats an uninformative 95 percent accuracy
Frequently Asked Questions
Why does max pooling work for classification?
The label depends on whether a pattern appears, not where it appears, so the maximum activation of a filter is a presence indicator. This also removes the need for fixed positions, which lets one model handle short and long inputs.
Should you fine-tune a transformer or train a CNN?
If the label set is small and the text is short, TextCNN trains in minutes and serves cheaply. If labels depend on long range context, negation, or domain nuance, a fine-tuned transformer wins, and the hybrid prefilter approach gets most of both benefits.
How do you handle a label that has very few examples?
Reweight the loss with , oversample the minority split, or use a threshold tuned on validation rather than the argmax, and always report macro F1 so the minority class stays visible.
Interview Questions
Q1: How many features does TextCNN produce for a 50 token input with widths 3, 4, 5?
100 filters over 48, 47, and 46 positions give 14,100 pooled features, and a six class head adds 84,600 weights.
Q2: Why use hierarchical attention instead of one flat transformer?
Attention over all tokens costs quadratic memory, while sentence level encoding with a second pooling stage stays linear in sentences and still exposes which sentences mattered.