PIXELBANKv8.2.1
Menu
Back to NLP Study Plan
Week 3

Chapter 3: Text Representation

Transform raw text into numerical vectors that machine learning models can process. Master classical techniques from simple count-based methods to dimensionality reduction, building the foundation for modern embeddings.

Chapter Overview

Before any NLP model can process text, words and documents must be converted into numerical representations. This chapter covers the classical methods that dominated NLP for decades and still serve as strong baselines today.

The central challenge is capturing meaning in numbers. A naive approach (assigning word 1 = 1, word 2 = 2) imposes a false ordering. Instead, we need representations where similar texts map to nearby vectors. The methods here range from simple count-based approaches (Bag of Words) to statistically weighted schemes (TF-IDF) to techniques that capture word relationships through co-occurrence patterns.

Understanding these foundations is essential because:

  • Bag of Words and TF-IDF remain competitive for many classification tasks
  • Co-occurrence matrices inspired the word embeddings revolution (Word2Vec, GloVe)
  • Dimensionality reduction techniques (SVD, PCA) are used everywhere in modern NLP pipelines
  • Every modern embedding method can be understood as improving upon these classical approaches

This chapter covers:

  • Bag of Words: Converting documents to count vectors
  • TF-IDF: Weighting terms by importance across a corpus
  • N-grams: Capturing local word order and phrases
  • One-Hot Encoding: Binary word representations and their limitations
  • Co-occurrence Matrices: Learning from word context patterns
  • Dimensionality Reduction: Compressing sparse representations into dense vectors

Chapter Roadmap

Click any topic to jump in

1
Bag of Words

Count-based document vectors — ignoring word order to capture which words appear and how often.

Vocabulary ConstructionCount Vector RepresentationTerm Frequency (TF)Limitations of Bag of Words
Improving on raw counts

Weighting by importance and capturing local order

2
TF-IDF

Weighting terms by local frequency and global rarity — the workhorse of information retrieval.

TF-IDF FormulaInverse Document Frequency (IDF)TF-IDF VariantsTF-IDF for Document Retrieval
3
N-grams

Capturing local word order as token tuples — bigrams, trigrams, and language model probabilities.

N-gram DefinitionN-gram Language ModelsSkip-gramsData Sparsity and Smoothing
From sparse to distributional

Simple indicators and context-based statistics

4
One-Hot Encoding

Binary indicator vectors — the simplest representation and why it fails at scale.

One-Hot Vector DefinitionDimensionality ProblemEmbedding Layer as One-Hot Lookup
5
Co-occurrence Matrices

Counting word-context pairs and PMI weighting — the statistical foundation of word embeddings.

Word-Context Co-occurrence MatrixPointwise Mutual Information (PMI)PPMI (Positive PMI)SVD on Co-occurrence Matrices
Compressing into dense representations
6
Dimensionality Reduction

PCA, SVD, and LSA — compressing sparse representations into dense vectors that generalize.

Principal Component Analysis (PCA)Singular Value Decomposition (SVD)Latent Semantic Analysis (LSA)Truncated SVD for Sparse Matrices

The Bag of Words (BoW) model is the simplest and most intuitive method for converting text into numerical vectors. Each document is represented as a vector of word counts, completely ignoring grammar and word order.

Despite its simplicity, BoW is surprisingly effective for many tasks like spam detection, sentiment analysis, and document classification. The key insight is that which words appear often matters more than how they are arranged.

Formally, given a vocabulary VV of V|V| unique words, each document dd is represented as a vector xRV\mathbf{x} \in \mathbb{R}^{|V|} where xix_i is the count of the ii-th vocabulary word in dd.

In this topic

1Vocabulary Construction
2Count Vector Representation
3Term Frequency (TF)
4Limitations of Bag of Words
1 of 4
Vocabulary Construction

V={w1,w2,,wn}=dDunique(d)V = \{w_1, w_2, \ldots, w_n\} = \bigcup_{d \in D} \text{unique}(d)

The vocabulary is the set of all unique words across the entire corpus DD. Each word gets a fixed index position. The vocabulary size V|V| determines the dimensionality of every document vector. In practice, vocabularies are pruned by removing rare words (appearing in fewer than kk documents) and very common words (stop words) to reduce dimensionality.

Mathematical Intuition

The vocabulary V=dDunique(d)V = \bigcup_{d \in D} \text{unique}(d) grows sublinearly with corpus size by Heaps' law: VkNβ|V| \approx k N^\beta. Each document vector xRV\mathbf{x} \in \mathbb{R}^{|V|} has at most d|d| non-zero entries out of V|V| dimensions. For a typical corpus with V=50,000|V| = 50{,}000 and average document length 200 words, each vector is 99.6%99.6\% zeros — sparse matrix storage is essential.

Example:

Build the vocabulary for the corpus: ["the cat sat", "the dog ran", "a cat ran"]. What is the dimensionality?

2 of 4
Count Vector Representation

xd=[count(w1,d),count(w2,d),,count(wV,d)]\mathbf{x}_d = [\text{count}(w_1, d), \text{count}(w_2, d), \ldots, \text{count}(w_{|V|}, d)]

Each document dd becomes a vector where the ii-th element is the number of times word wiw_i appears in dd. This creates a document-term matrix MRD×VM \in \mathbb{R}^{|D| \times |V|} where each row is a document and each column is a word. The matrix is typically very sparse since most documents use only a small fraction of the vocabulary.

Mathematical Intuition

The document-term matrix MRD×VM \in \mathbb{R}^{|D| \times |V|} has Mij=count(wj,di)M_{ij} = \text{count}(w_j, d_i). Two documents sharing kk words have dot product x1x2=j:wjd1d2c1jc2j\mathbf{x}_1 \cdot \mathbf{x}_2 = \sum_{j: w_j \in d_1 \cap d_2} c_{1j} \cdot c_{2j}. Cosine similarity normalizes this by vector magnitudes, removing the length bias: longer documents do not automatically appear more similar to everything.

Example:

Using vocabulary [a, cat, dog, ran, sat, the], represent "the cat sat" and "a cat ran" as count vectors.

3 of 4
Term Frequency (TF)

TF(t,d)=ft,dtdft,d\text{TF}(t, d) = \frac{f_{t,d}}{\sum_{t' \in d} f_{t',d}}

Raw counts can be misleading: a longer document naturally has higher counts. Term Frequency normalizes by dividing each word count by the total number of words in the document. This gives a proportion rather than an absolute count. Variants include binary TF (1 if present, 0 otherwise), logarithmic TF (1+logft,d1 + \log f_{t,d}), and augmented TF that prevents bias toward longer documents.

Mathematical Intuition

Term frequency TF(t,d)=ft,d/tft,d\text{TF}(t,d) = f_{t,d} / \sum_{t'} f_{t',d} normalizes raw counts to a probability distribution over the vocabulary. The sum tTF(t,d)=1\sum_t \text{TF}(t,d) = 1 for every document, regardless of length. This means TF treats a 10-word tweet and a 10,000-word article on equal footing — the representation captures word proportions, not absolute counts.

Example:

Compute TF for every word in "the cat sat on the mat" (6 words total).

4 of 4
Limitations of Bag of Words

BoW has three fundamental limitations: (1) No word order -- "dog bites man" and "man bites dog" produce identical vectors. (2) High dimensionality -- vocabulary sizes of 50K-100K create very sparse vectors. (3) No semantics -- "happy" and "joyful" are treated as completely unrelated dimensions. These limitations motivate TF-IDF (for importance weighting), n-grams (for local order), and word embeddings (for semantics).

Mathematical Intuition

BoW is invariant to word permutation: any reordering of words produces the same vector. Formally, for any permutation π\pi, BoW(w1,,wn)=BoW(wπ(1),,wπ(n))\text{BoW}(w_1, \ldots, w_n) = \text{BoW}(w_{\pi(1)}, \ldots, w_{\pi(n)}). This means n!n! distinct sentences map to the same representation. For a 10-word sentence, that is 10!=3,628,80010! = 3{,}628{,}800 distinct orderings collapsed into one vector — a massive information loss that n-grams partially recover.

Example:

Show that BoW cannot distinguish "the cat chased the dog" from "the dog chased the cat".

Theory Exercise

Problem:

A corpus has 10,000 documents with an average of 200 words each. The vocabulary after preprocessing has 25,000 unique words. (a) What is the shape of the document-term matrix? (b) Estimate the sparsity (percentage of zero entries). (c) Why is sparsity a problem for machine learning?

Hints:
  • Each document is a row, each word is a column

Coding Exercise

Problem:

Use scikit-learn's CountVectorizer to convert a list of 3 sentences into a document-term matrix. Print the vocabulary, the matrix shape, and the dense matrix.

Hints:
  • Import CountVectorizer from sklearn.feature_extraction.text