A document as a vector of counts
- : how many times vocabulary term appears in the document.
- : the size of the vocabulary.
Every document becomes a vector of the same length, whatever its actual length, and that fixed shape is what lets ordinary models read text at all.
The order is discarded, which is the assumption in the name. The bag knows what was said and not how it was arranged.
The two things that go wrong immediately
Losing order loses the relation, and for some tasks that is fatal while for topic classification it barely matters.
The vectors are enormous and almost entirely zero. A 50,000-term vocabulary and a 200-word document means 0.4 percent of the entries are non-zero.
That sparsity is the reason these vectors are stored as index and value pairs rather than as arrays, and why linear models on them are fast despite the dimension.
Weighting the counts
Raw counts favour long documents, so the counts are usually normalised by length first.
Sublinear scaling is the other common correction, since a term appearing 100 times is not 100 times as important as one appearing once.
The frequency problem remains: the most common terms carry the least information, which is exactly what TF-IDF is for and why a bag of raw counts is rarely used on its own.
One document, in order
- Lowercase and strip punctuation, unless case or punctuation is a signal.
- Split into tokens.
- Remove stop words, or keep them and let the weighting handle it.
- Map each token to its vocabulary index, dropping anything unseen.
- Count, weight, and store the non-zero entries.
The hashing trick replaces steps four and five: hash each token into one of buckets and skip the vocabulary entirely, which fixes the memory and accepts a small collision rate.
Where it still wins
Adding bigrams recovers a little of the lost order, at the cost of a vocabulary several times larger.
A bag of words with TF-IDF and a linear classifier is a serious baseline on topic classification, spam and sentiment, and it trains in seconds on a laptop.
It has no idea that two words mean the same thing, because every term is its own orthogonal dimension. That single limitation is what embeddings were invented to remove.