349. Build a bag-of-words count matrix over a fixed vocabulary
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.
def 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.
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
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.