liveBook · Manning

Inverse document frequency

As explained in AI Agents in Action, Second Edition

Inverse document frequency is a logarithmic measure of how uncommon a term is across a document collection.

Inverse document frequency (IDF) measures how uncommon a term is across a document collection. Within TF-IDF, it gives more weight to distinctive words and less to words appearing throughout the corpus. section 6.1.3

Use this mental model:

  • Term frequency asks how often a word appears in one document. section 6.1.3
  • IDF offsets common words by considering their frequency across the document set. section 6.1.3
  • TF-IDF measures term importance, not meaning: “vehicles” does not match “cars” merely because they are synonymous. section 6.1.3
Listing 6.1 document_vector_similarity (transform to vector)
import plotly.graph_objects as go
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

documents = [     #1
    "The sky is blue and beautiful.",
    "Love this blue and beautiful sky!",
    "The quick brown fox jumps over the lazy dog.",
    "A king's breakfast has sausages, ham, bacon, eggs, toast, and beans",
    "I love green eggs, ham, sausages and bacon!",
    "The brown fox is quick and the blue dog is lazy!",
    "The sky is very blue and the sky is very beautiful today",
    "The dog is lazy but the brown fox is quick!"
]

vectorizer = TfidfVectorizer()    #2
X = vectorizer.fit_transform(documents)   #3

Inspect a minimal Python example that transforms a document collection with scikit-learn’s TfidfVectorizer before comparing document vectors. section 6.1.3

How AI Agents in Action, Second Edition covers it

How deep it goes
Defines IDF within TF-IDF and contrasts term counting with semantic embeddings, without explaining embedding internals.
Examples
Uses sample sentences focused on “blue” and a small collection containing sky, fox, dog, eggs, ham, and bacon.
What you can do after
Apply it via scikit-learn’s TfidfVectorizer to transform documents into sparse vectors for similarity search.
How it connects
Connects IDF to term frequency, TF-IDF, sparse vectors, cosine similarity, vector similarity search, and semantic embeddings.

Also explained in

Compare how 4 books explain inverse document frequency →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of AI Agents in Action, Second Edition. The section links point to the parts of the book it draws on.