TExcelTAD
Home › NLP, Transformers & LLM Fine-Tuning › Bag of Words and n-grams

Bag of Words and n-grams

A linear classifier, a nearest-neighbour search or a clustering algorithm needs every input to be a vector of the same length. Text is a sequence of variable length. The bag of words is the oldest and still the simplest bridge: fix a vocabulary of VV words, and represent each document by how often each vocabulary word occurs in it. Word order is thrown away (the "bag"), and so is everything the model has not seen in training. What remains is surprisingly strong: bag-of-words features with a linear model were the standard for spam filtering, topic classification and search for two decades, and they are still the baseline any neural model has to beat, as in Text Classification with Linear Models.

Working with Text introduced CountVectorizer for beginners. This lesson builds the document-term matrix from scratch, stores it the way scikit-learn does (a sparse CSR matrix), adds n-grams to recover some word order, prunes the vocabulary with document frequencies and stop words, and replaces the vocabulary altogether with the hashing trick.

"The bike lockis broken." raw text the bike lockis broken normalise + tokenise the:19 bike:1lock:10 is:9broken:2 vocabulary lookup 23 columns,5 non-zero count vector fitted on training text only 0 1 1 bike 1 2 broken 0 0 0 0 0 0 1 9 is 1 10 lock 0 0 0 0 0 0 0 0 1 19 the 0 0 0 one row of the document-term matrix; columns in alphabetical vocabulary order

The document-term matrix

Given documents d1,…,dnd_1, \dots, d_n and a vocabulary w1,…,wVw_1, \dots, w_V, the document-term matrix X∈Nn×VX \in \mathbb{N}^{n \times V} has entries

Xij=count⁡(wj,di),X_{ij} = \operatorname{count}(w_j, d_i),

the number of times word jj occurs in document ii. Row ii is document ii's vector. Building it takes two passes: one over the training documents to collect and number the vocabulary, one to count. The example does both with a dictionary and a NumPy array, using scikit-learn's default token pattern (lowercase, words of at least two letters or digits) so that the result can be compared with CountVectorizer exactly.

python · try it yourself
import re
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer

docs = ["The bike lock is broken.",
        "The app shows the bike, but the lock will not open.",
        "Refund the double charge on my card.",
        "My card was charged twice for one ride."]

def tokenize(doc):
    return re.findall(r"(?u)\b\w\w+\b", doc.lower())     # scikit-learn's default pattern

vocab = {w: i for i, w in enumerate(sorted({w for d in docs for w in tokenize(d)}))}
X = np.zeros((len(docs), len(vocab)), dtype=np.int64)
for row, d in enumerate(docs):
    for w in tokenize(d):
        X[row, vocab[w]] += 1

print(len(vocab), "words:", list(vocab))
print(X)
cv = CountVectorizer()
Xs = cv.fit_transform(docs)
print("same as CountVectorizer:", list(cv.get_feature_names_out()) == list(vocab),
      np.array_equal(Xs.toarray(), X))
print("new text:", cv.transform(["The lock of the e-bike is stuck"]).toarray()[0].tolist())
23 words: ['app', 'bike', 'broken', 'but', 'card', 'charge', 'charged', 'double', 'for', 'is', 'lock', 'my', 'not', 'on', 'one', 'open', 'refund', 'ride', 'shows', 'the', 'twice', 'was', 'will']
[[0 1 1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 1 0 0 0]
 [1 1 0 1 0 0 0 0 0 0 1 0 1 0 0 1 0 0 1 3 0 0 1]
 [0 0 0 0 1 1 0 1 0 0 0 1 0 1 0 0 1 0 0 1 0 0 0]
 [0 0 0 0 1 0 1 0 1 0 0 1 0 0 1 0 0 1 0 0 1 1 0]]
same as CountVectorizer: True True
new text: [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0]

The four sentences give a 23-word vocabulary, numbered alphabetically, and a 4×234 \times 23 count matrix; "the" occurs three times in the second sentence. CountVectorizer produces the same vocabulary and the same matrix. The last line shows what the representation does with new text: "The lock of the e-bike is stuck" keeps only the words the vocabulary knows ("the" twice, "bike", "lock", "is"). "of" and "stuck" were never seen and vanish without a trace, and the one-letter "e" of "e-bike" is dropped by the token pattern. A bag-of-words model is blind to every word outside its training vocabulary, the same out-of-vocabulary problem as in Splitting Text.

The figure above shows the first sentence's row: five non-zero entries out of 23. With a realistic vocabulary of 50,000 words and documents of 50 words, more than 99.9% of each row is zero.

Sparse storage: CSR

Storing those zeros is wasteful, so scikit-learn returns a sparse matrix in compressed sparse row (CSR) format from SciPy. CSR keeps three arrays: data holds the non-zero values row by row, indices the column of each value, and indptr where each row starts in the other two (row ii is data[indptr[i]:indptr[i+1]]). Row access and the matrix-vector products that linear models need are fast; changing the sparsity pattern is slow, which is why vectorisers build the matrix once.

python · try it yourself
import numpy as np
from scipy import sparse
from sklearn.feature_extraction.text import CountVectorizer

X = np.array([[0, 2, 0, 0, 1],
              [1, 0, 0, 0, 0],
              [0, 0, 0, 3, 1]])
data, indices, indptr = [], [], [0]
for row in X:
    nz = np.flatnonzero(row)
    data += row[nz].tolist()
    indices += nz.tolist()
    indptr.append(len(data))
print("data   ", data)
print("indices", indices)
print("indptr ", indptr)
S = sparse.csr_matrix((data, indices, indptr), shape=X.shape)
print("round trip ok:", np.array_equal(S.toarray(), X))

rng = np.random.default_rng(0)
words = [f"w{i}" for i in range(20_000)]
p = 1 / np.arange(1, 20_001) ** 1.1
p /= p.sum()
docs = [" ".join(rng.choice(words, size=40, p=p)) for _ in range(2_000)]
M = CountVectorizer().fit_transform(docs)
dense_mb = M.shape[0] * M.shape[1] * 8 / 1e6
sparse_mb = (M.data.nbytes + M.indices.nbytes + M.indptr.nbytes) / 1e6
print(f"shape {M.shape}, stored values {M.nnz}, density {M.nnz / (M.shape[0] * M.shape[1]):.4%}")
print(f"dense float64: {dense_mb:.1f} MB, CSR: {sparse_mb:.2f} MB")
data    [2, 1, 1, 3, 1]
indices [1, 4, 0, 3, 4]
indptr  [0, 2, 3, 5]
round trip ok: True
shape (2000, 9258), stored values 60206, density 0.3252%
dense float64: 148.1 MB, CSR: 0.73 MB

The hand-built arrays reproduce the small matrix, and indptr = [0, 2, 3, 5] says row 0 has 2 non-zeros, row 1 has 1 and row 2 has 2. On a synthetic corpus of 2,000 documents of 40 words drawn from a Zipf distribution, the vocabulary has 9,258 words and only 0.3252% of the matrix is non-zero. As a dense float64 array it would take 148.1 MB; in CSR it takes 0.73 MB, about 200 times less. Keep the matrix sparse all the way: X.toarray() on a real corpus is the classic way to run out of memory, and models such as LogisticRegression, LinearSVC and MultinomialNB accept sparse input directly.

n-grams: some word order back

"the battery is good" and "the battery is not good" differ in a single count, that of "not", which says nothing about what was negated. n-grams, sequences of nn consecutive tokens, restore local order: with bigrams (n=2n = 2) the second sentence contains "not good", a feature that a classifier can learn to weight negatively. ngram_range=(1, 2) uses unigrams and bigrams together.

The cost is vocabulary size. A corpus with VV distinct words can have up to V2V^2 distinct bigrams, and in practice the number of distinct n-grams grows almost linearly with the corpus, most of them seen once. Two pruning parameters fix this: min_df drops terms that occur in fewer than that many documents (an integer) or that fraction of documents (a float), and max_df drops terms that occur in more than that fraction of documents, typically words so common that they carry no information. Stop-word lists remove a fixed set of function words; scikit-learn ships one as ENGLISH_STOP_WORDS (NLTK's stopwords corpus needs a download).

python · try it yourself
from sklearn.feature_extraction.text import CountVectorizer, ENGLISH_STOP_WORDS

docs = ["the battery is good", "the battery is not good", "not bad at all, the app is good",
        "the app is bad", "battery life is not great"]
for ngr in [(1, 1), (1, 2), (2, 2)]:
    cv = CountVectorizer(ngram_range=ngr)
    X = cv.fit_transform(docs)
    print(ngr, "features:", X.shape[1])
cv = CountVectorizer(ngram_range=(1, 2))
cv.fit(docs)
print([f for f in cv.get_feature_names_out() if "not" in f])

print(len(ENGLISH_STOP_WORDS), "stop words; 'not' in them:", "not" in ENGLISH_STOP_WORDS,
      "| 'all' in them:", "all" in ENGLISH_STOP_WORDS)
sw = CountVectorizer(stop_words="english", ngram_range=(1, 2)).fit(docs)
print("with stop words removed:", list(sw.get_feature_names_out()))
for kw in [dict(min_df=2), dict(max_df=0.8), dict(min_df=2, max_df=0.8)]:
    cv = CountVectorizer(**kw).fit(docs)
    print(kw, list(cv.get_feature_names_out()))
(1, 1) features: 11
(1, 2) features: 26
(2, 2) features: 15
['is not', 'not', 'not bad', 'not good', 'not great']
318 stop words; 'not' in them: True | 'all' in them: True
with stop words removed: ['app', 'app bad', 'app good', 'bad', 'bad app', 'battery', 'battery good', 'battery life', 'good', 'great', 'life', 'life great']
{'min_df': 2} ['app', 'bad', 'battery', 'good', 'is', 'not', 'the']
{'max_df': 0.8} ['all', 'app', 'at', 'bad', 'battery', 'good', 'great', 'life', 'not', 'the']
{'min_df': 2, 'max_df': 0.8} ['app', 'bad', 'battery', 'good', 'not', 'the']

On five short reviews, unigrams give 11 features, unigrams plus bigrams 26, and the bigram vocabulary alone 15: bigrams more than double the feature count even here. The bigram vocabulary contains "not bad", "not good" and "not great", exactly the features a sentiment model needs.

Then look at the stop-word line. scikit-learn's list (318 words) contains "not" and "all", so after removing stop words "the battery is not good" contributes the bigram "battery good", the same feature as the positive review, and "not bad at all" becomes just "bad". For sentiment and intent, a stock stop-word list destroys the most important words; it is meant for topic-style tasks, and scikit-learn's own documentation warns that its list has known issues. Prefer max_df, which removes the words that are frequent in your corpus: max_df=0.8 dropped only "is", which occurs in all five reviews (a term is removed when its document frequency is above the threshold, so "the", in exactly 4 of 5 documents, stays). min_df=2 removed every word seen in a single review, a good default on large corpora where such words are mostly typos and names.

Fit on training data only, or hash

The vocabulary is a learned parameter, so it must come from the training split alone (data leakage). Fitting on all data lets test-only words into the vocabulary: the model cannot have learned weights for them, but min_df, max_df and IDF statistics shift, and any cross-validation that refits nothing per fold reports a score the deployed model will not reach. The flip side is that new words at serving time are silently ignored.

The hashing trick removes the vocabulary entirely. A hash function maps each token straight to a column, j=h(w) mod mj = h(w) \bmod m, for a fixed number of columns mm. Nothing is fitted, any word gets a column, memory is fixed, and the vectoriser can run on a stream or in parallel workers without sharing a dictionary. The price: you cannot map a column back to its word (no feature names, harder debugging), and different words can collide in one column. With nn distinct words hashed into mm columns, the expected number of occupied columns is

m(1−e−n/m),m \left(1 - e^{-n/m}\right),

so collisions are rare only when mm is much larger than nn. scikit-learn's HashingVectorizer uses MurmurHash3 with m=220m = 2^{20} by default and, with alternate_sign=True (the default), gives each word a random sign so that collisions cancel on average instead of adding up.

python · try it yourself
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer, HashingVectorizer

train = ["refund my double charge", "the lock is broken", "bike lock will not open",
         "charged twice for one ride"]
test = ["the e-bike lock jammed", "please refund the charge"]

cv = CountVectorizer().fit(train)                       # vocabulary from training text only
print("train vocabulary:", len(cv.vocabulary_))
analyze = cv.build_analyzer()
for t in test:
    toks = analyze(t)
    known = [w for w in toks if w in cv.vocabulary_]
    print(f"  {t!r}: tokens {toks}, kept {known}")

hv = HashingVectorizer(n_features=2**10, alternate_sign=False, norm=None)
H = hv.transform(test)                                   # no fit: any word gets a column
print("hashing, columns used per test text:", [r.nnz for r in H], "of", H.shape[1])

rng = np.random.default_rng(0)
vocab = [f"word{i}" for i in range(5_000)]
for k in (10, 14, 18):
    hv = HashingVectorizer(n_features=2**k, alternate_sign=False, norm=None)
    cols = hv.transform([" ".join(vocab)]).indices
    print(f"n_features 2^{k}: {len(vocab)} words -> {len(np.unique(cols))} distinct columns")
train vocabulary: 17
  'the e-bike lock jammed': tokens ['the', 'bike', 'lock', 'jammed'], kept ['the', 'bike', 'lock']
  'please refund the charge': tokens ['please', 'refund', 'the', 'charge'], kept ['refund', 'the', 'charge']
hashing, columns used per test text: [4, 4] of 1024
n_features 2^10: 5000 words -> 1018 distinct columns
n_features 2^14: 5000 words -> 4333 distinct columns
n_features 2^18: 5000 words -> 4955 distinct columns

The count vectoriser fitted on four training tickets knows 17 words; at test time "jammed" and "please" are not in its vocabulary and are dropped. The hashing vectoriser was never fitted and still gives every test token a column (4 per text, out of 1,024). The collision count follows the formula: 5,000 words in 210=1,0242^{10} = 1{,}024 columns occupy 1,018 of them (the formula predicts about 1,016), so almost every column is shared by about five words; with 2142^{14} columns 4,333 distinct columns are used, so hundreds of words still share; with 2182^{18}, 4,955, so only a few dozen collide. Since the matrix is sparse, a large mm costs almost nothing in memory for the features themselves, only in the size of the model's weight vector.

Pitfalls

  • Densifying. toarray() or np.asarray(X) on a real document-term matrix exhausts memory; keep CSR end to end.
  • A stock stop-word list for sentiment or intent. It removes "not", "no", "all", "full"; use max_df or a list written for the task.
  • Fitting the vectoriser before the split. Put it inside a Pipeline so that cross-validation refits it on every training fold.
  • n-grams without pruning. ngram_range=(1, 3) on a large corpus produces millions of features seen once; combine with min_df or max_features.
  • Too few hash columns. Collisions silently merge unrelated words; choose mm well above the expected vocabulary.
  • Reading hashed features. There are no feature names; keep a CountVectorizer on a sample when you need to inspect what the model learned.

Practice

  1. In the first example, which column of the count matrix does "charged" occupy, and in which documents is it non-zero?
  2. A CSR matrix has indptr = [0, 3, 3, 7]. How many rows does it have, and how many non-zeros does each row hold?
  3. Why can max_df=0.8 remove "is" but not "the" from the five reviews?
  4. You hash 100,000 distinct words into 2182^{18} columns. Estimate how many columns are occupied.
  5. A colleague fits CountVectorizer(min_df=5) on the full dataset and then runs 5-fold cross-validation of a classifier on the result. What is wrong, and how do you fix it?
Answers
  1. The vocabulary is alphabetical: "app" 0, "bike" 1, "broken" 2, "but" 3, "card" 4, "charge" 5, "charged" 6. Column 6 is 1 only in the fourth document ("My card was charged twice for one ride."); the third document has "charge", a different column.
  2. Three rows (indptr has rows + 1 entries). Row 0 holds 3 non-zeros, row 1 none (3 to 3), row 2 holds 4 (3 to 7).
  3. "is" occurs in all five documents, a document frequency of 1.0, above 0.8. "the" occurs in 4 of 5, exactly 0.8, and scikit-learn removes only terms above max_df.
  4. m(1−e−n/m)m (1 - e^{-n/m}) with m=262,144m = 262{,}144 and n/m≈0.381n/m \approx 0.381: 262,144×(1−e−0.381)≈262,144×0.317≈83,000262{,}144 \times (1 - e^{-0.381}) \approx 262{,}144 \times 0.317 \approx 83{,}000 columns, so about 17,000 words land in a column that another word already took.
  5. The vocabulary (and the min_df filter) were chosen using the validation folds, so the folds are not unseen data: words that occur 5 times only because of validation documents become features. Put the vectoriser and the classifier in one Pipeline and cross-validate the pipeline, which refits the vocabulary on each training fold.

Test yourself

In a CSR matrix, what does indptr store?

  1. The column index of each non-zero value
  2. For each row, where its values start in data and indices
  3. The non-zero values themselves
  4. The vocabulary

On the synthetic corpus of 2,000 documents, how much memory did CSR need compared with the 148.1 MB dense array?

  1. About 74 MB
  2. About 15 MB
  3. 0.73 MB
  4. 0.07 MB

After stop_words="english", the review "the battery is not good" produced the bigram "battery good". Why?

  1. Bigrams skip one word by design
  2. "not" is in scikit-learn's stop-word list, so it is removed before the bigrams are formed
  3. "not" was below min_df
  4. The tokenizer drops three-letter words

What does the hashing trick give up in exchange for needing no fitted vocabulary?

  1. Sparse output
  2. The ability to handle new words
  3. Mapping columns back to words, and collision-free columns
  4. Linear models