Text Preprocessing
🎯 Learning Objectives
- Understand the standard NLP text preprocessing pipeline
- Differentiate between stemming and lemmatization
- Compute Bag of Words and TF-IDF representations by hand
- Explain n-gram models and their applications
- Apply text normalization techniques to real text
1. Why Text Preprocessing?
Raw text data is noisy, unstructured, and highly variable. Before any NLP model can work effectively, text must be transformed into a clean, consistent, numerical representation. The preprocessing pipeline typically follows this order:
- Text normalization (lowercasing, punctuation removal, special character handling)
- Tokenization (splitting text into tokens)
- Stop word removal (filtering common, low-information words)
- Stemming or Lemmatization (reducing words to their base form)
- Vectorization (converting tokens to numerical features: BoW, TF-IDF, n-grams)
2. Text Normalization
Text normalization standardizes raw text to reduce variability without losing meaning:
- Lowercasing: Convert all characters to lowercase. “The Cat SAT” → “the cat sat”. Reduces vocabulary size but may lose meaning (“Apple” the company vs “apple” the fruit).
- Punctuation removal: Strip periods, commas, exclamation marks, etc. Useful for bag-of-words models but may hurt tasks like sentiment analysis where “!!!” carries emphasis.
- Number handling: Replace digits with a token like <NUM> or remove them entirely depending on the task.
- Unicode normalization: Convert accented characters (é → e), handle ligatures, emoji processing.
- Whitespace normalization: Collapse multiple spaces, tabs, and newlines into single spaces.
Example: Normalization Pipeline
Input: “Dr. Smith’s 3rd paper (2024) costs $45.99!!!”
After lowercasing: “dr. smith’s 3rd paper (2024) costs $45.99!!!”
After punctuation removal: “dr smiths 3rd paper 2024 costs 4599”
After number handling: “dr smiths <NUM> paper <NUM> costs <NUM>”
3. Tokenization
3.1 Word Tokenization
The simplest approach splits on whitespace and punctuation:
- “I can't wait!” → [“I”, “can”, “'t”, “wait”, “!”] (handling contractions)
- “New York City” → [“New”, “York”, “City”] (loses multi-word entity)
3.2 Subword Tokenization
Modern NLP models (BERT, GPT) use subword tokenization to handle out-of-vocabulary words:
- Byte Pair Encoding (BPE): Iteratively merges the most frequent pair of adjacent characters/subwords. Vocabulary size is a hyperparameter.
- WordPiece: Similar to BPE but uses likelihood-based merging. Used by BERT.
- SentencePiece: Language-agnostic, treats the input as raw text (no pre-tokenization needed).
Example: BPE Tokenization
“unhappiness” → [“un”, “happiness”] or [“un”, “hap”, “pi”, “ness”] depending on the learned merges.
This allows the model to handle rare words by decomposing them into known subwords.
3.3 Character Tokenization
Splits text into individual characters. Very small vocabulary (e.g., 128 for ASCII) but produces very long sequences, making it computationally expensive for most tasks.
4. Stop Word Removal
Removing stop words reduces the feature space and can improve performance in tasks like document classification and information retrieval. However, stop word removal can hurt tasks that rely on syntax (e.g., machine translation, question answering).
Example
Before: “the cat is sitting on the mat”
After stop word removal: [“cat”, “sitting”, “mat”]
The core meaning is preserved while reducing tokens from 7 to 3.
5. Stemming
Porter Stemmer (most widely used) applies a series of rule-based transformations:
- “running” → “run”
- “flies” → “fli” (not a real word!)
- “happiness” → “happi”
- “computing”, “computed”, “computation” → “comput”
Pros: Fast, simple, no dictionary required. Cons: Over-stemming (“university” → “univers”, “universe” → “univers” — incorrectly merged) and under-stemming (“alumni” and “alumnus” may not reduce to the same stem).
6. Lemmatization
- “running” → “run” (verb)
- “flies” → “fly” (not “fli”)
- “better” → “good” (adjective)
- “went” → “go” (verb)
Lemmatization requires knowledge of the part of speech (POS): “meeting” as a noun → “meeting”; as a verb → “meet”.
Stemming vs Lemmatization
| Feature | Stemming | Lemmatization |
|---|---|---|
| Method | Rule-based suffix stripping | Dictionary + morphological analysis |
| Output | May not be a valid word | Always a valid dictionary word |
| Speed | Faster | Slower (requires POS tagging) |
| Accuracy | Lower (over/under-stemming) | Higher |
| “better” | “better” (no change) | “good” |
7. Bag of Words (BoW)
Given a vocabulary V = {w₁, w₂, …, w|V|}, each document d is represented as a vector x ∈ ℝ|V| where xi = count of word wi in d.
Worked Example
Documents:
- D1: “the cat sat on the mat”
- D2: “the dog sat on the log”
Vocabulary: {cat, dog, log, mat, on, sat, the}
BoW vectors:
| cat | dog | log | mat | on | sat | the | |
|---|---|---|---|---|---|---|---|
| D1 | 1 | 0 | 0 | 1 | 1 | 1 | 2 |
| D2 | 0 | 1 | 1 | 0 | 1 | 1 | 2 |
Limitations: Loses word order (“dog bites man” = “man bites dog”); high dimensionality for large vocabularies; no semantic understanding.
8. TF-IDF (Term Frequency – Inverse Document Frequency)
Term Frequency (TF):
TF(t, d) = (count of term t in document d) / (total terms in d)
Inverse Document Frequency (IDF):
IDF(t, D) = log(N / df(t))
where N = total number of documents, df(t) = number of documents containing term t.
TF-IDF score:
TF-IDF(t, d, D) = TF(t, d) × IDF(t, D)
Worked Example
Corpus (3 documents):
- D1: “machine learning is great” (4 terms)
- D2: “deep learning is powerful” (4 terms)
- D3: “machine learning and deep learning” (5 terms)
Compute TF-IDF for “machine” in D1:
- TF(“machine”, D1) = 1/4 = 0.25
- df(“machine”) = 2 (appears in D1 and D3)
- IDF(“machine”) = log(3/2) = log(1.5) ≈ 0.176
- TF-IDF = 0.25 × 0.176 ≈ 0.044
Compute TF-IDF for “learning” in D1:
- TF(“learning”, D1) = 1/4 = 0.25
- df(“learning”) = 3 (all documents)
- IDF(“learning”) = log(3/3) = log(1) = 0
- TF-IDF = 0.25 × 0 = 0 (word appears everywhere — no discriminative power)
💡 GATE Tip
GATE may ask you to compute TF-IDF values by hand. Always check whether the problem uses natural log (ln) or log base 10. Also note the “+1” variants: some formulations use IDF = log((N+1)/(df+1)) + 1 to avoid division by zero and zero IDF.
9. N-grams
Example
Sentence: “the cat sat on the mat”
- Unigrams: [the, cat, sat, on, the, mat]
- Bigrams: [(the, cat), (cat, sat), (sat, on), (on, the), (the, mat)]
- Trigrams: [(the, cat, sat), (cat, sat, on), (sat, on, the), (on, the, mat)]
Number of n-grams from a sequence of length L: L − n + 1
For our sentence (L=6): bigrams = 6 − 2 + 1 = 5 ✔
N-grams capture local word order, partially addressing the limitation of Bag of Words. Bigram features can distinguish “not good” from “good” in sentiment analysis.
Trade-off: Larger n captures more context but increases vocabulary size exponentially (|V|n possible n-grams) and leads to data sparsity.
10. Summary
| Technique | Purpose | Key Point |
|---|---|---|
| Normalization | Clean & standardize text | Lowercasing, punctuation removal |
| Tokenization | Split text into tokens | Word, subword (BPE), or character level |
| Stop words | Remove low-information words | “the”, “is”, “and” etc. |
| Stemming | Reduce to root (heuristic) | Fast but may produce invalid words |
| Lemmatization | Reduce to lemma (dictionary) | Slower but always valid output |
| Bag of Words | Count-based vector representation | Ignores word order |
| TF-IDF | Weighted representation | TF × IDF; penalizes common words |
| N-grams | Capture local word order | Bigrams, trigrams; #n-grams = L−n+1 |