TF-IDF Score
Compute TF-IDF scores for terms across documents.
For each term in each document:
- TF (Term Frequency):
- IDF (Inverse Document Frequency):
- TF-IDF = TF × IDF
where is the total number of documents and is the natural logarithm.
Return the vocabulary (sorted) and the TF-IDF matrix, rounded to 4 decimal places.
Example
documents = ["the cat", "the dog", "the bird"]
(['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]])
- Input:
documentsholds 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
theandcatappears once out of 2 words, so . Absent words have . - IDF:
theis in all 3 documents, so . Each animal word is in just 1 document, so . - TF-IDF: for
catin document 1, ; forthe, . Rounded to 4 decimal places, row 1 is[0.0, 0.5493, 0.0, 0.0], and rows 2 and 3 put0.5493underdogandbird. - Notice the
thecolumn 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