Chapter 7: Text Classification
Master the core techniques for assigning labels to text, from classical sentiment analysis and document classification to modern deep learning approaches including TextCNN and BERT fine-tuning. Learn multi-label strategies, evaluation metrics, and practical deployment considerations.
- Topics
- 6
- Demos
- 6
- Min read
- 52
Chapter Overview
Text classification is one of the most widely deployed NLP tasks in industry. Every spam filter, content moderation system, and customer feedback pipeline relies on a classifier that maps raw text to one or more categorical labels. The task appears simple --- read some text, pick a label --- but building classifiers that generalize across domains, handle class imbalance, and scale to millions of documents requires deep understanding of both traditional and neural methods.
This chapter covers the full spectrum of text classification. We begin with sentiment analysis, the canonical classification task, then move to general document classification and multi-label settings where each document can belong to multiple categories simultaneously. On the modeling side, we explore CNNs for text (the TextCNN architecture that applies convolutional filters over word embeddings), fine-tuning pretrained transformers like BERT, and the evaluation metrics that matter for real-world deployment.
The progression mirrors how the field evolved: from hand-crafted features and linear classifiers, through task-specific neural architectures, to the current paradigm of fine-tuning large pretrained models. Understanding each stage helps you choose the right approach for your data size, latency requirements, and accuracy needs.
Chapter Roadmap
Click any topic to jump in
Sentiment Analysis
Polarity classification, aspect-based sentiment, and fine-grained rating prediction.
Document-level and multi-label extensions of classification
Document Classification
Naive Bayes, TF-IDF features, hierarchical categories, and handling class imbalance.
Multi-Label Classification
Binary relevance, classifier chains, and threshold tuning for multi-label outputs.
CNNs for Text
1D convolution over embeddings, max-pooling, and the TextCNN architecture.
Pretrained model fine-tuning and evaluation methodology
Fine-Tuning Pretrained Models
Classification heads, learning rate strategies, and parameter-efficient fine-tuning.
Classification Evaluation
Precision, recall, F1, macro/micro averaging, confusion matrices, and ROC-AUC.
Topics
6 topics in this chapter
A product team receives 40,000 new reviews a week and has one question: are customers happier than last month, and about what? Nobody can read them all, and a star rating alone hides the reason behind it. Sentiment analysis turns that free text into labels a dashboard can count. It opens this chapter on classification, where the representations and the Transformer encoders of the previous chapters are finally aimed at a concrete prediction target.
The task comes in three granularities. Polarity classification assigns positive, negative, or neutral to a whole document. Fine-grained sentiment predicts a 5-point scale, where adjacent ratings are hard to separate and the ordering of labels matters. Aspect-based sentiment analysis (ABSA) attaches a polarity to each entity or attribute, because "great camera, awful battery" is neither simply positive nor negative.
The concepts below follow that arc: softmax polarity scores, per-aspect extraction, and ordinal 5-class prediction. Keep the failure modes in mind throughout: negation, sarcasm, and domain shift, where "unpredictable" praises a thriller but condemns a car's steering.
Definition
Sentiment analysis is the task of predicting the opinion expressed in a text, either as a polarity label (positive, negative, neutral), as an ordinal rating such as 1 to 5 stars, or as a set of (aspect, polarity) pairs. It is usually framed as supervised classification over a learned representation of the text.
In this topic
- 1Polarity Classification
- 2Aspect-Based Sentiment Analysis
- 3Fine-Grained Sentiment Scales
Polarity Classification
Polarity classification assigns each document a single sentiment label. The classifier outputs a probability distribution over classes using softmax, and the predicted label is the class with highest probability. Training uses cross-entropy loss: . Common architectures range from logistic regression on TF-IDF features to fine-tuned BERT models. The choice depends on data volume and latency requirements --- linear models on n-gram features remain competitive for large-scale, low-latency applications.
The softmax turns unbounded logits into a probability distribution. The boundary between classes and lies where , which for a linear model is the hyperplane . Cross-entropy is 0.21 when the true class gets probability 0.81, 2.3 at 0.1, and 4.6 at 0.01, so it grows without bound as a confident prediction turns out wrong. Log loss is a proper scoring rule, but large networks still end up overconfident in practice, so calibration should be measured rather than assumed.
A logistic regression model outputs raw scores [2.1, -0.5, 0.3] for [positive, negative, neutral]. Compute the predicted class and its probability.
Aspect-Based Sentiment Analysis
ABSA goes beyond document-level polarity by identifying what the sentiment is about. A single review like 'The camera is amazing but battery life is terrible' contains two aspects (camera, battery) with opposite sentiments. ABSA involves two subtasks: aspect extraction (identifying the entities or attributes mentioned) and aspect sentiment classification (determining sentiment toward each aspect). Joint models tackle both subtasks simultaneously using sequence labeling (BIO tags for aspects) combined with per-aspect sentiment heads.
ABSA decomposes the document-level sentiment into aspect-specific sentiments for each aspect . The joint task of aspect extraction and sentiment classification can be modeled as a sequence labeling problem with compound tags (e.g., B-POS, I-NEG) or as a two-stage pipeline. The attention mechanism naturally supports ABSA: aspect-specific attention weights focus on the words relevant to aspect , enabling the same sentence to yield different sentiment features for different aspects.
Given the review 'The screen is beautiful, the speakers are decent, but the keyboard feels cheap', identify the aspects and their sentiments.
Fine-Grained Sentiment Scales
Fine-grained sentiment extends polarity from 3 classes to 5 (or more), typically mapping to star ratings. The Stanford Sentiment Treebank (SST-5) is the canonical benchmark, with labels from 'very negative' (1) to 'very positive' (5). The key challenge is distinguishing adjacent classes --- what separates a 3-star from a 4-star review? Ordinal regression approaches that respect the ordering (3 is closer to 4 than to 1) often outperform standard multiclass classification. Label smoothing and soft targets also help by allowing the model to express uncertainty between adjacent ratings.
Ordinal regression respects the ordering by modeling cumulative probabilities for thresholds . This ensures monotonicity: by construction. Standard multiclass softmax treats ratings 1 and 5 as equally "different" from rating 3, but ordinal regression knows that misclassifying a 4-star review as 3-star (off by 1) is less severe than misclassifying it as 1-star (off by 3). The expected rating provides a continuous score even from a discrete classifier.
A model predicts probabilities [0.05, 0.10, 0.25, 0.40, 0.20] for ratings [1, 2, 3, 4, 5]. What is the predicted rating? What is the expected rating as a weighted average?
Theory Exercise
Problem:
Negation handling is a persistent challenge in sentiment analysis. Explain how the phrase 'not bad' should be interpreted, why simple negation flipping (inverting sentiment of the next word) fails, and describe a more robust approach.
Hints:
- Consider that 'not bad' doesn't mean 'good' --- it's milder
Coding Exercise
Problem:
Implement a simple lexicon-based sentiment analyzer that handles negation. Given a sentiment lexicon (word -> score), compute the overall sentiment of a sentence, flipping the sign of words that follow a negation word.
Hints:
- Define a set of negation words: {'not', 'no', 'never', "don't", "doesn't", "isn't", "wasn't"}
Related Problems on PixelBank
A support desk receives tickets about billing, outages, and password resets; a newsroom files thousands of wire stories into sections; a mail server must decide spam or not before anyone reads a message. Each case needs one category per document, assigned at volume and consistently. Sentiment analysis, the previous topic, is one instance of this problem with opinion labels. Document classification is the general form, covering topic, genre, language, spam, and moderation labels.
The pipeline has three parts. Feature engineering turns text into numbers, from bag-of-words and TF-IDF to pretrained embeddings. A model maps features to classes, and linear models such as Naive Bayes or logistic regression on n-grams remain hard to beat when data is plentiful and latency matters. Then practical problems take over: rare classes, noisy labels, and categories arranged in a taxonomy such as Science, Biology, Genetics.
The concepts below take these in order: Naive Bayes, TF-IDF weighting, hierarchical label spaces and their error propagation, and the class-imbalance fixes that keep a 98 percent accurate model from being useless.
Definition
Document classification is the task of assigning each document one label from a fixed set of categories by learning a function from a text representation, such as bag of words, TF-IDF, or a pretrained encoding, to a class. Common variants include hierarchical labels drawn from a taxonomy and heavily imbalanced label distributions, as in spam or abuse detection.
In this topic
- 1Naive Bayes for Text
- 2TF-IDF Feature Engineering
- 3Hierarchical Classification
- 4Handling Class Imbalance
Naive Bayes for Text
Naive Bayes applies Bayes' theorem with a strong independence assumption: each word is conditionally independent given the class. Despite this unrealistic assumption, Naive Bayes works remarkably well for text classification. The multinomial variant models word counts: where is Laplace smoothing. The class prior is estimated from training label frequencies. Classification is done in log space to avoid numerical underflow: .
The log-space computation converts products of small probabilities into sums of log-probabilities, avoiding numerical underflow. The naive independence assumption is clearly wrong (words are correlated), yet the classifier works because the decision boundary only requires the correct ranking of classes, not calibrated probabilities. Laplace smoothing prevents zero probabilities by adding pseudo-counts, effectively applying a Dirichlet prior with concentration .
Given , , , , , . Classify: "goal election".
TF-IDF Feature Engineering
TF-IDF weighs each term by its importance to a specific document relative to the corpus. Term frequency measures how often term appears in document . Inverse document frequency downweights terms that appear in many documents (like 'the' and 'is'). The result is that rare, distinctive words get high weights while common words get low weights. Sublinear TF () prevents long documents from dominating. L2 normalization of the resulting vectors makes cosine similarity equivalent to dot product, enabling efficient nearest-neighbor classification.
TF-IDF weights balance two signals: how important a term is to a specific document (TF) and how distinctive it is across the corpus (IDF). A word appearing 10 times in a document but in every document (like "the") gets high TF but low IDF, resulting in low weight. A word appearing 3 times but in only 5 of 10,000 documents gets moderate TF but very high IDF (), making it highly discriminative. The IDF term is essentially the Shannon information content of observing a word: .
In a corpus of 10,000 documents, the word 'algorithm' appears in 50 documents. In document , 'algorithm' appears 3 times out of 200 total words. Compute TF-IDF with sublinear TF.
Hierarchical Classification
When categories form a taxonomy (e.g., News > Sports > Football), flat classification ignores structural constraints. Hierarchical approaches enforce consistency: if a document is labeled 'Football', it must also be labeled 'Sports' and 'News'. Three main strategies exist: (1) Flat --- ignore hierarchy, train one classifier over leaf categories; (2) Local per-node --- train a binary classifier at each node, classify top-down; (3) Global --- use the full hierarchy as a structured output space. The local per-node approach is most common, cascading predictions from root to leaves. A key advantage is that errors at higher levels prevent wasted computation on irrelevant subtrees.
In hierarchical classification, the label space forms a tree or DAG where each node is a category. A local approach trains one classifier per internal node to distinguish among its children. A global approach flattens the hierarchy but constrains predictions to be consistent: if the model predicts "Genetics", the parent "Biology" and grandparent "Science" must also be predicted. The constraint can be enforced via masking: at inference time, only labels whose parents are already predicted (or above a threshold) are considered. The evaluation metric must account for partial credit — predicting "Biology" when the gold label is "Genetics" is partially correct.
A hierarchical classifier has accuracy 0.95 at each level. For a 3-level hierarchy (root -> mid -> leaf), what is the probability of correct leaf classification?
Handling Class Imbalance
Real-world classification datasets are often heavily imbalanced --- spam might be 1% of emails, toxic content 0.1% of posts. Standard classifiers trained on imbalanced data learn to predict the majority class. Mitigation strategies include: oversampling the minority class (SMOTE generates synthetic examples), undersampling the majority class, class-weighted loss ( for class with samples), and focal loss () which downweights easy examples. Evaluation must also adapt: accuracy is misleading when classes are imbalanced; use precision, recall, F1, and AUROC instead.
When class frequencies differ by 10x or more, the majority class dominates the cross-entropy gradient because it contributes more terms to the loss sum. Cost-sensitive learning assigns class weights inversely proportional to frequency: where is total samples, is number of classes, and is the count of class . This makes each class contribute equally to the total loss in expectation. Focal loss takes a different approach: it down-weights easy (well-classified) examples regardless of class, focusing the model on the hard examples that tend to be from rare classes.
A spam dataset has 980 legitimate and 20 spam emails. A model that always predicts 'legitimate' achieves what accuracy? What is its recall for the spam class?
Theory Exercise
Problem:
Compare Naive Bayes and logistic regression for document classification. Under what conditions does each perform better? Why does Naive Bayes often outperform logistic regression with very small training sets?
Hints:
- Think about the bias-variance tradeoff
Coding Exercise
Problem:
Implement a Multinomial Naive Bayes classifier from scratch. Train it on a small document classification dataset and evaluate its predictions.
Hints:
- Count word occurrences per class with Laplace smoothing
Related Problems on PixelBank
In standard multi-class classification, each document belongs to exactly one category. Multi-label classification relaxes this constraint: a news article might be tagged with both "Technology" and "Business", a movie might be labeled "Action", "Sci-Fi", and "Thriller" simultaneously, and a medical report might indicate multiple diagnoses.
The key difference from multi-class is that labels are not mutually exclusive. This changes the loss function (from softmax cross-entropy to binary cross-entropy per label), the output layer (independent sigmoids instead of shared softmax), and the evaluation metrics (subset accuracy, Hamming loss, micro/macro F1). It also opens up modeling strategies that exploit label correlations --- if a document is labeled "Machine Learning", it is more likely to also be labeled "Artificial Intelligence".
Three main approaches exist: binary relevance (train independent classifiers per label), classifier chains (chain classifiers so each one sees previous predictions as features), and joint models (use a single network with a multi-label output head). Modern transformer models handle multi-label classification naturally by replacing the softmax head with independent sigmoid outputs.
Definition
Multi-label classification assigns each instance a subset of possible labels rather than exactly one, so the target is a binary vector . It is usually trained with an independent sigmoid and binary cross-entropy per label, plus decision thresholds that convert the scores into the predicted label set.
In this topic
- 1Binary Relevance
- 2Classifier Chains
- 3Threshold Selection
Binary Relevance
Binary relevance (BR) decomposes multi-label classification into independent binary classification problems, one per label. Each classifier predicts whether label applies, using a sigmoid output and binary cross-entropy loss: . The total loss is the sum across all labels. BR is simple and parallelizable, but it completely ignores label correlations --- the prediction for 'Action' does not influence the prediction for 'Adventure', even though these labels frequently co-occur.
Binary relevance trains independent binary classifiers, one per label: . Each classifier uses binary cross-entropy and the total loss is . The independence assumption means the model cannot capture label correlations — if labels A and B always co-occur, each classifier must learn this pattern independently from the features rather than from the other classifier's output. Despite this limitation, binary relevance is simple, parallelizable, and works well when label correlations are weak.
A movie classifier has 4 labels: Action, Comedy, Drama, Thriller. Given sigmoid outputs [0.85, 0.12, 0.67, 0.78] and threshold 0.5, what labels are predicted?
Classifier Chains
Classifier chains (CC) address the label independence problem by ordering the labels and feeding previous predictions as features to subsequent classifiers. The first classifier predicts from features . The second predicts from . The -th classifier predicts from . This captures label correlations at the cost of error propagation --- mistakes in early classifiers cascade. Ensemble of chains (ECC) mitigates this by training multiple chains with random label orderings and averaging predictions.
A classifier chain orders labels as and trains each classifier to predict , conditioning on the true labels of all previous classifiers in the chain. This captures label dependencies: if is predicted, the classifier for can use this as a feature. The chain approximates the joint distribution via the chain rule. Order matters: placing highly predictive labels earlier in the chain gives downstream classifiers more useful conditioning information.
In a classifier chain with order [Action, Comedy, Thriller], the Action classifier predicts 1, Comedy predicts 0. How does this affect the Thriller classifier?
Threshold Selection
Multi-label classification requires choosing a threshold to convert continuous sigmoid outputs to binary predictions: if . The default is rarely optimal. Per-label thresholds can be tuned on validation data, maximizing each label's F1 independently. Global threshold optimization finds a single that maximizes a global metric (micro-F1 or macro-F1). Rank-based thresholds predict the top- labels where is estimated from the training distribution. The threshold choice has an outsized effect on the precision-recall tradeoff and should always be tuned rather than defaulted.
Unlike multiclass classification where the prediction is always , multi-label requires choosing a threshold : predict label if . The default is rarely optimal. Threshold tuning optimizes on a validation set to maximize F1 score: . Per-label thresholds further improve performance because different labels may have different calibration. A rare label might achieve best F1 at while a common label peaks at .
A model outputs scores [0.45, 0.52, 0.48, 0.38] for 4 labels. With threshold 0.5, only label 2 is predicted. If the true labels are {1, 2, 3}, what are precision and recall? What threshold gives better results?
Theory Exercise
Problem:
Explain the difference between subset accuracy, Hamming loss, and example-based F1 for multi-label classification. Why is subset accuracy often too strict as a metric?
Hints:
- Subset accuracy requires ALL labels to match exactly
Coding Exercise
Problem:
Implement binary relevance multi-label classification using logistic regression. Train independent classifiers for each label and evaluate using Hamming loss and example-based F1.
Hints:
- Train a separate sigmoid classifier for each label
Convolutional Neural Networks, originally designed for images, turned out to be remarkably effective for text classification. The key insight is that 1D convolutions over word embeddings act as n-gram detectors --- each filter learns to recognize a specific pattern of consecutive words, regardless of where it appears in the document.
The TextCNN architecture, introduced by Yoon Kim in 2014, is elegantly simple: embed the input words, apply multiple convolutional filters of different sizes (capturing unigrams, bigrams, trigrams, etc.), apply max-over-time pooling to extract the strongest signal from each filter, concatenate the pooled features, and classify with a fully connected layer. Despite its simplicity, TextCNN was competitive with much more complex recurrent models and remains a strong baseline.
The architecture's strength comes from max-over-time pooling, which makes the representation invariant to the position of the detected pattern. Whether a sentiment phrase appears at the beginning or end of a review, the pooling operation captures it. Combined with multiple filter sizes, TextCNN captures patterns at multiple granularities simultaneously.
Definition
A convolutional text classifier slides 1D filters spanning consecutive word embeddings over the input, so each filter acts as a learned n-gram detector. Max-over-time pooling keeps each filter's strongest response anywhere in the text, and the pooled features feed a softmax layer. TextCNN (Kim, 2014) is the canonical design.
In this topic
- 11D Convolution over Embeddings
- 2Max-Over-Time Pooling
- 3Multiple Filter Sizes
- 4TextCNN Architecture (Kim 2014)
1D Convolution over Embeddings
A 1D convolution slides a filter of height (the n-gram size) across the sequence of word embeddings. If the input is a sequence of words, each represented by a -dimensional embedding, the input matrix is . A filter computes a dot product with each contiguous window of words, producing a feature map . The activation function (typically ReLU) introduces nonlinearity. Each filter is essentially a learned n-gram detector that fires when it encounters a specific word pattern.
A 1D convolutional filter slides over consecutive -grams in the embedding matrix . At position , the output is where is a submatrix. This is a pattern detector: the filter learns to fire when a specific -gram pattern appears, regardless of where it appears in the sequence. Unlike RNNs that process sequentially, all positions are convolved in parallel, giving depth for pattern detection versus for an RNN to propagate information across the sequence.
An input sentence has 10 words, each with a 300-dim embedding. A filter of height 3 slides over this input. What is the shape of the resulting feature map?
Max-Over-Time Pooling
After convolution, each filter produces a feature map of variable length (depending on input length). Max-over-time pooling takes the maximum value from each feature map, producing exactly one scalar per filter. This operation captures the strongest activation of each pattern detector, regardless of where in the document the pattern occurred. It also makes the representation fixed-size (one value per filter), regardless of input length. This is critical for feeding into a fully connected classification layer. The pooling discards positional information but preserves the most important signal.
Max pooling extracts the strongest activation of each filter across the entire sequence. This makes the representation position-invariant: whether a bigram "not good" appears at position 3 or position 30, the same filter fires and the max pool captures it equally. The resulting feature is a single scalar per filter, creating a fixed-length representation regardless of input length. The gradient flows only through the argmax position, meaning the model learns from the single strongest match of each pattern, ignoring weaker matches elsewhere in the text.
A bigram filter detects the pattern 'very good'. Applied to 'The food was very good but the service was very bad', it produces feature map [0.1, 0.2, 0.1, 0.9, 0.3, 0.1, 0.2, 0.1, 0.2, 0.8]. What does max pooling return?
Multiple Filter Sizes
TextCNN uses filters of different heights (typically 3, 4, and 5) to capture patterns at multiple n-gram scales. Trigram filters detect 3-word phrases ('not at all'), 4-gram filters capture longer expressions ('could have been better'), and 5-gram filters detect even longer patterns. Each filter size has multiple filters (typically 100 each), so the model learns 100 different trigram patterns, 100 different 4-gram patterns, and so on. After max pooling, each filter contributes one scalar, giving a 300-dimensional feature vector (100 filters 3 sizes) that is fed to the classification layer.
Using filters of sizes captures different n-gram scales: trigrams, 4-grams, and 5-grams. Each filter size produces a feature map of different length (), but max pooling reduces each to a single value. With filters per size and 3 sizes, the final representation is a -dimensional vector. This multi-scale approach captures both local patterns ("very good") and slightly longer phrases ("not at all bad") simultaneously. The total parameter count is — much smaller than an LSTM's because CNN filters are small and shared across positions.
TextCNN uses 128 filters each of sizes [2, 3, 4, 5] on 300-dim embeddings. How many total parameters are in the convolutional layers (excluding bias)?
TextCNN Architecture (Kim 2014)
The complete TextCNN pipeline: (1) Embed each word using pretrained embeddings (Word2Vec or GloVe), optionally with a trainable copy for fine-tuning. (2) Apply convolutional filters of different sizes. (3) Max-pool each filter's output. (4) Concatenate all pooled features into a single vector. (5) Apply dropout for regularization. (6) Classify with a fully connected softmax layer. Kim (2014) showed that this simple architecture, with pretrained Word2Vec embeddings and minimal hyperparameter tuning, matched or exceeded more complex models on multiple benchmarks including SST-2, TREC, and MR datasets.
TextCNN composes embedding, parallel convolutions, max-over-time pooling, dropout, and a softmax layer, so sequence length matters only inside the convolutions. Kim (2014) compared four embedding setups. On the MR movie-review dataset, random embeddings scored 76.1 percent, frozen word2vec 81.0, fine-tuned word2vec 81.5, and a two-channel model with one frozen and one fine-tuned copy 81.1. Pretrained vectors gave the large jump, while the multichannel design did not consistently help. Kim's filters, 100 each of heights 3, 4, and 5 on 300-dimensional vectors, hold weights, and every window is convolved in parallel rather than in an RNN's sequential steps.
A TextCNN with 100 filters of sizes [3, 4, 5], dropout 0.5, and 5 output classes processes a 50-word review. Trace the tensor shapes through the network.
Theory Exercise
Problem:
TextCNN applies max-over-time pooling, which discards all positional information. Explain why this works for classification tasks but would fail for tasks like machine translation. What modification would preserve positional information?
Hints:
- Classification only needs to know IF a pattern exists, not WHERE
Coding Exercise
Problem:
Implement a simplified TextCNN forward pass using NumPy. Create convolutional filters of sizes 2 and 3, apply them to a sentence's word embeddings, perform max-over-time pooling, and classify.
Hints:
- A 1D convolution is a sliding dot product across the embedding matrix
Related Problems on PixelBank
A team with 2,000 labeled support tickets cannot train a TextCNN or an LSTM from scratch to high accuracy, because the model would have to learn English and the task from the same small set. The previous topic's convolutional classifier only partly escaped this by borrowing pretrained word vectors. Fine-tuning goes much further. Start from a language model such as BERT or RoBERTa that has already learned syntax, semantics, and a good deal of world knowledge from billions of words, add a small classification head, and train the whole network briefly on the labeled data.
The data efficiency is striking. ULMFiT (Howard and Ruder, 2018) matched the accuracy of training from scratch on 100 times more data using only 100 labeled examples, and BERT-style fine-tuning became the default for text classification soon after.
The risk is that aggressive updates overwrite what pretraining learned. The concepts below cover the head that reads the [CLS] vector, learning-rate schedules with layer-wise decay and warmup, catastrophic forgetting, and parameter-efficient methods such as LoRA that train under 1 percent of the weights.
Definition
Fine-tuning is transfer learning in which a pretrained language model's weights initialize a task model, a small task head, often one linear layer on the [CLS] vector, is added, and all or some parameters are trained on labeled data with a small learning rate. Parameter-efficient variants train only added low-rank or adapter weights.
In this topic
- 1Classification Head Architecture
- 2Learning Rate Strategies
- 3Catastrophic Forgetting
- 4Few-Shot and Parameter-Efficient Fine-Tuning
Classification Head Architecture
BERT and similar models produce a contextualized representation for each token. For classification, the [CLS] token's representation (a vector summarizing the entire input) is extracted and fed through a linear layer followed by softmax. The classification head is typically just one linear layer: where is the hidden dimension (768 for BERT-base) and is the number of classes. The entire model (pretrained backbone + classification head) is trained end-to-end with cross-entropy loss, though the learning rate for the backbone is usually much smaller than for the head.
The classification head maps the [CLS] token representation to class logits: where . The [CLS] representation aggregates information from the entire sequence via self-attention — it attends to all tokens and encodes a summary. For BERT-base () with 3 classes, the head adds only parameters on top of 110M pretrained parameters. This extreme parameter efficiency is why fine-tuning works: the pretrained model already has rich linguistic representations, and only a thin task-specific layer needs to be learned.
BERT-base has hidden size 768. For a 5-class sentiment task, how many parameters are in the classification head? How does this compare to the 110M parameters in the backbone?
Learning Rate Strategies
Fine-tuning with a single learning rate often fails: too high destroys pretrained features, too low fails to adapt. Discriminative fine-tuning uses different learning rates per layer, with lower layers (closer to input, encoding general features) getting smaller learning rates and upper layers (more task-specific) getting larger ones. Layer-wise decay multiplies the learning rate by for each layer down from the top. Warmup gradually increases the learning rate from 0 to the target over the first 5-10% of training steps, preventing large gradient updates to the pretrained weights early in training.
Discriminative fine-tuning uses different learning rates for different layers: lower layers get smaller rates (e.g., ) because their general linguistic features need minimal adjustment, while the classification head gets a larger rate (e.g., ) because it starts from random initialization. The common heuristic is for layer with decay factor . Warmup (linearly increasing from 0 to over the first 5--10% of steps) prevents large early updates from destroying pretrained features before the optimizer has a good gradient estimate.
BERT has 12 layers. With base learning rate and layer decay , what is the learning rate for layer 1 (bottom) vs. layer 12 (top)?
Catastrophic Forgetting
When fine-tuning aggressively, the model can 'forget' the general language knowledge encoded during pretraining, causing it to overfit to the small task-specific dataset. This manifests as excellent training accuracy but poor generalization, especially on out-of-distribution examples. Mitigation strategies include: (1) Low learning rates () with warmup. (2) Gradual unfreezing: freeze all layers initially, then unfreeze one layer at a time from top to bottom. (3) Early stopping: monitor validation loss and stop before overfitting. (4) Regularization: dropout in the classification head, weight decay on all parameters. (5) Mixout: randomly replaces fine-tuned weights with pretrained weights during training.
Catastrophic forgetting occurs when fine-tuning on a small task dataset overwrites the pretrained representations, degrading performance on the pretraining distribution and potentially reducing generalization. Mathematically, the fine-tuned parameters move far from the pretrained parameters in a direction that optimizes task loss but damages the general features. L2 regularization toward the pretrained weights keeps the model close. Elastic Weight Consolidation (EWC) goes further by weighting each parameter's penalty by its Fisher information — parameters that are important for the pretrained knowledge get stronger regularization.
A BERT model fine-tuned with learning rate (too high) achieves 99% train accuracy but only 62% test accuracy. The same model with learning rate achieves 94% train and 89% test accuracy. Explain the difference.
Few-Shot and Parameter-Efficient Fine-Tuning
When labeled data is extremely scarce (10-100 examples), full fine-tuning risks overfitting even with low learning rates. Parameter-efficient fine-tuning (PEFT) methods add or modify a small number of parameters while keeping the pretrained model frozen. LoRA (Low-Rank Adaptation) adds low-rank update matrices to attention layers: where and with rank . Prompt tuning prepends learnable continuous vectors to the input. Adapters insert small bottleneck layers between transformer blocks. These methods reduce trainable parameters from 110M to 0.1-1M while achieving 90-99% of full fine-tuning performance.
LoRA (Low-Rank Adaptation) freezes the pretrained weights and adds a low-rank update where and with rank . For and , each adapted layer adds only parameters versus for full fine-tuning. The low-rank constraint acts as an inductive bias: task-specific adaptations tend to lie in a low-dimensional subspace of the full parameter space. Prompt tuning prepends learnable "soft prompt" tokens to the input, adding only parameters while keeping the entire model frozen.
BERT-base has . LoRA with rank is applied to all 12 attention layers (Q, K, V, O projections each). How many trainable parameters does this add?
Theory Exercise
Problem:
Compare fine-tuning the entire BERT model vs. freezing the backbone and only training the classification head (feature extraction). Under what data conditions does each approach work best? What is the tradeoff?
Hints:
- Think about how many parameters need to be estimated in each approach
Coding Exercise
Problem:
Simulate the difference between feature extraction and fine-tuning. Create a frozen 'pretrained' feature extractor, train a classification head on top, then compare with end-to-end training where the features are also updated.
Hints:
- Create random 'pretrained' features as a fixed transformation
Related Problems on PixelBank
A toxicity classifier that labels every comment "safe" is 99 percent accurate on a platform where 1 percent of comments are toxic, and it catches nothing. Accuracy hides exactly the failures that matter, so a model is only as good as the metric used to judge it. The previous topics built classifiers, from Naive Bayes to fine-tuned BERT; this topic decides how to tell whether they work.
Precision and recall separate the two kinds of error, false alarms and misses. F1 combines them with a harmonic mean that punishes imbalance between them. Multi-class problems need an averaging rule, and macro, micro, and weighted averages can disagree sharply when one class is rare. A confusion matrix shows which classes are mistaken for which, and ROC-AUC measures ranking quality before any threshold is chosen.
The right metric follows from the cost of errors. A spam filter values precision, since losing a legitimate email is costly, while a medical screen values recall. Each concept below computes its metric by hand on a small example, then shows the case it misses.
Definition
Classification evaluation measures a classifier against held-out gold labels with metrics built from true and false positives and negatives: precision, recall, F1, per-class averages (macro, micro, weighted), the confusion matrix, and threshold-free ranking metrics such as ROC-AUC. The metric should reflect the real cost of each type of error.
In this topic
- 1Precision, Recall, and F1
- 2Macro, Micro, and Weighted Averaging
- 3Confusion Matrix Analysis
- 4ROC-AUC and Threshold-Independent Evaluation
Precision, Recall, and F1
Precision is the fraction of predicted positives that are truly positive: . Recall is the fraction of actual positives that are correctly predicted: . F1 is their harmonic mean, which penalizes extreme imbalances between precision and recall. A model with 100% precision but 1% recall gets F1 = 1.98%, not 50.5% as the arithmetic mean would suggest. The harmonic mean ensures that both precision and recall must be reasonable for F1 to be high.
Precision measures what fraction of positive predictions are correct (penalizes false alarms). Recall measures what fraction of actual positives are found (penalizes misses). F1 is the harmonic mean, which is always less than or equal to the arithmetic mean — it heavily penalizes imbalanced P/R. If and , the arithmetic mean is 0.50 (looks decent) but (correctly identifies the problem). This harsh penalty is why F1 is the standard metric for imbalanced classification.
A sentiment classifier has: TP=80 (correctly identified positive), FP=20 (negative called positive), FN=30 (positive called negative), TN=870. Compute precision, recall, F1, and accuracy.
Macro, Micro, and Weighted Averaging
Multi-class problems require aggregating per-class metrics. Macro averaging computes F1 for each class independently and averages them, treating all classes equally regardless of size. Micro averaging pools all TP, FP, FN across classes before computing F1, effectively weighting by class frequency. Weighted averaging computes per-class F1 and averages weighted by class support (number of true instances). Macro is sensitive to performance on rare classes, micro is dominated by frequent classes, and weighted balances between the two.
Macro-average computes the metric per class then averages: , treating all classes equally regardless of size. Micro-average pools all TP/FP/FN across classes: , weighting by class size. Weighted-average multiplies each class's metric by its support: . For imbalanced datasets (95% class A, 5% class B), micro-F1 accuracy A's F1, while macro-F1 averages A and B equally, exposing poor performance on the rare class.
A 3-class classifier has: Class A (100 samples): F1=0.95. Class B (50 samples): F1=0.80. Class C (10 samples): F1=0.40. Compute macro and weighted F1.
Confusion Matrix Analysis
A confusion matrix is a table where entry counts how many examples of true class were predicted as class . The diagonal contains correct predictions; off-diagonal entries reveal systematic error patterns. For text classification, confusion matrices often reveal that: (1) adjacent sentiment classes are confused (3-star vs 4-star), (2) similar topics are mixed up (Science vs Technology), (3) one class absorbs errors from many others (the majority class in imbalanced settings). Normalizing rows by the true class count shows per-class recall; normalizing columns shows per-class precision.
The confusion matrix shows which classes are confused with which. The diagonal contains correct predictions; off-diagonal entries reveal error patterns. Normalizing each row by its sum gives , making it easy to spot classes that are systematically misclassified. For instance, if the (negative, neutral) cell is large, the model struggles to distinguish mildly negative from neutral — a signal to improve feature engineering or add more training data for these borderline cases.
A 3-class sentiment classifier is evaluated on 300 reviews, 100 per true class. Of the reviews whose true label is negative, 85 were predicted negative, 10 neutral, and 5 positive. Of the true neutrals, 15 were predicted negative, 60 neutral, and 25 positive. Of the true positives, 3 were predicted negative, 12 neutral, and 85 positive. Which class has the worst recall? Which has the worst precision?
ROC-AUC and Threshold-Independent Evaluation
The Receiver Operating Characteristic (ROC) curve plots the True Positive Rate (recall) against the False Positive Rate () at every possible classification threshold. The Area Under the Curve (AUC) summarizes ranking quality: AUC = 0.5 means random ranking, AUC = 1.0 means perfect ranking. AUC is threshold-independent, making it useful when the optimal threshold is unknown or will be tuned separately. For multi-class problems, AUC is computed per class (one-vs-rest) and averaged. AUC is particularly valuable for imbalanced datasets where accuracy and even F1 can be misleading.
The ROC curve plots true positive rate () versus false positive rate () at every possible threshold. AUC is the integral under this curve, with 1.0 being perfect and 0.5 being random. Probabilistically, AUC equals — the probability that a randomly chosen positive example scores higher than a randomly chosen negative. This threshold-independent property is valuable when the operating threshold will be chosen later based on deployment constraints (e.g., "we can tolerate 5% false positive rate").
A binary classifier produces scores for 6 examples: positives get scores [0.9, 0.7, 0.4] and negatives get scores [0.6, 0.3, 0.1]. Compute the AUC using the probabilistic interpretation.
Theory Exercise
Problem:
A medical text classification system detects disease mentions in clinical notes. The dataset has 95% negative (no disease) and 5% positive (disease present). Explain why accuracy, macro-F1, and AUC would give different assessments of the system. Which metric should be prioritized and why?
Hints:
- Calculate accuracy for a model that always predicts negative
Coding Exercise
Problem:
Implement a complete evaluation suite for a multi-class classifier. Compute the confusion matrix, per-class precision/recall/F1, macro/micro/weighted F1, and AUC for a simulated classifier.
Hints:
- Build the confusion matrix by counting (true, predicted) pairs