Bag of Words
Build a Bag-of-Words (BoW) representation for a corpus of documents.
Algorithm:
- Build a vocabulary: collect all unique words across all documents, sorted alphabetically
- For each document, create a vector where each element is the count of the corresponding vocabulary word in that document
Input:
- docs: a list of N document strings (lowercase, space-separated words)
Output:
- A tuple (vocabulary, matrix):
- vocabulary: the sorted list of unique words
- matrix: the BoW matrix (list of lists, one row per document)
Example
3 the cat sat the dog sat the cat and the dog
['and', 'cat', 'dog', 'sat', 'the'] [[0, 1, 0, 1, 1], [0, 0, 1, 1, 1], [1, 1, 1, 0, 2]]
- Input:
docsholds three strings of space-separated lowercase words: "the cat sat", "the dog sat" and "the cat and the dog". They hold 11 words, only 5 of them distinct. - Vocabulary: the distinct words are the, cat, sat, dog, and. In alphabetical order they become
['and', 'cat', 'dog', 'sat', 'the']; column of the matrix means "vocabulary word ". - Counting: entry is how many times vocabulary word appears in document . Document 0 has one cat, one sat and one the, giving . Document 1 swaps cat for dog: .
- Repeats add up: document 2 contains the twice, so its last entry is : . In general equals the length of document .
- Output: a pair made of the vocabulary and a matrix (one row per document, one column per word). Notice that word order inside a document is lost: "sat the cat" would produce the same row as document 0.
Constraints
- All words are already lowercase
- Vocabulary is sorted alphabetically
- Each row of the BoW matrix corresponds to a document
- Each column corresponds to a vocabulary word