TF-IDF Vectorizer
Implement TF-IDF vectorization for a corpus of documents.
TF (term frequency): tf(t, d) = count of t in d / total words in d IDF (inverse document frequency): idf(t) = log(N / df(t)) where N = total documents, df(t) = documents containing term t.
TF-IDF = tf × idf
Input:
- Line 1: N (number of documents)
- Next N lines: documents (space-separated words, lowercase)
- Last line: query word
Output: TF-IDF score of the query word in each document, one per line, rounded to 4 decimal places.
Example
3 the cat sat the dog sat the cat and dog cat
0.1352 0.0000 0.1352
- We calculate the term frequency () of the query word "cat" in each document:
- Document 1: ,
- Document 2: ,
- Document 3:
- We calculate the inverse document frequency () of the query word "cat":
- ,
- ,
- We calculate the TF-IDF score for the query word "cat" in each document by multiplying and :
- Document 1: ,
- Document 2: ,
- Document 3:
- The final output is the TF-IDF score of the query word in each document, rounded to 4 decimal places, resulting in the given sample output values.
Constraints
- Use natural log (np.log)
- If word not in document, TF-IDF = 0
- If word not in any document, IDF = 0
- Round to 4 decimal places