v9.1.1
Menu

TF-IDF Score

easyPRONLP FundamentalsMachine Learning 2

Compute TF-IDF scores for terms across documents.

For each term in each document:

  • TF (Term Frequency): count of term in doctotal terms in doc\frac{\text{count of term in doc}}{\text{total terms in doc}}
  • IDF (Inverse Document Frequency): ln⁡Nnumber of docs containing term\ln\frac{N}{\text{number of docs containing term}}
  • TF-IDF = TF × IDF

where NN is the total number of documents and ln⁡\ln is the natural logarithm.

Return the vocabulary (sorted) and the TF-IDF matrix, rounded to 4 decimal places.

Example

Input
documents = ["the cat", "the dog", "the bird"]
Output
(['bird', 'cat', 'dog', 'the'], [[0.0, 0.5493, 0.0, 0.0], [0.0, 0.0, 0.5493, 0.0], [0.5493, 0.0, 0.0, 0.0]])
Reasoning
  • Input: documents holds N=3N = 3 short texts, each split into words: "the cat", "the dog", "the bird". Every document has exactly 2 words.
  • Vocabulary: the distinct words in alphabetical order are bird, cat, dog, the. They are the 4 columns; each of the 3 rows is one document.
  • TF: in "the cat", each of the and cat appears once out of 2 words, so TF=12TF = \frac{1}{2}. Absent words have TF=0TF = 0.
  • IDF: the is in all 3 documents, so IDF=ln⁡33=ln⁡1=0IDF = \ln\frac{3}{3} = \ln 1 = 0. Each animal word is in just 1 document, so IDF=ln⁡31=ln⁡3≈1.0986IDF = \ln\frac{3}{1} = \ln 3 \approx 1.0986.
  • TF-IDF: for cat in document 1, 12×1.0986=0.5493\frac{1}{2} \times 1.0986 = 0.5493; for the, 12×0=0\frac{1}{2} \times 0 = 0. Rounded to 4 decimal places, row 1 is [0.0, 0.5493, 0.0, 0.0], and rows 2 and 3 put 0.5493 under dog and bird.
  • Notice the the column is all zeros: a word that appears in every document cannot tell documents apart, so its IDF wipes it out.

Constraints

  • documents: list of strings (split on spaces, lowercase)
  • Return tuple (vocabulary, tfidf_matrix)
  • tfidf_matrix: 2D list (n_docs x vocab_size)
  • Use natural log (ln), round to 4 decimal places

More from Machine Learning 2

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.