BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Tokenization and NLP5 of 38 in topic

349. Build a bag-of-words count matrix over a fixed vocabulary

EasyTokenization and NLP
Asked atApple

Why it matters Count vectors are still strong baselines for text classification and are the input to TF-IDF and topic models.

A bag-of-words matrix is the input to Naive Bayes, logistic regression text classifiers and TF-IDF. Each row is a document and each column counts one vocabulary word.

Write bow_matrix(docs, vocab). docs is a list of D token lists; vocab is a list of V distinct words. Return an int NumPy array of shape (D, V) where entry [d, v] is how many times vocab[v] appears in docs[d]. Tokens not in vocab are ignored.

Functiondef bow_matrix(docs, vocab)

Example 1

Input: bow_matrix([['the', 'cat', 'the'], ['dog']], ['cat', 'dog', 'the'])

Output: [[1, 0, 2], [0, 1, 0]]

Constraints

  • Python 3 with NumPy. Code runs in your browser.
  • Your code must pass all 3 tests to be accepted.
Hint 1

Map each word to its column with a dict, then add 1 for every token occurrence that is in the dict.

Hint 2

Give every vocab word a column index.

Hint 3

Loop over tokens, not unique tokens.

Hint 4

Skip tokens that have no column.

Common mistakes
  • Deduplicating tokens, which gives binary features instead of counts.
  • Building the vocab from the documents in a different order than the one given.
Understand the idea

Bag of words represents a document by how many times each vocabulary word appears, ignoring order. 'the cat the' and 'the the cat' get the same vector. It is simple, but with a linear model it is a strong baseline for spam and topic classification.

Worked example

vocab [cat, dog, the]. Document 1 is the, cat, the: cat appears once, dog zero times, the twice, so its row is [1, 0, 2]. Document 2 is dog: [0, 1, 0].

M[d, v] = number of positions i with docs[d][i] == vocab[v]

Words outside the vocab are dropped (or sent to an UNK column if you keep one).

Spam filters, Naive Bayes classifiers, TF-IDF search and topic models such as LDA start from this matrix.

Topics
Tokenization and NLP
Companies1
  • Apple a candidate reported this question Apple Machine Learning Engineer Interview Questions | Screna AI

From public interview reports and guides. Not affiliated with or endorsed by these companies.

Similar questions
  • Score words by TF-IDFEasy
  • Encode text with a byte fallback so no character is ever unknownEasy
  • Normalize text by lowercasing, stripping accents and collapsing spacesEasy
  • Count word n-grams and return the k most frequent with stable tiesEasy
All Tokenization and NLP problems
Report
349 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
import numpy as np
​
def bow_matrix(docs, vocab):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 3 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS