Sub topic 3
Bag-of-words and the document-term matrix
This chapter covers how a collection of documents becomes a matrix of word counts. It assumes you can write basic Python, know what training and test sets are, and have used NumPy arrays. It also assumes you have read the previous chapter on tokenization, so you know that a tokenizer splits text into lowercase word pieces.
Why classifiers need a matrix
A logistic regression model takes a fixed-length vector of numbers for each example. A document is a string of arbitrary length. Bag-of-words is the simplest bridge between the two. You choose a vocabulary, which is a list of terms. Then you represent each document by how many times each vocabulary term occurs in it.
The word "bag" is literal. Imagine dropping all the tokens of a document into a bag and shaking it. You keep which tokens are present and how often. You lose the order. "dog bites man" and "man bites dog" produce the same vector.
Stacking the vectors for all documents gives the document-term matrix. It has one row per document and one column per vocabulary term. Entry X[i, j] is the count of term j in document i.
A worked example
Take three short documents.
the cat sat on the matthe dog sat on the logcats and dogs are pets
The vocabulary, sorted alphabetically, has 12 terms: and, are, cat, cats, dog, dogs, log, mat, on, pets, sat, the. Note that cat and cats are separate columns. The tokenizer does not stem or lemmatize.
Scikit-learn's CountVectorizer builds this matrix.
from sklearn.feature_extraction.text import CountVectorizer
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"cats and dogs are pets",
]
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(docs)
print(X.shape)
print(vectorizer.get_feature_names_out())
print(X.toarray())The output has shape (3, 12). The first row has a 2 in the the column because "the" appears twice in the first document. Most other entries are 0 or 1.
If your own text differs from this example, check one default before you trust the vocabulary. The default token pattern is (?u)\b\w\w+\b. It keeps only tokens of two or more word characters. A one-letter word like "a" or "I" is dropped silently.
Fit and transform are different steps
fit_transform does two jobs. fit learns the vocabulary from the documents you pass in. transform uses that fixed vocabulary to produce counts.
This distinction matters when you handle new text.
new_docs = ["the cat chased the dog", "a bird sat on the mat"]
X_new = vectorizer.transform(new_docs)
print(X_new.shape)
print(X_new.toarray())The result still has 12 columns. The words "chased" and "bird" are not in the vocabulary, so they are ignored. This is called the out-of-vocabulary problem. The model can only use words it saw during fitting.
Two consequences follow.
- Always call
fiton the training documents only. If you fit on the test set too, the vocabulary absorbs information from data the model should never have seen. This is a form of data leakage. - The columns must match between training and prediction. Reuse the same fitted vectorizer. Never call
fit_transforma second time on new data.
Sparsity and why it matters
Real vocabularies have tens of thousands of terms, but a typical document uses a few hundred of them. So almost every entry in the matrix is zero. A matrix like this is sparse.
Scikit-learn returns a SciPy sparse matrix, which stores only the nonzero entries and their positions. You can measure the saving.
import numpy as np
from scipy import sparse
rng = np.random.default_rng(0)
n_docs, n_terms = 10_000, 50_000
# Simulate 100 distinct terms per document
rows = np.repeat(np.arange(n_docs), 100)
cols = rng.integers(0, n_terms, size=n_docs * 100)
vals = np.ones(n_docs * 100)
X_sparse = sparse.csr_matrix((vals, (rows, cols)), shape=(n_docs, n_terms))
dense_bytes = n_docs * n_terms * 8
sparse_bytes = X_sparse.data.nbytes + X_sparse.indices.nbytes + X_sparse.indptr.nbytes
print(f"density: {X_sparse.nnz / (n_docs * n_terms):.4%}")
print(f"dense: {dense_bytes / 1e6:.0f} MB")
print(f"sparse: {sparse_bytes / 1e6:.0f} MB")A dense version of this matrix needs about 4,000 MB. The sparse version needs roughly 12 MB. Calling .toarray() on a real corpus is a common way to run out of memory. Keep the matrix sparse and pass it directly to the classifier. Logistic regression in scikit-learn accepts sparse input.
Inspecting a sparse matrix safely
Use these operations instead of converting to a dense array.
| Goal | Code |
|---|---|
| Number of documents and terms | `X.shape` |
| Number of stored nonzero entries | `X.nnz` |
| Total count of each term | `np.asarray(X.sum(axis=0)).ravel()` |
| Number of terms in each document | `np.asarray(X.sum(axis=1)).ravel()` |
| One document as a dense row | `X[i].toarray()` |
The sums return NumPy matrix objects, so wrap them with np.asarray(...).ravel() to get ordinary 1-D arrays.
Reading the vocabulary
The fitted vectorizer has a vocabulary_ dictionary that maps each term to its column index. The method get_feature_names_out() returns the terms in column order. Together they let you translate between words and columns.
terms = vectorizer.get_feature_names_out()
totals = np.asarray(X.sum(axis=0)).ravel()
for idx in np.argsort(totals)[::-1][:5]:
print(terms[idx], totals[idx])
print(vectorizer.vocabulary_["cat"])The most frequent term is the with a total of 4. This shows a basic weakness of raw counts. The most common words are usually the least informative. They appear in every document regardless of class. The next chapter addresses this with TF-IDF weighting.
Options that change the counts
CountVectorizer has several parameters that change what the matrix contains. These are the ones you will use most often.
| Parameter | Default | Effect |
|---|---|---|
| `lowercase` | `True` | Lowercases text before tokenizing, so "Cat" and "cat" share a column |
| `stop_words` | `None` | Removes words from a list, such as `"english"` |
| `min_df` | `1` | Drops terms found in fewer than this many documents |
| `max_df` | `1.0` | Drops terms found in more than this fraction of documents |
| `binary` | `False` | Records 1 for presence instead of the count |
| `max_features` | `None` | Keeps only the most frequent terms by total count |
| `ngram_range` | `(1, 1)` | Includes word sequences of the given lengths |
Two of these deserve a closer look.
Binary versus counts
With binary=True, a word that appears 10 times is recorded as 1, the same as a word that appears once. For short texts such as tweets or titles, repeats are rare and the two options behave almost identically. For long documents, counts carry more information about topic emphasis, but they also let a single repeated word dominate the row. You can test both choices with cross-validation rather than guessing.
Document frequency filters
min_df=2 removes terms that occur in only one document. These are often typos, names, or identifiers. A term seen once in training cannot teach the model a general pattern, and it adds a column that only memorizes one example. Likewise max_df=0.9 removes terms present in more than 90% of documents. The later chapter on n-grams and vocabulary control covers these filters in detail.
Common errors
- Fitting on all the data before splitting. The vocabulary then includes test-only words, which makes evaluation look better than it should.
- Expecting similar words to be related.
catandcats, orgoodandgreat, are unrelated columns. The model has no idea they are similar unless you normalize them or supply enough examples of each. - Assuming order is kept. Negation breaks. "not good" yields the counts for
notandgoodseparately. Bigrams partly fix this, which a later chapter shows. - Converting to dense.
.toarray()on a large corpus can exhaust memory. - Losing short tokens. The default pattern drops single characters, which can remove meaningful signals like "c" or "r" in programming text. Pass a custom
token_patternif that matters for your data. - Mismatched vectorizers. A model trained with one vectorizer must be paired with that same fitted vectorizer. Storing them together in a Pipeline prevents this mistake.
Where raw counts fall short
Raw counts have two problems. First, long documents get larger numbers than short ones, even if they talk about the same thing. Second, frequent function words get large counts but carry little class information. TF-IDF corrects both: it rescales counts by how rare each term is across the collection and normalizes each row by length. Everything else you learned here carries over, because TfidfVectorizer builds the same sparse matrix and then applies the weighting.
Exercise
You fit a CountVectorizer on 5,000 training emails and get 40,000 columns. You then call vectorizer.fit_transform(test_emails) to prepare the test set and feed it to the trained classifier. Name two things that go wrong, and give the corrected call.
Show answer
First, the vectorizer learns a new vocabulary from the test emails, so the number of columns can differ from 40,000 and the classifier will reject the input with a shape error. Second, even when the shapes happen to match, column j now stands for a different word than the one the classifier learned a weight for, so predictions are meaningless. The test set also influences the vocabulary, which is data leakage. The correct call is vectorizer.transform(test_emails), using the vectorizer that was fitted on the training emails only.
Exercise
A corpus of 20,000 documents has a 60,000-term vocabulary, and each document contains about 150 distinct terms. Estimate the number of stored nonzero entries and the density of the document-term matrix.
Show answer
The matrix stores about 20,000 × 150 = 3,000,000 nonzero entries. The full matrix has 20,000 × 60,000 = 1,200,000,000 cells, so the density is 3,000,000 / 1,200,000,000 = 0.25%. A dense float64 version would take about 9.6 GB, while the sparse version needs a few tens of megabytes.