v9.1.1
Menu

Bag of Words

easyFREEText RepresentationNLP 1: Foundations

Build a Bag-of-Words (BoW) representation for a corpus of documents.

Algorithm:

  1. Build a vocabulary: collect all unique words across all documents, sorted alphabetically
  2. 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

Input
3
the cat sat
the dog sat
the cat and the dog
Output
['and', 'cat', 'dog', 'sat', 'the']
[[0, 1, 0, 1, 1], [0, 0, 1, 1, 1], [1, 1, 1, 0, 2]]
Reasoning
  • Input: docs holds 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 jj of the matrix means "vocabulary word jj".
  • Counting: entry cijc_{ij} is how many times vocabulary word jj appears in document ii. Document 0 has one cat, one sat and one the, giving [0,1,0,1,1][0, 1, 0, 1, 1]. Document 1 swaps cat for dog: [0,0,1,1,1][0, 0, 1, 1, 1].
  • Repeats add up: document 2 contains the twice, so its last entry is 22: [1,1,1,0,2][1, 1, 1, 0, 2]. In general ∑jcij\sum_j c_{ij} equals the length of document ii.
  • Output: a pair made of the vocabulary and a 3×53 \times 5 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

Learn this in

More from NLP 1: Foundations

solution.py

Test results

Sign in to run your code against the test cases.