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

Signaturedef tf_idf(docs)

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. Worked example: 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. Rule: score = (count in doc / doc length) x ln(N / df). TF-IDF powered classic search engines and is still a strong text baseline.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: doc 0tf_idf(_docs)[0]
  • Sample 2: doc 1 counts repeats in tf onlytf_idf(_docs)[1]
  • Test 3: word everywhere scores 0tf_idf([['x', 'y'], ['x']])[0]