v9.1.1
Menu

Chapter 3: Text Representation

Week 3

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.

Topics
6
Demos
3
Videos
3
Min read
47

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

Explainer videoInteractive demo
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

Topics

6 topics in this chapter

A spam filter receives the email "WIN a FREE prize now". A sentiment classifier receives "the battery died after two days". Both are machine-learning models, and machine-learning models take fixed-length vectors of numbers, not strings of varying length. How do we turn arbitrary text into such a vector while keeping enough signal to separate spam from real mail, or praise from complaint?

The previous chapter, Text Preprocessing, produced clean tokens through tokenization, stemming, stopword removal, and normalization. This chapter, Text Representation, turns those tokens into numbers, and Bag of Words is the simplest answer: count each vocabulary word in the document and ignore order entirely. The topic starts with vocabulary construction, which fixes the dimensions of every vector. Count vectors and the document-term matrix follow, then term frequency, which normalizes counts by document length. It ends with the limitations of the model, namely lost word order, huge sparse vectors, and no notion of meaning, which motivate the rest of the chapter: TF-IDF, n-grams, co-occurrence statistics, and dense vectors.

Definition

A Bag of Words representation maps a document dd to a vector x∈N∣V∣\mathbf{x} \in \mathbb{N}^{|V|} over a fixed vocabulary VV, where xix_i is the number of times word wiw_i occurs in dd. Word order, grammar, and position are discarded; only the multiset of tokens remains, so the vector is sparse and has one dimension per vocabulary word.

In this topic

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

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

Before any document becomes a vector, the model needs a fixed list of dimensions. The vocabulary VV is the union of unique tokens across the training corpus DD, and each word receives a permanent index, so ∣V∣|V| sets the length of every document vector. Vocabularies keep growing with corpus size, roughly as a power of the token count by Heaps' law, so practical pipelines prune them: drop words found in fewer than a minimum number of documents, drop stopwords or words found in almost every document, or keep the top kk by frequency. Words seen only at test time have no index and are silently ignored.

Mathematical Intuition

The vocabulary V=⋃d∈Dunique(d)V = \bigcup_{d \in D} \text{unique}(d) grows sublinearly with corpus size by Heaps' law: ∣V∣≈kNβ|V| \approx k N^\beta. Each document vector x∈R∣V∣\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(w∣V∣,d)]\mathbf{x}_d = [\text{count}(w_1, d), \text{count}(w_2, d), \ldots, \text{count}(w_{|V|}, d)]

Given the vocabulary, each document dd becomes a vector xd\mathbf{x}_d whose ii-th entry counts how often word wiw_i appears in dd. Stacking these vectors row by row gives the document-term matrix M∈R∣D∣×∣V∣M \in \mathbb{R}^{|D| \times |V|}, with one row per document and one column per word. Because a document uses a few hundred distinct words out of tens of thousands, more than 99 percent of entries are zero, so libraries store MM in sparse formats such as CSR that keep only the non-zero values and their positions. Similarity between documents is then a dot product or cosine between rows. Raw counts favor long documents, which is why the next step normalizes them.

Mathematical Intuition

The document-term matrix M∈R∣D∣×∣V∣M \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 x1⋅x2=∑j:wj∈d1∩d2c1j⋅c2j\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,d∑t′∈dft′,d\text{TF}(t, d) = \frac{f_{t,d}}{\sum_{t' \in d} f_{t',d}}

Raw counts grow with document length: a review pasted twice has every count doubled, though its content is unchanged. Term frequency divides each count ft,df_{t,d} by the total number of tokens in dd, turning the count vector into a probability distribution over the vocabulary that sums to 1. Variants make different trade-offs. Binary TF records presence only, which works well for short texts. Logarithmic TF, 1+log⁡ft,d1 + \log f_{t,d}, damps words repeated many times. Augmented TF divides by the largest count in the document. TF alone still rewards frequent function words such as "the", the problem that the next topic, TF-IDF, solves by weighting terms by their rarity across documents.

Mathematical Intuition

Term frequency TF(t,d)=ft,d/∑t′ft′,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

Bag of Words makes three simplifying choices, and each one breaks something. It discards order, so "dog bites man" and "man bites dog" get identical vectors; every permutation of a sentence maps to the same point. It uses one dimension per word, so vectors have 50,000 to 100,000 dimensions that are almost all zeros, and models need many examples per feature. It treats every word as an unrelated axis, so "happy" and "joyful" share nothing, and a classifier that learns one never generalizes to the other. The later topics in this chapter each address one gap: TF-IDF weights importance, n-grams restore local order, and co-occurrence statistics begin to capture meaning.

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