v9.1.1
Menu

Bag of Words

easyFREENLP FundamentalsMachine Learning 2

Build a Bag of Words (BoW) representation from a list of documents.

  1. Build a vocabulary of 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

Words are split by spaces and converted to lowercase. Return the vocabulary list and the BoW matrix.

Example

Input
documents = ["the cat sat", "the dog sat", "the cat"]
Output
(['cat', 'dog', 'sat', 'the'], [[1, 0, 1, 1], [0, 1, 1, 1], [1, 0, 0, 1]])
Reasoning
  • Input: documents holds 3 sentences of space-separated words; case is ignored, so "The" and "the" are one word.
  • Vocabulary: the distinct words across all three documents are cat, dog, sat and the. In alphabetical order this gives ['cat', 'dog', 'sat', 'the'], so every document becomes a vector of length V=4V = 4, and position jj always means the same word.
  • Counting: entry xijx_{ij} is how many times vocabulary word jj occurs in document ii. "the cat sat" has one cat, no dog, one sat, one the, giving [1, 0, 1, 1]. "the dog sat" gives [0, 1, 1, 1], and "the cat" has no sat, giving [1, 0, 0, 1].
  • Output: a tuple of the vocabulary and a 3×43 \times 4 matrix (one row per document, one column per word).
  • Notice that each row sums to its document's length (3,3,23, 3, 2), and that word order inside a document is lost: "sat cat the" would map to the same row. A repeated word counts more than once: "a a b" gives 22 for a.

Constraints

  • documents: list of strings
  • Split on spaces, convert to lowercase
  • Vocabulary is sorted alphabetically
  • Return tuple (vocabulary, bow_matrix)
  • bow_matrix: 2D list (n_docs x vocab_size)

Learn this in

More from Machine Learning 2

solution.py

Test results

Sign in to run your code against the test cases.