🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

TF-IDF: Ranking Words by Scarcity

Classical NLPText RepresentationđŸŸĸ Free Lesson

Counting alone cannot tell you what matters

Take two documents that both mention database twelve times and ask which one is about databases. Frequency answers immediately, and frequency is wrong as often as it is right — a corpus where every document says database twelve times has gained nothing from the word, while a document that mentions kubernetes exactly once may be the only one in the collection that is actually about Kubernetes. The insight behind TF-IDF is that a term's importance is the product of two independent judgements: how much the term dominates this document, and how rarely the corpus lets it dominate anything.

The result is a weighting scheme, not a segmentation scheme. TF-IDF does not decide where tokens begin and ends; it takes an existing tokenization and rescales the columns of the resulting matrix so that rare, concentrated terms tower over common, diffuse ones. That single rescaling turned out to be strong enough to power web search ranking for two decades, and it remains the strongest baseline you can fit in under a second.

This lesson derives both halves of the score, implements them without any library, then compares the smoothing and length-normalization variants that production retrieval systems actually ship.

The two halves of the score

Term frequency measures dominance inside one document. Raw counts over-weight long documents, so the usual form divides by the document length, and a sublinear variant takes 1 + log(tf) to acknowledge that the difference between five and fifty occurrences of a word is much less informative than the difference between zero and one.

Inverse document frequency measures surprise across the collection. If a term appears in every document, its IDF is log(N / N) = log(1) = 0, and it contributes nothing at all. If it appears in one document out of a thousand, IDF is log(1000) ≈ 6.9, and it dominates the vector. The multiplication then keeps only terms that are both locally dominant and globally rare.

ComponentFormulaAnswersSensitivity
Raw TFcount of t in dHow often does t occur here?Linear in document length
Normalized TFcount divided by lengthWhat share of d is t?Length invariant
Sublinear TF1 plus log of countDid t dominate d?Compresses repeats
Classic IDFlog of N over dfHow surprising is t?Zero when df equals N
Smoothed IDFlog of 1 plus N over 1+df, plus 1Same, never zeroSafe for unseen terms
BM25 IDFlog of N minus df over df plus 0.5Same, with a floorBounded below

Computing the score by hand first

The arithmetic below is deliberately written with nothing but the standard library, so that every number the library prints later can be traced back to a rule you have already executed.

python
import math
from collections import Counter

def tf(document):
    total = len(document)
    return {w: c / total for w, c in Counter(document).items()}

def idf(documents, smooth=True):
    n = len(documents)
    out = {}
    vocab = set(w for d in documents for w in d)
    for w in vocab:
        df = sum(1 for d in documents if w in d)
        if smooth:
            out[w] = math.log(1 + n / (1 + df)) + 1
        else:
            out[w] = math.log(n / df)
    return out

def tfidf(documents, smooth=True):
    weights = idf(documents, smooth)
    return [
        {w: f * weights[w] for w, f in tf(d).items()}
        for d in documents
    ]

docs = [
    ["sql", "index", "query", "database", "query"],
    ["sql", "query", "plan", "optimizer", "index"],
    ["canvas", "brush", "palette", "painting"],
]
for i, vec in enumerate(tfidf(docs, smooth=False)):
    top = sorted(vec.items(), key=lambda kv: -kv[1])[:4]
    print(i, [(w, round(s, 3)) for w, s in top])

Run it and sql and index score well in the first two documents while painting scores highest in the third — but note also that sql, appearing in two of three documents, is being discounted relative to palette, which appears once. That discount is the entire mechanism.

Smoothing, sublinear scaling, and BM25

Work the arithmetic on one concrete pair before trusting the code. Suppose a corpus of one thousand documents holds the term gadget in ten of them, so IDF is the log of one hundred, which is about 4.6. If gadget then appears three times in a twelve-word note, raw TF is 0.25, normalized TF is 0.25, and the resulting weight is 1.15. Now let it appear three times in a two-hundred-word essay: raw TF falls to 0.015 and the weight drops to 0.07, even though the term carried identical local emphasis. Dividing by length is what keeps a short note from outranking a long report merely for being concise, and the sublinear variant additionally ensures that going from three occurrences to thirty adds a little rather than ten times as much.

Three refinements account for most of the gap between a textbook implementation and one you can put behind a search endpoint. Smoothing prevents a term from acquiring an infinite or zero weight when document frequencies are extreme. Sublinear scaling stops a single repeated keyword from dominating a long document. Length normalization makes scores comparable across documents of different sizes.

BM25 combines all three and adds a saturation parameter that controls how quickly the contribution of additional occurrences flattens out, plus a document-length correction that pulls long documents toward the average length.

python
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer

corpus = [
    "The database index speeds up the query planner",
    "Query the database and inspect the execution plan",
    "Oil paint on canvas for beginners",
]
vec_smooth = TfidfVectorizer(sublinear_tf=True, norm="l2")
X = vec_smooth.fit_transform(corpus)
print("vocab:", vec_smooth.get_feature_names_out())
print("idf of 'database':", round(vec_smooth.idf_[3], 3))
print("matrix:\n", np.round(X.toarray(), 3))

# BM25-style scoring without a library
def bm25_score(query, doc, k1=1.5, b=0.75):
    qf = Counter(query)
    df = Counter(doc)
    dl, avg = len(doc), 8.0
    score = 0.0
    for term, q in qf.items():
        tf_ = df.get(term, 0)
        if not tf_:
            continue
        idf_ = math.log(1 + (100 - 50 + 0.5) / (50 + 0.5))
        score += q * idf_ * tf_ * (k1 + 1) / (
            tf_ + k1 * (1 - b + b * dl / avg)
        )
    return score

print("bm25:", round(bm25_score(["database", "query"], ["database", "query", "plan"]), 3))

The k1 and b defaults — 1.5 and 0.75 — are not sacred, but they are a sane starting point: k1 sets where saturation begins and b sets how strongly length is penalized.

Reading a fitted matrix as a ranking tool

Once the matrix exists, retrieval is a vector operation. Encode the query with the same fitted vectorizer, take the cosine similarity between the query row and every document row, and sort. Because the rows are L2-normalized by default, the dot product already is the cosine, which is why a sparse matrix multiply is all a production indexer needs.

python
from sklearn.metrics.pairwise import cosine_similarity

documents = [
    "Postgres btree indexes and query planning",
    "Kubernetes rolling deploys with health checks",
    "Banana bread without refined sugar",
    "Query performance and index selectivity",
]
query = "index for faster queries"

vec = TfidfVectorizer(ngram_range=(1, 2), sublinear_tf=True)
matrix = vec.fit_transform(documents + [query])
sims = cosine_similarity(matrix[-1], matrix[:-1])[0]

for rank, (i, s) in enumerate(sorted(enumerate(sims), key=lambda t: -t[1]), 1):
    print(f"{rank}. {s:.3f}  {documents[i]}")

Two details decide whether this works in practice. First, the query must be vectorized by the fitted transformer, never by a separately fitted one — different vocabularies produce different column orders and silently scrambled scores. Second, n-grams in the query only help if the same n-grams exist in the corpus; adding bigrams to the query but not the corpus adds columns of pure zeros.

Where TF-IDF stops being enough

TF-IDF matches on surface tokens. It cannot connect car with automobile, cannot follow a query phrased differently from the document, and cannot rank a passage that answers a question without using any of the question's words. Vocabulary mismatch is not an edge case; it is the normal condition of natural language, and it is precisely the gap that dense embeddings and later transformers were built to close. The practical answer in modern systems is hybrid retrieval: run BM25 for exact and rare-term matches, run a dense retriever for paraphrase, and fuse the two rankings.

💡Check your IDF for a degenerate corpus

If a term's IDF comes out at exactly zero, it appears in every document and is contributing nothing but compute. Printing sorted(vec.idf_)[:10] after fitting is the fastest way to spot stopwords your analyzer forgot to remove.

Common Mistakes

Fitting one vectorizer on the corpus and another on the query

Fix: Fit once, then call transform for both; column order must be identical or scores are meaningless.

Using raw counts instead of length-normalized TF for retrieval

Fix: Long documents win every ranking by sheer volume; normalize rows or switch to BM25 length correction.

Applying IDF without smoothing on a small corpus

Fix: A term in a single document can drive IDF to an extreme weight; use log(1 + N/(1+df)) + 1.

Tuning k1 and b against a single query

Fix: Evaluate on a graded relevance set, since BM25 parameters trade precision against recall differently per corpus.

Best Practices

  • Normalize rows to unit length before any cosine-based ranking step
  • Apply sublinear_tf=True for prose corpora where repeated terms are mostly stylistic
  • Keep the vectorizer, vocabulary, and IDF table versioned together with the index
  • Pair BM25 with a dense retriever and fuse ranks rather than choosing one outright

Interview Questions

Q1: Why is IDF computed as a logarithm rather than a plain ratio?

Because the ratio N over df spans orders of magnitude, and the log compresses that range so a term in one document out of a million does not swamp the term frequency half by itself.

Q2: What happens to a term that appears in every document?

Its classic IDF is log of one, which is zero, so it contributes nothing to any vector; smoothed variants keep a small positive weight instead to avoid the hard zero.

Q3: How does BM25 improve on plain TF-IDF?

It saturates term frequency with k1 so extra occurrences add less, penalizes document length with b, and floors IDF so no term can contribute a negative score.

Key Takeaways

  • TF-IDF multiplies local dominance by global surprise, keeping terms that are frequent here and rare elsewhere
  • Normalized or sublinear TF stops document length and keyword stuffing from dominating the score
  • Smoothed IDF prevents zero and infinite weights on small or degenerate corpora
  • Cosine similarity on L2-normalized rows reduces retrieval to a single sparse matrix product
  • Surface matching cannot bridge paraphrase, which is why hybrid BM25 plus dense retrieval is now the default
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert NLP Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement