Sub topic 3
Bag-of-Words and Document-Term Counts
Prerequisites and purpose
This chapter assumes that you know tokenisation, stop words, TF-IDF, basic probability, and Python package installation. We use these ideas to build the representation that LDA needs.
A bag of words represents a document by the words it contains and how often each word occurs. It ignores word order. For example, “cats chase mice” and “mice chase cats” have the same bag of words:
- cats: 1
- chase: 1
- mice: 1
This loses grammar and some meaning, but it gives topic models a simple, useful input.
The document-term matrix
For a collection of documents, choose a vocabulary containing the terms you want to keep. A document-term matrix has one row per document and one column per vocabulary term. Each cell contains that term's count in that document.
Suppose the vocabulary is ["apple", "market", "orange"]:
| Document | apple | market | orange |
|---|---|---|---|
| D1: apple market apple | 2 | 1 | 0 |
| D2: orange market | 0 | 1 | 1 |
The matrix is usually sparse: most documents contain only a small fraction of the vocabulary. LDA therefore commonly stores each document as a list of (term_id, count) pairs rather than as a full row of zeros.
Building counts in Python
CountVectorizer from scikit-learn creates the vocabulary and count matrix. The example keeps unigrams, which are single words.
from sklearn.feature_extraction.text import CountVectorizer
documents = [
"team wins match",
"coach prepares team",
"government passes policy",
]
vectorizer = CountVectorizer()
counts = vectorizer.fit_transform(documents)
print(vectorizer.get_feature_names_out())
print(counts.toarray())fit_transform learns the vocabulary from the documents and returns the count matrix. The column order is the order printed by get_feature_names_out(). The resulting matrix can be passed to tools that accept standard count data.
Gensim uses a different but equivalent form. Its dictionary assigns each term an integer ID, and doc2bow converts each tokenised document into (term_id, count) pairs. LDA uses these counts to estimate which words tend to appear together.
Why the representation matters
Vocabulary choices affect the topics. Common stop words can dominate counts without identifying a theme. Rare spelling variants can split one concept across several columns. Removing every rare word, however, can remove meaningful names or technical terms.
LDA uses word counts directly. BERTopic usually begins with document embeddings, but its topic descriptions later use a count-based representation, class-based TF-IDF, to find words that distinguish one cluster from others. Thus, document-term counts remain useful even when embeddings perform the initial grouping.
Exercise
If two documents contain exactly the same words with the same counts in different orders, how do they differ in a bag-of-words representation?
Show answer
They do not differ. Bag-of-words records term counts and discards word order.