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.
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]
Create a dictionary mapping each vocab word to its index for fast lookup.
Initialize a zero array with np.zeros(), then iterate through tokens to increment counts.
Sign in to take notes on this problem
Accepts: array
Accepts: array
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.
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]
Create a dictionary mapping each vocab word to its index for fast lookup.
Initialize a zero array with np.zeros(), then iterate through tokens to increment counts.
Sign in to take notes on this problem
Accepts: array
Accepts: array