Sub topic 6
The Document-Term Matrix
Prerequisites and the basic structure
Assume you know Python lists, NumPy arrays, and the idea that a machine-learning model needs numeric input. You should also know that tokenization splits text into tokens, such as words, and that a vocabulary is the set of terms selected from a collection of documents.
A document-term matrix (DTM) is a table that represents documents as numbers. Each row represents one document. Each column represents one vocabulary term. The cell at row i, column j stores the relationship between document i and term j. With bag-of-words features, that value is usually the term's count.
For example, consider these documents:
- Document 1: “cat sat”
- Document 2: “cat slept”
The vocabulary is [cat, sat, slept], so the DTM is:
| Document | cat | sat | slept |
|---|---|---|---|
| 1 | 1 | 1 | 0 |
| 2 | 1 | 0 | 1 |
The matrix has shape (2, 3): two documents and three terms. The order of the columns is part of the model. A new document must use the same vocabulary and column order.
Constructing a DTM with scikit-learn
CountVectorizer tokenizes text, builds a vocabulary, and counts token occurrences. Its output is usually a SciPy sparse matrix rather than a dense NumPy array.
from sklearn.feature_extraction.text import CountVectorizer
documents = [
"the cat sat on the mat",
"the dog sat on the log",
"the cat chased the dog",
]
vectorizer = CountVectorizer()
matrix = vectorizer.fit_transform(documents)
print(vectorizer.get_feature_names_out())
print(matrix.shape)
print(matrix.toarray())The vocabulary is sorted alphabetically by default. The first document becomes [1, 0, 0, 0, 1, 1, 1, 2] for the columns cat, chased, dog, log, mat, on, sat, the. The final value is 2 because “the” occurs twice.
fit_transform learns the vocabulary from these documents and transforms them into rows. Later, call only transform on new documents:
new_matrix = vectorizer.transform(["the cat sat"])
print(new_matrix.toarray())Calling fit_transform again would create a new vocabulary and could change the meaning of every column.
Sparse storage
Most documents contain only a small fraction of the full vocabulary. Therefore, most DTM cells are zero. A sparse matrix stores nonzero values and their positions instead of storing every zero. This saves memory when the corpus is large.
Exercise
If a corpus has 500 documents and a vocabulary of 2,000 terms, what is the DTM shape, and what does a value of 3 mean?
Show answer
The shape is (500, 2000). A value of 3 means that the corresponding term occurs three times in that document.