v9.1.1
Menu

Chapter 7: Text Classification

Week 7

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

Interactive demo
1
Sentiment Analysis

Polarity classification, aspect-based sentiment, and fine-grained rating prediction.

Polarity ClassificationAspect-Based Sentiment AnalysisFine-Grained Sentiment Scales
Generalizing beyond sentiment

Document-level and multi-label extensions of classification

2
Document Classification

Naive Bayes, TF-IDF features, hierarchical categories, and handling class imbalance.

Naive Bayes for TextTF-IDF Feature EngineeringHierarchical ClassificationHandling Class Imbalance
3
Multi-Label Classification

Binary relevance, classifier chains, and threshold tuning for multi-label outputs.

Binary RelevanceClassifier ChainsThreshold Selection
Neural architectures for text
4
CNNs for Text

1D convolution over embeddings, max-pooling, and the TextCNN architecture.

1D Convolution over EmbeddingsMax-Over-Time PoolingMultiple Filter SizesTextCNN Architecture (Kim 2014)
Modern methods and measurement

Pretrained model fine-tuning and evaluation methodology

5
Fine-Tuning Pretrained Models

Classification heads, learning rate strategies, and parameter-efficient fine-tuning.

Classification Head ArchitectureLearning Rate StrategiesCatastrophic ForgettingFew-Shot and Parameter-Efficient Fine-Tuning
6
Classification Evaluation

Precision, recall, F1, macro/micro averaging, confusion matrices, and ROC-AUC.

Precision, Recall, and F1Macro, Micro, and Weighted AveragingConfusion Matrix AnalysisROC-AUC and Threshold-Independent Evaluation

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

  1. 1Polarity Classification
  2. 2Aspect-Based Sentiment Analysis
  3. 3Fine-Grained Sentiment Scales
1 of 3
Polarity Classification

y^=arg⁡max⁡c∈{pos,neg,neu}P(c∣x)\hat{y} = \arg\max_{c \in \{\text{pos}, \text{neg}, \text{neu}\}} P(c \mid x)

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: L=−∑cyclog⁡(y^c)\mathcal{L} = -\sum_{c} y_c \log(\hat{y}_c). 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.

Mathematical Intuition

The softmax P(c∣x)=exp⁡(zc)/∑c′exp⁡(zc′)P(c \mid x) = \exp(z_c) / \sum_{c'} \exp(z_{c'}) turns unbounded logits zcz_c into a probability distribution. The boundary between classes c1c_1 and c2c_2 lies where zc1=zc2z_{c_1} = z_{c_2}, which for a linear model is the hyperplane (wc1−wc2)⊤x=bc2−bc1(w_{c_1} - w_{c_2})^\top x = b_{c_2} - b_{c_1}. Cross-entropy −log⁡P(y∣x)-\log P(y \mid x) 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.

Example:

A logistic regression model outputs raw scores [2.1, -0.5, 0.3] for [positive, negative, neutral]. Compute the predicted class and its probability.

2 of 3
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.

Mathematical Intuition

ABSA decomposes the document-level sentiment P(sentiment∣doc)P(\text{sentiment} \mid \text{doc}) into aspect-specific sentiments P(sentimenta∣spana,context)P(\text{sentiment}_a \mid \text{span}_a, \text{context}) for each aspect aa. 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 αa,j\alpha_{a,j} focus on the words relevant to aspect aa, enabling the same sentence to yield different sentiment features for different aspects.

Example:

Given the review 'The screen is beautiful, the speakers are decent, but the keyboard feels cheap', identify the aspects and their sentiments.

3 of 3
Fine-Grained Sentiment Scales

y^=arg⁡max⁡c∈{1,2,3,4,5}P(c∣x)\hat{y} = \arg\max_{c \in \{1,2,3,4,5\}} P(c \mid x)

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.

Mathematical Intuition

Ordinal regression respects the ordering 1<2<3<4<51 < 2 < 3 < 4 < 5 by modeling cumulative probabilities P(y≤k∣x)=σ(θk−w⊤x)P(y \leq k \mid x) = \sigma(\theta_k - w^\top x) for thresholds θ1<θ2<θ3<θ4\theta_1 < \theta_2 < \theta_3 < \theta_4. This ensures monotonicity: P(y≤3)≥P(y≤2)P(y \leq 3) \geq P(y \leq 2) 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 E[y]=∑kk⋅P(y=k)\mathbb{E}[y] = \sum_k k \cdot P(y = k) provides a continuous score even from a discrete classifier.

Example:

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"}