Build a bag-of-words count matrix over a fixed vocabulary
Why it matters Count vectors are still strong baselines for text classification and are the input to TF-IDF and topic models.
A bag-of-words matrix is the input to Naive Bayes, logistic regression text classifiers and TF-IDF. Each row is a document and each column counts one vocabulary word.
Write bow_matrix(docs, vocab). docs is a list of D token lists; vocab is a list of V distinct words. Return an int NumPy array of shape (D, V) where entry [d, v] is how many times vocab[v] appears in docs[d]. Tokens not in vocab are ignored.
def bow_matrix(docs, vocab)Example
bow_matrix([['the', 'cat', 'the'], ['dog']], ['cat', 'dog', 'the']) is [[1, 0, 2], [0, 1, 0]].
Understand the idea
Bag of words represents a document by how many times each vocabulary word appears, ignoring order. 'the cat the' and 'the the cat' get the same vector. It is simple, but with a linear model it is a strong baseline for spam and topic classification.
Worked example: vocab [cat, dog, the]. Document 1 is the, cat, the: cat appears once, dog zero times, the twice, so its row is [1, 0, 2]. Document 2 is dog: [0, 1, 0].
Rule: M[d, v] = number of positions i with docs[d][i] == vocab[v]. Words outside the vocab are dropped (or sent to an UNK column if you keep one).
Spam filters, Naive Bayes classifiers, TF-IDF search and topic models such as LDA start from this matrix.