Sub topic 5
Bag of words: counting terms
This chapter assumes you can read basic Python, know what a NumPy array is, and have seen a classifier with fit and predict. Earlier chapters covered tokenization, normalization and vocabulary construction. Here we use them to turn documents into rows of counts.
The idea
A bag of words (BoW) represents a document by how many times each vocabulary term appears in it. Order and grammar are discarded, as if you tipped the words into a bag and shook it. What remains is one number per term.
Given a vocabulary of V terms, each document becomes a vector of length V. Position j holds the count of term j. Stacking one vector per document gives the document-term matrix, which the next chapter covers in detail.
Building it by hand
The algorithm has two passes. The first pass collects the vocabulary and assigns each term a column. The second pass counts terms in each document.
from collections import Counter
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"the cat chased the dog",
]
tokenized = [d.split() for d in docs]
vocab = sorted({t for doc in tokenized for t in doc})
index = {t: i for i, t in enumerate(vocab)}
def to_counts(tokens):
row = [0] * len(vocab)
for term, count in Counter(tokens).items():
if term in index: # terms outside the vocabulary are ignored
row[index[term]] = count
return row
print(vocab)
for tokens in tokenized:
print(to_counts(tokens))
print(to_counts("the bird sat on the mat".split()))The vocabulary is ['cat', 'chased', 'dog', 'log', 'mat', 'on', 'sat', 'the']. The first document becomes [1, 0, 0, 0, 1, 1, 1, 2]: "cat", "mat", "on" and "sat" appear once, and "the" appears twice.
The last line shows an important property. "bird" is not in the vocabulary, so it contributes nothing, and the result is [0, 0, 0, 0, 1, 1, 1, 2]. A fitted vocabulary is fixed. Any word it has not seen is invisible at prediction time.
The same thing with scikit-learn
CountVectorizer performs both passes. fit learns the vocabulary, and transform counts against it.
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.toarray())
print(vec.transform(["the bird sat on the mat"]).toarray())The output matches the hand-built version. The feature names are sorted alphabetically, and the unseen word "bird" is silently dropped.
fit_transform returns a SciPy sparse matrix, not a dense array. We call toarray() only because the example is tiny. On a real corpus, stay sparse.
What the defaults do for you
CountVectorizer applies several steps before counting. Knowing them explains most surprises.
| Step | Default behavior | Parameter |
|---|---|---|
| Lowercasing | On | `lowercase=True` |
| Tokenization | Regex `(?u)\b\w\w+\b`, which keeps runs of two or more word characters | `token_pattern` |
| N-gram range | Single words only | `ngram_range=(1, 1)` |
| Stop words | None removed | `stop_words=None` |
| Counting | Raw counts | `binary=False` |
The tokenizer drops one-character tokens. You can check this directly.
from sklearn.feature_extraction.text import CountVectorizer
print(CountVectorizer().fit(["a cat saw I"]).get_feature_names_out())This prints ['cat', 'saw']. The words "a" and "I" vanish because they are one character long. That is usually harmless, but it matters for tasks where short tokens carry meaning, such as "C" versus "R" in programming text. Change token_pattern if you need them.
Counts, binary presence and word order
Raw counts are one choice. With binary=True, every nonzero count becomes 1, so the vector records only whether a term appears. Binary features can work better on short texts, where a repeated word is rarely a stronger signal than a single mention. Later chapters cover frequency weighting that handles repetition more gracefully.
The bigger consequence of bag of words is that word order is lost completely. The following example shows two sentences with opposite meanings.
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
pair = ["dog bites man", "man bites dog"]
X = CountVectorizer().fit_transform(pair).toarray()
print(X)
print(np.array_equal(X[0], X[1]))Both rows are [1 1 1], and the check prints True. A model fed these features cannot tell the sentences apart. N-grams, covered later, recover some local order by treating phrases such as "man bites" as terms.
Common errors
- Fitting on the wrong data. The vocabulary comes from whatever you pass to
fit. Fit on training text only, then calltransformon test text. Chapter 16 explains why. - Treating unseen words as errors. They are ignored by design. If the test set uses mostly new vocabulary, your vectors will be near zero, and the model will behave as if it saw nearly empty documents.
- Calling
toarray()on a large corpus. A 100,000-document corpus with a 200,000-term vocabulary needs 20 billion cells as a dense array. Keep the sparse matrix. - Assuming column order is meaningful. Columns are ordered alphabetically only because of how the vocabulary is stored. Always map columns back through
get_feature_names_out(). - Raw counts that track length. A document twice as long has roughly twice the counts. Normalization and TF weighting, covered in later chapters, address this.
What bag of words gives you, and what it costs
Bag of words is simple, fast, and works well as a baseline for classification and search. Each feature is a named word, so you can inspect which terms drive a linear model's decisions.
The costs follow from the design. Word order is lost. Synonyms such as "film" and "movie" occupy unrelated columns. Common words such as "the" get the largest counts yet say the least about content. The last problem is the motivation for the IDF weighting that the following chapters introduce.
Exercise
Using the vocabulary ['cat', 'chased', 'dog', 'log', 'mat', 'on', 'sat', 'the'], write the count vector for the new document "the dog chased the cat on the mat". Then say what vector you would get if you added the word "tiger" to the document.
Show answer
Count each term in vocabulary order: cat 1, chased 1, dog 1, log 0, mat 1, on 1, sat 0, the 3. The vector is [1, 1, 1, 0, 1, 1, 0, 3]. Adding "tiger" changes nothing, because "tiger" is not in the fitted vocabulary and is ignored. The vector stays [1, 1, 1, 0, 1, 1, 0, 3].
Exercise
Why does CountVectorizer().fit_transform(["dog bites man", "man bites dog"]) produce two identical rows, and which later technique recovers some of the lost information?
Show answer
Bag of words records only how many times each term occurs, not where. Both sentences contain the same three terms once each, so their count vectors are equal. N-grams (for example ngram_range=(1, 2)) add phrase terms such as "dog bites" and "bites man", which makes the two rows differ.