Skip to the content.

1️⃣ What is TF-IDF?

TF-IDF (Term Frequency – Inverse Document Frequency) is a statistical measure used in information retrieval and text mining to evaluate how important a word is to a document in a collection (corpus).


2️⃣ Components of TF-IDF

(a) TF – Term Frequency

[ TF(t, d) = \frac{\text{Number of times term t appears in document d}}{\text{Total number of terms in document d}} ]


(b) IDF – Inverse Document Frequency

[ IDF(t, D) = \log\frac{N}{1 + DF(t)} ]

Where:


(c) TF-IDF Score

[ \text{TF-IDF}(t, d, D) = TF(t, d) \times IDF(t, D) ]

Example:


3️⃣ Intuition


4️⃣ Use Cases of TF-IDF

  1. Search Engines

    • Rank documents based on query terms
  2. Keyword Extraction

    • Identify important words from text automatically
  3. Text Classification / NLP

    • Convert text into numerical vectors for ML algorithms
  4. Document Similarity

    • Compute cosine similarity between TF-IDF vectors

5️⃣ Example in Python (for clarity)

from sklearn.feature_extraction.text import TfidfVectorizer

corpus = [
    "the cat sat on the mat",
    "the dog chased the cat",
    "cats and dogs are friends"
]

vectorizer = TfidfVectorizer()
tfidf_matrix = vectorizer.fit_transform(corpus)
print(vectorizer.get_feature_names_out())
print(tfidf_matrix.toarray())

6️⃣ Quick Analogy