TensorTonicTensorTonic
Problems
Study PlansProjectsNewInterviewPricingFeedback
Problems
Loading...
1 / 1

Bag-of-Words Vector

NLPFeature Engineering
Easy

Create a bag-of-words count vector for a token sequence and an ordered vocabulary. Output position i stores the number of times vocab[i] occurs in tokens. Ignore tokens outside the vocabulary and return a one-dimensional integer NumPy array.

Loading visualization...

Examples

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

Output: [1, 2, 0, 1]

Explanation: The output follows vocabulary order, and "love" occurs twice.

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

Output: [1, 0]

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

Output: [0, 0]

Hint 1

Build {word: index for index, word in enumerate(vocab)}.

Hint 2

Increment the mapped position only when a token exists in the index dictionary.

Requirements

  • Map each vocabulary token to its output index
  • Count repeated in-vocabulary tokens
  • Ignore tokens that are absent from the vocabulary
  • Return an integer NumPy array of length len(vocab)

Constraints

  • Vocabulary entries are unique strings
  • Tokens and vocabulary may be empty
  • Use NumPy only for the output array
Try Similar Problems
Bleu ScoreTfidf VectorizerWord Count DictBm25Bigram Probabilities

Sign in to take notes on this problem

Case 1
Case 2
Case 3

Accepts: array

Accepts: array

You must run your code first.
PrevNext

Bag-of-Words Vector

NLPFeature Engineering
Easy

Create a bag-of-words count vector for a token sequence and an ordered vocabulary. Output position i stores the number of times vocab[i] occurs in tokens. Ignore tokens outside the vocabulary and return a one-dimensional integer NumPy array.

Loading visualization...

Examples

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

Output: [1, 2, 0, 1]

Explanation: The output follows vocabulary order, and "love" occurs twice.

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

Output: [1, 0]

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

Output: [0, 0]

Hint 1

Build {word: index for index, word in enumerate(vocab)}.

Hint 2

Increment the mapped position only when a token exists in the index dictionary.

Requirements

  • Map each vocabulary token to its output index
  • Count repeated in-vocabulary tokens
  • Ignore tokens that are absent from the vocabulary
  • Return an integer NumPy array of length len(vocab)

Constraints

  • Vocabulary entries are unique strings
  • Tokens and vocabulary may be empty
  • Use NumPy only for the output array
Try Similar Problems
Bleu ScoreTfidf VectorizerWord Count DictBm25Bigram Probabilities

Sign in to take notes on this problem

Case 1
Case 2
Case 3

Accepts: array

Accepts: array

You must run your code first.