A document is a histogram, not a sentence
Bag of Words reduces a paragraph to a frequency table over a fixed vocabulary, and the reduction is deliberately violent: grammar disappears, word order disappears, and only the count of each term survives. That sounds like a fatal loss, and for tasks that hinge on who did what to whom it is. For a great many tasks it is not, because the presence of refund, invoice, and dispute already separates a complaint email from a newsletter regardless of the order those words appear in.
The representation is a sparse vector in a space whose dimension equals the vocabulary size. A typical English vocabulary of 50,000 terms means every document lives in 50,000 dimensions, of which a 200-word email fills perhaps 150. Everything interesting about BoW follows from that one fact: it is cheap to build, cheap to multiply, blind to syntax, and expensive to store once your corpus grows.
This lesson builds the vectorizer by hand first, so the matrix produced by scikit-learn stops being a black box, then examines the exact information BoW discards and the point at which discarding it stops being acceptable.
Building the vocabulary and the matrix
Collection is the first pass: scan every document once, gather the distinct terms, sort them, and assign each an index. Classification is the second: for each document, tally occurrences and emit one row. The row is the document, the column is a vocabulary term, and the number of non-zero entries equals the number of distinct terms in that document.
from collections import Counter
def fit_bow(documents, min_df=1, max_df_ratio=1.0):
n = len(documents)
counts = [Counter(d.lower().split()) for d in documents]
df = Counter()
for c in counts:
df.update(c.keys())
vocab = sorted(
w for w, d in df.items()
if min_df <= d <= max_df_ratio * n
)
index = {w: i for i, w in enumerate(vocab)}
return index, counts
def transform(index, counts):
rows = []
for c in counts:
row = [0] * len(index)
for w, k in c.items():
if w in index:
row[index[w]] = k
rows.append(row)
return rows
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"the cat chased the dog",
]
index, counts = fit_bow(docs, min_df=2)
matrix = transform(index, counts)
print("vocab (min_df=2):", sorted(index))
# ['cat', 'dog', 'on', 'sat', 'the']
for row in matrix:
print(row)
# [1, 0, 1, 1, 2]
# [0, 1, 1, 1, 2]
# [1, 1, 0, 0, 2]
Notice what min_df=2 did: log and chased were dropped because they occur once, which shrinks the matrix but also discards exactly the terms that make a document distinctive. Document-frequency filtering is a precision-versus-size dial, and setting it too aggressively is one of the most common ways to quietly damage a classifier.
Binary, sublinear, and normalized variants
Raw counts assume that a term appearing six times is six times as informative as one appearing once, which is rarely true â the sixth occurrence of a keyword usually says more about the author's persistence than about the topic. Binary counting throws frequency away entirely and keeps presence. Sublinear scaling keeps the signal but compresses it: 1 + log(count).
import math
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
documents = [
"spam spam spam offer",
"meeting notes for monday",
"spam offer for you",
]
raw = CountVectorizer()
X_raw = raw.fit_transform(documents).toarray()
binary = CountVectorizer(binary=True)
X_bin = binary.fit_transform(documents).toarray()
def sublinear(count):
return 1 + math.log(count) if count else 0
X_sub = np.vectorize(sublinear)(X_raw)
print("vocab:", raw.get_feature_names_out())
print("raw:\n", X_raw)
print("binary:\n", X_bin)
print("sublinear:\n", X_sub)
# raw: [[3, 1, 0, 1, 1], [0, 0, 1, 1, 1], [1, 1, 0, 1, 1]]
# binary: [[1, 1, 0, 1, 1], [0, 0, 1, 1, 1], [1, 1, 0, 1, 1]]
# sublinear:[[3.40, 1.0, 0, 1.0, 1.0], [0, 0, 1.0, 1.0, 1.0], [1.0, 1.0, 0, 1.0, 1.0]]
Normalization divides each row by its L2 norm so that document length stops dominating similarity. Without it, a 5,000-word report scores higher against almost any query than a precise 30-word answer, purely because it contains more of everything.
What the vectors mean geometrically
Once a document is a point in vocabulary space, similarity becomes a question about angles rather than words. Two reviews that share no rare terms but agree on awful, broken, and refund sit close together even if one is twice as long, provided the rows are normalized. This is the reason normalization matters more than the choice between raw counts and binary counts: without it, length is the dominant direction in the space, and cosine similarity quietly degrades into a comparison of document sizes. It also explains why BoW classifiers generalize across topics they have never seen â the decision boundary is drawn between regions of the space, and a new document that lands in the right region is classified correctly no matter which specific sentences produced it.
What the bag deliberately forgets
The canonical failure is the reversed sentence: dog bites man and man bites dog produce byte-identical vectors, so any classifier built on them must treat the two as the same observation. The second failure is synonymy: excellent and superb occupy different columns and therefore appear unrelated, while bank occupies one column for both the river and the account. The third is composition â not good counts as one positive adjective plus one negation word, and nothing in the vector records that they interact.
| Property | Preserved by BoW | Lost by BoW |
|---|---|---|
| Term frequency | Yes | â |
| Document length | Only via normalization | Absolute length |
| Word order | No | All syntax and relations |
| Synonyms | No | excellent vs superb |
| Negation scope | No | not good reads as good |
| Topic signal | Strong | â |
| Out-of-vocabulary terms | Unknown token | Subword identity |
Sparsity grows with the vocabulary
As the vocabulary expands, the fraction of non-zero entries collapses. A 10,000-word email against a 100,000-term vocabulary is 0.1 percent dense, and dense linear algebra wastes almost all of its work on zeros. This is why BoW pipelines use sparse CSR matrices, why hashing vectorizers exist, and why dimensionality reduction or feature selection usually precedes the classifier.
| Vocabulary | Avg distinct terms per 200-word doc | Density | Memory per 1M docs (sparse) |
|---|---|---|---|
| 5,000 | 180 | 3.6% | ~144 MB |
| 20,000 | 195 | 1.0% | ~195 MB |
| 100,000 | 199 | 0.2% | ~210 MB |
| 1,000,000 | 200 | 0.02% | ~230 MB |
Putting BoW in front of a classifier
The classic production pattern is a pipeline: vectorize, then classify, with both steps fitted on the training fold only. Fitting the vectorizer on the full dataset before splitting leaks test vocabulary into training and inflates reported accuracy, which is the single most frequent methodological error in beginner text projects.
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import Pipeline
from sklearn.model_selection import cross_val_score
from sklearn.metrics import classification_report
train_docs = [
"win free cash prize now", "claim your reward click here",
"quarterly budget review notes", "standup moved to ten am",
"cheap meds no prescription needed", "project deadline extended friday",
]
train_labels = [1, 1, 0, 0, 1, 0] # 1 = spam
bow_pipe = Pipeline([
("bow", CountVectorizer(ngram_range=(1, 2), min_df=1)),
("clf", MultinomialNB(alpha=1.0)),
])
scores = cross_val_score(bow_pipe, train_docs, train_labels, cv=3)
print("cv accuracy:", scores.mean().round(3))
bow_pipe.fit(train_docs, train_labels)
print(classification_report(
train_labels, bow_pipe.predict(train_docs), digits=2
))
print("top spam terms:", sorted(
zip(bow_pipe.named_steps["bow"].get_feature_names_out(),
bow_pipe.named_steps["clf"].feature_log_prob_[1]),
key=lambda kv: kv[1], reverse=True)[:5]
)
Reading the learned weights turns the model into an audit tool: if the top-weighted tokens for the spam class include a word your support team uses in legitimate replies, the training set is biased and the metric will not tell you.
When BoW is still the right answer
BoW remains competitive when the signal is lexical and the labels are topical: language identification, keyword filtering, authorship-attribution baselines, and coarse sentiment on short reviews. It trains in seconds on a laptop, it is trivially explainable, and it needs no GPU. It stops being the right answer as soon as the task depends on relations between words, on long-range context, or on meaning that is not spelled out â for those, you move to TF-IDF weighting, then to embeddings, then to transformers.
đĄBaseline before you benchmark
Common Mistakes
Fitting CountVectorizer on the entire dataset before train-test splitting
Fix: Put the vectorizer inside a Pipeline so fit runs only on training folds and vocabulary never leaks.
Assuming BoW captures negation or word order
Fix: Add bigrams so 'not good' becomes its own feature, or move to embeddings when relations matter.
Keeping every hapax legomenon in the vocabulary
Fix: Tune min_df and max_df; terms occurring once add columns but almost never add signal.
Comparing raw-count vectors of very different lengths
Fix: Normalize rows to unit L2 norm or use TfidfVectorizer, which normalizes by default.
Best Practices
- Establish a BoW baseline before reaching for embeddings or transformers
- Use ngram_range=(1, 2) for short texts, where bigrams carry most of the negation and phrase signal
- Inspect top-weighted features per class to catch label leakage and annotation artifacts
- Keep the vectorizer inside the pipeline so preprocessing is versioned with the model
Interview Questions
Q1: Why does BoW treat 'dog bites man' and 'man bites dog' identically?
Because the representation is a per-term count vector with no positional channel, so any permutation of the same multiset of words maps to the same point in the space.
Q2: What does min_df actually filter?
Minimum document frequency: terms appearing in fewer than min_df documents are dropped from the vocabulary, shrinking the matrix but discarding rare and often highly discriminative terms.
Q3: How does binary BoW differ from count BoW and when would you pick it?
Binary records presence as 1 regardless of frequency, which helps when repeated occurrences reflect writing style rather than topic, and it is the default choice for authorship and short-text similarity.
Key Takeaways
- BoW maps each document to a sparse count vector indexed by a fixed vocabulary, discarding order and grammar entirely
- Binary, sublinear, and L2-normalized variants each correct a specific distortion in raw counts
- Vocabulary growth drives density toward zero, which is why sparse matrix formats and feature filtering matter
- Always fit the vectorizer inside the pipeline to prevent vocabulary leakage across folds
- A BoW baseline is the honest yardstick any neural text model has to beat