Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

TF-IDF and the inverted index

How TF‑IDF weights terms for ranking and how inverted indices store term→posting lists so search engines answer queries quickly.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

TF‑IDF and the inverted index are used everywhere an engineer builds a text search system: TF‑IDF gives a simple, effective weight for ranking documents by relevance, and the inverted index is the data structure that makes query evaluation fast. Together they form the core of many search engines, recommendation components, and IR pipelines (see related topics: Text preprocessing, Vector space model and cosine ranking, Compressing postings lists).

Key ideas

All terms are defined plainly before use.

  • Corpus: the set of all documents you have (denote size by N). Unit: count (unitless). Assumption: corpus content is already tokenised and normalized unless noted.
  • Document: one text unit in the corpus (document ID = docID).
  • Vocabulary: the set of distinct tokens (terms) that appear in the corpus.
  • Term frequency (TF): for a given term t in document d, raw term frequency tf_{t,d} is the number of times t appears in d. Unit: count (unitless).
  • Document frequency (DF): for term t, df_t is the number of documents in the corpus that contain t (count of documents where tf_{t,d} > 0). Unit: count (unitless).
  • Inverse document frequency (IDF): a measure of how rare a term is across documents. A common definition is idf_t = ln(N / df_t). Assumption: df_t >= 1 (terms in vocabulary), N >= 1. IDF is unitless.
  • TF‑IDF weight: for a term t in document d, the weight w_{t,d} = TF_variant(t,d) × IDF_variant(t). This weight is used to build the document vector in a Vector Space Model.

Exact statements and variants (explanation universities expect):

  1. Raw TF: tf_{t,d} = count of t in d. Assumes bag‑of‑words (word order ignored).
  2. Log normalised TF: TF_{t,d} = 1 + ln(tf_{t,d}) if tf_{t,d} > 0, else 0. This reduces the effect of very frequent terms in a document.
  3. Boolean TF: TF_{t,d} = 1 if tf_{t,d} > 0 else 0.
  4. IDF standard: idf_t = ln(N / df_t). If a term appears in every document (df_t = N) then idf_t = 0.
  5. Smoothed IDF: idf_t = ln(1 + N / df_t) or idf_t = ln((N + 1) / (df_t + 1)) + 1 — common variants used to reduce extremes and to handle df_t = 0 for query‑only terms; always state which you use. Note: idf = ln(N / (1 + df_t)) can be negative when df_t = N and is generally avoided unless offset (e.g., +1).

Derivation universities ask for (why TF×IDF):

  • TF reflects importance of a term inside a document; repeated terms usually mean topic relevance.
  • IDF down‑weights terms that are common across many documents because common terms contribute little to discrimination.
  • Multiplying makes a term important only if it is frequent in the document and rare in the corpus.

Inverted index definitions and properties:

  • Inverted index: a mapping from term → postings list. Each posting is an entry for one document containing at least the docID and often additional data: term frequency in that doc, term positions (for phrase queries), and sometimes field/zone weights.
  • Postings list: for term t, the ordered sequence of postings for every document that contains t. Common ordering is by increasing docID.
  • Positional (or full) inverted index: postings store positions (integers) where the term occurs in the document; this supports phrase and proximity queries.

Complexities and assumptions:

  • Lookup of a term’s postings list: O(1) average if a hash map for vocabulary, O(log |V|) if vocabulary stored in a balanced tree; |V| is vocabulary size.
  • Merging two postings lists (to answer AND queries) takes O(|p1| + |p2|) time where |p1|,|p2| are postings list lengths when lists are read sequentially.
  • Space: postings lists dominate space; compression reduces size (see Compressing postings lists).

Diagram to draw for exam answers:

  • Draw a left column box labelled “Vocabulary” with terms listed vertically (term1, term2,...). Draw to the right for each term an arrow to a horizontal box labelled “Postings list for termX” containing entries like (docID, tf, [pos1,pos2,...]). Label docIDs in increasing order. This shows term→postings.

Formulas

tf_{t,d} = number of occurrences of term t in document d — tf unit: count (unitless). Applies for raw counts. TF_{t,d} = 1 + ln(tf_{t,d}) if tf_{t,d} > 0, else 0 — TF unitless. Use when applying log normalisation. TF_{boolean,t,d} = 1 if tf_{t,d} > 0 else 0 — unitless; for Boolean weighting. df_t = number of documents d where tf_{t,d} > 0 — unitless; applies across the corpus. idf_t = ln(N / df_t) — unitless; N is corpus size. Use when df_t >= 1 and no smoothing is applied. idf_{smooth,t} = ln(1 + N / df_t) or idf_{smooth,t} = ln((N + 1)/(df_t + 1)) + 1 — unitless; smoothed variants to reduce extremes and handle df_t = 0 in queries. w_{t,d} = TF_{variant,t,d} * IDF_{variant,t} — TF‑IDF weight. Unitless. DocumentVector_d = [w_{t1,d}, w_{t2,d}, ..., w_{t|V|,d}] — unitless vector representation. cosine(d,q) = (DocumentVector_d · QueryVector_q) / (||DocumentVector_d|| * ||QueryVector_q||) — unitless similarity measure. Use for ranking in Vector Space Model.

Worked examples

Example 1 — compute TF, IDF, TF‑IDF and rank for a query (step by step). Corpus N = 3 documents. Assume lowercasing, tokenisation only, no stemming, no stopword removal. Doc1: the cat sat on the mat Doc2: the dog sat on the log Doc3: cats and dogs are pets

Step 1: token counts (positions starting at 1): Doc1 tokens and counts: the(2 positions 1,5), cat(1 pos 2), sat(1 pos 3), on(1 pos 4), mat(1 pos 6). Doc2 tokens: the(2 pos 1,5), dog(1 pos 2), sat(1 pos 3), on(1 pos 4), log(1 pos 6). Doc3 tokens: cats(1 pos1), and(1 pos2), dogs(1 pos3), are(1 pos4), pets(1 pos5).

Step 2: document frequency df_t for each term: the: df=2; cat:1; sat:2; on:2; mat:1; dog:1; log:1; cats:1; dogs:1; and:1; are:1; pets:1.

Step 3: choose weighting variants: TF = 1 + ln(raw tf) if raw>0, IDF = ln(N/df). Use natural ln. Compute constants: ln(3) = 1.098612; ln(3/2) = ln(1.5) = 0.405465; ln(3/1) = 1.098612. TF for raw=2: 1 + ln2 = 1 + 0.693147 = 1.693147. For raw=1: 1 + ln1 = 1.

Step 4: compute TF‑IDF weights for Doc1 terms (only show terms that appear):

  • the: TF = 1.693147, IDF = 0.405465 => w = 1.693147 * 0.405465 = 0.68629
  • cat: TF = 1.0, IDF = 1.098612 => w = 1.098612
  • sat: TF = 1.0, IDF = 0.405465 => w = 0.405465
  • on: 0.405465
  • mat: 1.098612 (Document vector_d1 = [the:0.68629, cat:1.098612, sat:0.405465, on:0.405465, mat:1.098612])

Step 5: Query q = "cat sat". Treat query TF as raw counts 1 each; TF query = 1, so query weights are IDF×1: cat=1.098612, sat=0.405465.

Step 6: compute cosine similarity between query and Doc1.

  • Dot product q·d1 = (cat)1.0986121.098612 + (sat)0.4054650.405465 = 1.20695 + 0.16441 = 1.37136
  • Norm ||d1|| = sqrt(1.20695 + 0.16441 + 0.47098 + 0.16441 + 1.20695) = sqrt(3.2137) = 1.7927
  • Norm ||q|| = sqrt(1.20695 + 0.16441) = sqrt(1.37136) = 1.1711
  • cosine = 1.37136 / (1.7927 * 1.1711) ≈ 1.37136 / 2.0994 ≈ 0.6532

Do the same quickly for Doc2 (it has sat but not cat): dot product = 0.16441, ||d2|| = 1.7927 -> cosine = 0.0784. Doc3 has zero overlap -> cosine = 0. Result: ranking Doc1 > Doc2 > Doc3. Final answer: Doc1 is most relevant.

Example 2 — build a simple positional inverted index (show postings lists). From the same corpus, produce postings with (docID, tf, positions):

  • the -> [(1,2,[1,5]), (2,2,[1,5])]
  • cat -> [(1,1,[2])]
  • sat -> [(1,1,[3]), (2,1,[3])]
  • on -> [(1,1,[4]), (2,1,[4])]
  • mat -> [(1,1,[6])]
  • dog -> [(2,1,[2])]
  • log -> [(2,1,[6])]
  • cats -> [(3,1,[1])]
  • dogs -> [(3,1,[3])], etc.

Diagram to draw in answer: draw term "sat" on left, arrow to a box containing rows (doc1 | tf=1 | positions[3]) and (doc2 | tf=1 | positions[3]). Label lists sorted by docID.

Common mistakes

  • Forgetting to normalise TF (or forgetting to state you did). Exams penalise not specifying variants.
  • Using log base 10 vs natural log without saying which; give the base used.
  • Off‑by‑one in position numbering when building positional indexes.
  • Treating plurals (cat vs cats) as same token without explicit stemming — state preprocessing assumptions.

For your exam

Question types you will see: short definitions (TF, IDF, inverted index), derivations (show why tf×idf works), numericals (compute TF‑IDF and cosine similarity for small corpus), construction tasks (draw inverted index/postings lists, show positions), and complexity/space questions (time to merge postings, storage dominated by postings). A full‑marks answer must: state preprocessing assumptions (tokenisation, case, stemming), state which TF/IDF variant is used, show stepwise computation (counts → TF → IDF → weights), carry units (counts are unitless), and for index drawing label docIDs, positions and ordering.

Quick check

  1. Define document frequency and explain its role in IDF.
  2. How is a postings list ordered for efficient merging on AND queries and why?
  3. If a term appears in every document, what is the standard idf value and what does that imply for TF‑IDF ranking? Answers: 1) df_t = number of documents containing term t; it measures term commonness and appears in idf (idf = ln(N/df_t)) to downweight common terms. 2) Postings lists are ordered by increasing docID to allow linear‑time merging (two‑finger algorithm) in O(|p1|+|p2|). 3) idf = ln(N/N) = 0 so TF‑IDF weight becomes 0 and the term does not help distinguish documents.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?