Sub topic 6
The document-term matrix
This chapter assumes you can read basic Python and NumPy, know what fit and predict mean for a classifier, and have seen the earlier chapters on tokenization, normalization, vocabulary construction, and bag of words. Here we assemble those pieces into the object every later chapter uses: the document-term matrix.
What the matrix is
A document-term matrix (DTM) is a two-dimensional table of numbers.
- Each row is one document.
- Each column is one term from the vocabulary.
- Each cell holds a number describing how that term relates to that document. In a bag-of-words DTM, the number is the raw count.
If you have n_docs documents and a vocabulary of n_terms entries, the matrix has shape (n_docs, n_terms). A row is the vector that represents a document, so any model that accepts a feature matrix can accept a DTM.
A worked example
Take three short documents:
the cat sat on the matthe dog sat on the logthe cat chased the dog
The vocabulary, sorted alphabetically, is cat, chased, dog, log, mat, on, sat, the. That gives 8 columns. Counting each term in each document gives this matrix:
| Document | cat | chased | dog | log | mat | on | sat | the |
|---|---|---|---|---|---|---|---|---|
| 1 | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 2 |
| 2 | 0 | 0 | 1 | 1 | 0 | 1 | 1 | 2 |
| 3 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 2 |
You can read this table in two directions:
- Reading a row gives you a document's vector. Document 1 is
[1, 0, 0, 0, 1, 1, 1, 2]. - Reading a column gives you a term's profile across the corpus. The
catcolumn is[1, 0, 1], meaning it appears in documents 1 and 3.
Both views matter. Row-wise operations drive classification and similarity search. Column-wise operations drive vocabulary pruning and IDF, which counts how many documents contain each term.
Building it with scikit-learn
CountVectorizer does the tokenizing, vocabulary building, and counting in one object.
from sklearn.feature_extraction.text import CountVectorizer
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"the cat chased the dog",
]
vec = CountVectorizer()
X = vec.fit_transform(docs)
print(vec.get_feature_names_out())
print(X.shape, X.nnz)
print(X.toarray())The output is:
['cat' 'chased' 'dog' 'log' 'mat' 'on' 'sat' 'the']
(3, 8) 14
[[1 0 0 0 1 1 1 2]
[0 0 1 1 0 1 1 2]
[1 1 1 0 0 0 0 2]]Two methods do the work:
fitscans the documents and learns the vocabulary. Columnjof every matrix this object produces refers to the same term.transformcounts terms using that fixed vocabulary.
fit_transform runs both on the same input. The vocabulary lives in the vocabulary_ attribute, a dictionary from term to column index.
Sparse storage
X is not a NumPy array. It is a SciPy sparse matrix in compressed sparse row (CSR) format. The attribute X.nnz is the number of stored non-zero cells: 14 of 24 here.
Real corpora look very different from this toy. A news article might use 300 distinct words out of a 100,000-term vocabulary, so over 99.5% of its row is zero. CSR stores only the non-zero values, their column indices, and one pointer per row marking where each row starts. Memory then grows with the number of non-zero entries rather than with n_docs × n_terms.
Call .toarray() only on small examples like this one. On a real corpus it allocates the full dense table and can exhaust memory.
Reading the matrix
A few quick calculations show what the matrix tells you. getnnz(axis=0) counts non-zero cells per column, which is each term's document frequency. sum(axis=1) adds across a row, which is the document's token count after tokenization.
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"the cat chased the dog",
]
vec = CountVectorizer()
X = vec.fit_transform(docs)
doc_freq = X.getnnz(axis=0)
total_count = np.asarray(X.sum(axis=0)).ravel()
doc_length = np.asarray(X.sum(axis=1)).ravel()
for term, df, tc in zip(vec.get_feature_names_out(), doc_freq, total_count):
print(f"{term:7s} df={df} total={tc}")
print("tokens per document:", doc_length)This prints the with df=3 total=6, chased with df=1 total=1, and document lengths [6 6 5].
The distinction between the two column statistics is important:
- Document frequency counts how many documents contain the term. It is the quantity IDF uses.
- Total count adds up every occurrence.
thehas a total of 6 but a document frequency of 3.
Applying the matrix to new text
After fitting, transform maps new documents into the same column space.
from sklearn.feature_extraction.text import CountVectorizer
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"the cat chased the dog",
]
vec = CountVectorizer()
vec.fit(docs)
new = vec.transform(["the bird sat on the mat"])
print(new.toarray())The output is [[0 0 0 0 1 1 1 2]]. The word bird is not in the vocabulary, so it is silently dropped. Nothing is added to the matrix and no error is raised.
Common errors and edge cases
- Out-of-vocabulary words vanish. A document made only of unseen words becomes an all-zero row. Downstream code that divides by the row norm, such as L2 normalization or cosine similarity, must handle zero rows.
- Short tokens are dropped. The default
token_patternisr"(?u)\b\w\w+\b", which requires at least two word characters. Words likeaandI, and single digits, never reach the matrix. - Column order comes from the sorted vocabulary. It does not follow first appearance in the text. Always use
get_feature_names_out()rather than assuming positions. - Refitting changes columns. If you call
fit_transformon a second corpus, you get a new vocabulary and new column meanings. Matrices from different fits are not comparable. - Word order is gone.
the dog chased the catandthe cat chased the dogproduce identical rows. - Counts depend on length. A document twice as long has roughly double the counts. Later chapters address this with term frequency scaling and normalization.
Why this matrix is the foundation
TF-IDF, cosine similarity, and the classification pipeline in later chapters all start from a DTM and transform it. IDF is computed by looking down columns. L2 normalization is computed across rows. Vocabulary pruning removes columns. Keeping the row and column roles clear makes each of those steps easier to follow.
Exercise
Using the three-document corpus from this chapter, what is the document frequency of sat and of chased, and what does vec.transform(["chased chased chased"]) return as a row?
Show answer
sat appears in documents 1 and 2, so its document frequency is 2. chased appears only in document 3, so its document frequency is 1. The transformed row has a 3 in the chased column (index 1) and zeros elsewhere: [0 3 0 0 0 0 0 0]. Counts are raw, so repeating the word triples the cell value.
Exercise
A corpus has 50,000 documents and a 200,000-term vocabulary. Why is a dense float64 matrix impractical, and what does CSR store instead?
Show answer
A dense matrix needs 50,000 × 200,000 = 10^10 cells at 8 bytes each, about 80 GB. CSR stores only the non-zero values, their column indices, and one row pointer per row. Its memory therefore scales with the number of non-zero entries, which is small because each document uses only a tiny fraction of the vocabulary.