345. Score words by TF-IDF
Before embeddings, search engines ranked words by TF-IDF: a word matters in a document if it appears there often but appears in few documents overall.
Write tf_idf(docs) where docs is a list of token lists. Return a list of dicts, one per document, mapping each word in that document to:
tf = count of the word in the doc / number of tokens in the doc
idf = log(N / df) where N is the number of docs and df is how many docs contain the word (natural log)
score = tf * idf
def tf_idf(docs)Example 1
Input: tf_idf([['the', 'cat', 'sat'], ['the', 'dog', 'dog', 'ran'], ['a', 'cat', 'ran']])[0]
Output: {'the': 0.135155, 'cat': 0.135155, 'sat': 0.366204}
Example 2
Input: tf_idf([['the', 'cat', 'sat'], ['the', 'dog', 'dog', 'ran'], ['a', 'cat', 'ran']])[1]
Output: {'the': 0.101366, 'dog': 0.549306, 'ran': 0.101366}
Constraints
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
Hint 1
First pass: document frequency with a set per doc.
Hint 2
Second pass: counts per doc.
Common mistakes
- The buggy version counts 'dog' twice.
Understand the idea
TF-IDF scores how important a word is to one document. TF (term frequency) is how often the word appears in that document, as a share of its tokens. IDF (inverse document frequency) is high when few documents contain the word and zero when every document has it. Like a rare spice that tells you more about a dish than salt does.
docs [[dog, dog, cat], [cat, fish]], N = 2. In doc 0, dog has tf = 2/3, appears in 1 document, idf = ln(2/1) = 0.693, score 0.462. cat has tf = 1/3 but appears in both documents, idf = ln(2/2) = 0, score 0. In doc 1, fish has tf = 1/2, idf 0.693, score 0.347; cat again 0. Document frequency counts documents, not occurrences, so dog's df is 1 even though it appears twice.
score = (count in doc / doc length) x ln(N / df)
TF-IDF powered classic search engines and is still a strong text baseline.
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.
Similar questions
- 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
- Build a bag-of-words count matrix over a fixed vocabularyEasy