Sub topic 3
Bag-of-Words and the Document-Term Matrix
This chapter assumes basic Python, NumPy, and supervised learning. You should know that a training set contains examples and labels, and that a test set measures performance on unseen examples.
The bag-of-words idea
A machine-learning classifier needs numbers as input. Documents are sequences of words, so we first represent each document with numeric features.
The bag-of-words model represents a document by the words it contains and usually ignores word order. It builds a vocabulary, which is the set of distinct terms selected from the documents. Each vocabulary term becomes one feature.
For example, consider these documents:
the cat satthe dog satcats and dogs
The vocabulary might be:
and, cat, cats, dog, dogs, sat, the
Each document becomes a vector with one position for each vocabulary term. The value in a position is often the number of times that term occurs in the document.
This representation is called a document-term matrix. Each row represents a document, and each column represents a vocabulary term.
| Document | and | cat | cats | dog | dogs | sat | the |
|---|---|---|---|---|---|---|---|
| `the cat sat` | 0 | 1 | 0 | 0 | 0 | 1 | 1 |
| `the dog sat` | 0 | 0 | 0 | 1 | 0 | 1 | 1 |
| `cats and dogs` | 1 | 0 | 1 | 0 | 1 | 0 | 0 |
The matrix is usually very sparse. Sparse means that most entries are zero. A document normally contains only a small fraction of the terms in a large vocabulary, so storing every zero wastes memory.
Building the matrix with scikit-learn
CountVectorizer performs common text preparation and creates a document-term matrix. By default, it converts text to lowercase, splits it into tokens, and counts token occurrences.
from sklearn.feature_extraction.text import CountVectorizer
documents = [
"the cat sat on the mat",
"the dog sat on the log",
"cats and dogs are pets",
]
vectorizer = CountVectorizer()
counts = vectorizer.fit_transform(documents)
print("shape:", counts.shape)
print("vocabulary:", vectorizer.get_feature_names_out())
print(counts.toarray())fit_transform does two operations:
fitlearns the vocabulary from the supplied documents.transformconverts those documents into vectors using that vocabulary.
If the matrix has shape (3, 11), it has three document rows and eleven feature columns. The order of the columns is given by get_feature_names_out(). You must use that same order when interpreting feature values.
The vectorizer treats related spellings as different terms. For example, cat and cats receive separate columns. It also does not understand that dog and dogs have similar meanings. Stemming or lemmatization can combine related forms, but those choices add preprocessing decisions and are not always helpful.
What the representation preserves and loses
Bag-of-words preserves:
- Which vocabulary terms occur.
- How often each term occurs, when using counts.
- Differences in word usage between documents.
It loses:
- Word order.
- Most grammar.
- Word meaning and context.
- The relationship between synonyms.
For example, dog bites man and man bites dog produce identical unigram counts. A classifier using only these features cannot distinguish their word order.
A feature can also be a binary indicator rather than a count. With binary features, a term receives 1 if it appears and 0 otherwise. Counts can help when repetition matters, while binary features can be useful when repeated words mostly reflect writing style.
Vocabulary control
A vocabulary can become large when the corpus contains spelling variations, rare names, identifiers, or accidental text. CountVectorizer provides controls such as:
min_df, which removes terms appearing in too few documents.max_df, which removes terms appearing in too many documents.stop_words, which can remove a supplied list of frequent words.binary=True, which records presence instead of counts.
These settings should be selected using training data. If the vectorizer learns its vocabulary from the test set, information from the test set leaks into training and makes evaluation less trustworthy.
From counts to TF-IDF
Raw counts are a useful baseline, but common words can dominate the matrix. TF-IDF later reweights these counts so that a term receives more weight when it is frequent in one document but uncommon across the corpus. The same document-term structure remains; only the values change.
Exercise
Why can two documents with different word order produce the same unigram document-term vector?
Show answer
A unigram bag-of-words representation records term presence or counts but does not record the positions or order of the terms.