Sub topic 3
Bag-of-words and document-term counts
This chapter covers the input format that LDA reads and that BERTopic's c-TF-IDF step builds on. It assumes you can tokenise text, remove stop words, and run Python with gensim and scikit-learn installed. The previous chapter covered cleaning. Here you turn clean tokens into counts.
What a bag of words is
A bag-of-words representation describes a document only by which words it contains and how many times each appears. It discards word order, grammar, and position. "Dog bites man" and "man bites dog" give identical counts.
That looks wasteful, but it suits topic modelling. A topic is a pattern of words that tend to appear together. The patterns live in co-occurrence counts, not in sentence structure.
LDA treats each document as a bag of independent word draws. Its generative story, which comes later in this tutorial, is defined directly on these counts. BERTopic uses counts too. After it clusters embeddings, it counts words per cluster and weights them with c-TF-IDF.
The document-term matrix
Collect the counts for a whole corpus into a document-term matrix. Each row is a document, each column is a vocabulary word, and each cell is the number of times that word occurs in that document.
| Document | coach | government | match | policy | team | vote | win |
|---|---|---|---|---|---|---|---|
| d1: "team win match" | 0 | 0 | 1 | 0 | 1 | 0 | 1 |
| d2: "team coach team match" | 1 | 0 | 1 | 0 | 2 | 0 | 0 |
| d3: "government vote policy" | 0 | 1 | 0 | 1 | 0 | 1 | 0 |
Real matrices are mostly zeros. A news corpus may have 50,000 vocabulary words, while one article uses a few hundred of them. Libraries therefore store only the nonzero cells, which is called a sparse representation.
Building counts with gensim
Gensim stores each document as a list of (word_id, count) pairs. A Dictionary maps words to integer ids, and doc2bow converts a token list into those pairs.
from gensim import corpora
docs = [
["team", "win", "match", "team", "season"],
["government", "vote", "policy", "vote"],
["team", "coach", "season", "match"],
]
dictionary = corpora.Dictionary(docs)
corpus = [dictionary.doc2bow(doc) for doc in docs]
print(corpus[0])
print([(dictionary[word_id], count) for word_id, count in corpus[0]])
print("vocabulary size:", len(dictionary))The second print is readable: it shows ("team", 2) for the first document. The integer ids depend on the order in which gensim first saw each word, so do not rely on specific values. Words with a count of zero are absent from the pairs, which is the sparse format.
Building counts with scikit-learn
CountVectorizer does tokenising, vocabulary building, and counting in one step. It returns a SciPy sparse matrix.
from sklearn.feature_extraction.text import CountVectorizer
texts = [
"team win match",
"team coach team match",
"government vote policy",
]
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(texts)
print(vectorizer.get_feature_names_out())
print(X.shape)
print(X.toarray())The columns are sorted alphabetically, so the printed array matches the table above. X.toarray() is only safe for tiny examples. On a real corpus, converting to a dense array can exhaust memory.
The default token_pattern keeps only tokens of two or more alphanumeric characters. It lowercases text and does not stem or lemmatise. BERTopic passes a CountVectorizer to its c-TF-IDF step, so the same parameters (stop_words, ngram_range, min_df) control the words in BERTopic topic descriptions.
Moving between the two libraries
You can train gensim's LDA on a scikit-learn matrix. Wrap the sparse matrix with Sparse2Corpus and supply the vocabulary as a mapping from id to word.
from gensim.matutils import Sparse2Corpus
from gensim.models import LdaModel
from sklearn.feature_extraction.text import CountVectorizer
texts = [
"team win match season",
"team coach league season",
"government vote policy law",
"minister vote government policy",
]
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(texts)
# documents_columns=False because rows are documents in scikit-learn
corpus = Sparse2Corpus(X, documents_columns=False)
id2word = dict(enumerate(vectorizer.get_feature_names_out()))
lda = LdaModel(corpus=corpus, id2word=id2word, num_topics=2, passes=10, random_state=42)
print(lda.print_topics(num_words=4))Forgetting documents_columns=False is a common error. Gensim then reads columns as documents, and the model trains on the wrong axis without raising an error.
Controlling the vocabulary
Vocabulary size changes training time, memory use, and topic quality. Two kinds of word cause trouble:
- Very rare words, such as typos and names that appear once. They add columns but carry little co-occurrence evidence.
- Very common words, such as "said" in news text. They appear in most documents and show up in the top words of nearly every topic.
Gensim's filter_extremes removes both groups by document frequency, which is the number of documents containing a word.
from gensim import corpora
docs = [
["goal", "match", "player", "team", "season"],
["election", "vote", "party", "government", "policy"],
["team", "coach", "league", "season", "win"],
["minister", "government", "vote", "law", "policy"],
]
dictionary = corpora.Dictionary(docs)
dictionary.filter_extremes(no_below=2, no_above=0.75)
# Ids are reassigned after filtering, so rebuild the corpus
corpus = [dictionary.doc2bow(doc) for doc in docs]
print(sorted(dictionary.token2id))
print(corpus)no_below=2 drops words found in fewer than two documents. no_above=0.75 drops words found in more than 75% of documents. Only team, season, vote, government, and policy survive. The scikit-learn equivalents are min_df and max_df.
What counts cannot capture
Bag-of-words has limits you should know before you trust a topic model.
- Word order is lost. "Not good" becomes "not" and "good", and negation disappears. Phrase detection (gensim's
Phrases) orngram_range=(1, 2)inCountVectorizerjoins frequent pairs such asnew_york. - Meaning is not shared across words. "Car" and "automobile" are separate columns. LDA can still link them if they appear in similar contexts. BERTopic's embeddings address this directly.
- Document length varies. A 2,000-word article contributes far more counts than a tweet. Very short documents give LDA little evidence and tend to produce unstable topic mixtures.
- Counts are integers. Standard LDA models word counts as draws, so feed it raw counts. TF-IDF weights are fractional and break that assumption, although gensim will not stop you from passing them.
Checklist before training
- Tokens are lowercased, with stop words removed.
- The vocabulary is filtered by document frequency.
- The corpus is rebuilt after any filtering.
- No document is empty.
- Counts are raw integers.
Exercise
You run dictionary.filter_extremes(no_below=5) after building corpus with doc2bow, and then train LDA on the old corpus. Why can this produce wrong or confusing topics, and what should you do?
Show answer
filter_extremes removes words and reassigns the remaining word ids. The old corpus still uses the previous ids, so its pairs point to the wrong words or to ids that no longer exist. Rebuild the corpus with [dictionary.doc2bow(doc) for doc in docs] after filtering, then check for documents that became empty.
Exercise
A scikit-learn CountVectorizer fitted on 10,000 documents gives a matrix X of shape (10000, 40000). Why should you avoid calling X.toarray(), and how do you pass X to gensim's LdaModel?
Show answer
toarray() builds a dense 10,000 by 40,000 array of 400 million cells, which uses gigabytes of memory, while most cells are zero. Keep X sparse, wrap it with Sparse2Corpus(X, documents_columns=False), and pass id2word=dict(enumerate(vectorizer.get_feature_names_out())).