Bag-of-Words: Counts Over a Fixed Vocabulary

Feature EngineeringEasy+10 XP+10

Bag-of-Words: Counts Over a Fixed Vocabulary

A model needs a fixed-length row of numbers, and documents are different lengths. Bag-of-words solves that by fixing a vocabulary up front and describing every document as "how many times does each vocabulary word appear in it".

The name is the honest part: word order is thrown away completely. "dog bites man" and "man bites dog" produce identical vectors.

Task: write bag_of_words(documents, vocabulary) returning one count row per document.

  • Each document is a string. Lowercase it and split on whitespace.
  • Row position i holds the count of vocabulary[i] in that document. The vocabulary is already lowercase.
  • A word that isn't in the vocabulary is ignored entirely — it adds nothing anywhere, rather than erroring or getting its own column.
  • A vocabulary word that doesn't appear in a document gets 0.
  • Every row has the same length: len(vocabulary).

That fixed width is the whole point, and it's also the catch. Training and serving must use the identical vocabulary in the identical order, or column 7 means one word to the model and a different word to the data — a mismatch that produces no error at all, just quietly wrong predictions.

Examples

documents = ['the cat sat', 'the dog']
vocabulary = ['the', 'cat', 'dog']
returns [[1, 1, 0], [1, 0, 1]]
documents = ['a a a']
vocabulary = ['a', 'b']
returns [[3, 0]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run