Problems
Loading...
1 / 1

Bag-of-Words Vector

NLPFeature Engineering
Easy

Given a fixed vocabulary (ordered list of words) and a tokenized sentence, build a bag-of-words (BoW) count vector as a NumPy array. Index i in the output corresponds to vocab[i] and contains the count of that word in the sentence.

Loading visualization...

Examples

Input: tokens = ["i", "love", "ml", "love"], vocab = ["i", "love", "hate", "ml"]

Output: [1, 2, 0, 1]

Index 0=i:1, 1=love:2, 2=hate:0, 3=ml:1

Input: tokens = ["hello", "world"], vocab = ["hello", "ml"]

Output: [1, 0]

"world" is ignored (not in vocab)

Input: tokens = [], vocab = ["hello", "world"]

Output: [0, 0]

Hint 1

Create a dictionary mapping each vocab word to its index for fast lookup.

Hint 2

Initialize a zero array with np.zeros(), then iterate through tokens to increment counts.

Requirements

  • Output must be a 1D NumPy array of integers
  • Words not in vocab are ignored
  • Multiple occurrences of a word are counted
  • The order of vocab defines the index mapping

Constraints

  • 0 ≤ len(tokens) ≤ 10,000
  • 1 ≤ len(vocab) ≤ 5,000
  • NumPy required
Try Similar Problems