Text Preprocessing

GATE Relevance: Medium

🎯 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:

  1. Text normalization (lowercasing, punctuation removal, special character handling)
  2. Tokenization (splitting text into tokens)
  3. Stop word removal (filtering common, low-information words)
  4. Stemming or Lemmatization (reducing words to their base form)
  5. Vectorization (converting tokens to numerical features: BoW, TF-IDF, n-grams)
Definition — Corpus: A large, structured collection of text documents used for training or analysis. Example: all Wikipedia articles, a collection of news articles.
Definition — Vocabulary (V): The set of all unique tokens across the entire corpus. |V| denotes vocabulary size.

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

Definition: Tokenization is the process of splitting a text string into a sequence of tokens — typically words, subwords, or characters.

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

Definition: Stop words are high-frequency words that carry little semantic meaning in many contexts — e.g., “the”, “is”, “at”, “which”, “and”, “a”.

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

Definition: Stemming reduces words to their stem (root form) by stripping suffixes using heuristic rules. The result may not be a valid dictionary word.

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

Definition: Lemmatization reduces words to their lemma (dictionary base form) using morphological analysis and a vocabulary lookup. The result is always a valid word.
  • “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

FeatureStemmingLemmatization
MethodRule-based suffix strippingDictionary + morphological analysis
OutputMay not be a valid wordAlways a valid dictionary word
SpeedFasterSlower (requires POS tagging)
AccuracyLower (over/under-stemming)Higher
“better”“better” (no change)“good”

7. Bag of Words (BoW)

Definition: The Bag of Words model represents a document as a vector of word counts (or binary presence), ignoring word order and grammar.

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:

catdoglogmatonsatthe
D11001112
D20110112

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)

Definition: TF-IDF weights a term by how often it appears in a document (TF) penalized by how common it is across all documents (IDF). Words that are frequent in a specific document but rare across the corpus get high scores.

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

Definition: An n-gram is a contiguous sequence of n tokens from a text. Unigrams (n=1) are single words, bigrams (n=2) are pairs, trigrams (n=3) are triples.

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

TechniquePurposeKey Point
NormalizationClean & standardize textLowercasing, punctuation removal
TokenizationSplit text into tokensWord, subword (BPE), or character level
Stop wordsRemove low-information words“the”, “is”, “and” etc.
StemmingReduce to root (heuristic)Fast but may produce invalid words
LemmatizationReduce to lemma (dictionary)Slower but always valid output
Bag of WordsCount-based vector representationIgnores word order
TF-IDFWeighted representationTF × IDF; penalizes common words
N-gramsCapture local word orderBigrams, trigrams; #n-grams = L−n+1