Rank documents for a query with smoothed TF-IDF and cosine similarity

Why it matters TF-IDF cosine search is still the keyword half of hybrid RAG retrieval and a strong baseline for document ranking.

Before vector databases, keyword search ranked documents by the cosine between TF-IDF vectors. Smoothed IDF keeps words that appear in every document from getting a weight of zero.

Write tfidf_search(docs, query, k). docs is a list of N token lists, query a token list. The vocabulary is every word in docs. For each doc, tf is the raw count of each word. idf(w) = ln((1 + N) / (1 + df(w))) + 1 where df(w) is the number of docs containing w. Doc vector = tf * idf, then L2 normalized (an all-zero vector stays zero). The query vector is built the same way from its counts and the same idf (query words not in the vocabulary are ignored). Score = dot product of the normalized vectors.

Return a list of the top k (doc_index, score) pairs, sorted by score descending, then doc_index ascending.

Signaturedef tfidf_search(docs, query, k)

Example

tfidf_search([['cat', 'sat'], ['dog', 'sat'], ['cat', 'cat', 'ran']], ['cat'], 2) is about [(2, 0.8356), (0, 0.7071)].

Understand the idea

TF-IDF weighs a word by how often it appears in a document (tf) times how rare it is across documents (idf). Cosine similarity compares two weighted vectors by angle, so long documents do not win just by having more words.

Worked example: 3 docs, query 'cat'. df(cat) = 2, so idf(cat) = ln(4 / 3) + 1 = 1.288; idf(sat) = 1.288; idf(ran) = idf(dog) = ln(4 / 2) + 1 = 1.693. Doc 0 is cat and sat with equal weights, so its unit vector has 0.7071 on cat. Doc 2 has cat twice (2.575) and ran once (1.693); its norm is 3.082, so the cat part is 0.8356. The query is a unit vector on cat, so scores are 0.8356 for doc 2 and 0.7071 for doc 0.

Rule: w(t, d) = count(t, d) * (ln((1 + N) / (1 + df(t))) + 1), then score = cos(v_q, v_d).

Hybrid RAG systems mix this kind of keyword score with embedding similarity.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: exampletfidf_search([['cat', 'sat'], ['dog', 'sat'], ['cat', 'cat', 'ran']], ['cat'], 2)
  • Sample 2: word in every doctfidf_search([['the', 'gpu', 'is', 'fast'], ['the', 'cpu', 'is', 'slow'], ['the', 'gpu', 'gpu', 'kernel']],...
  • Test 3: unknown query wordstfidf_search([['a', 'b'], ['b', 'c']], ['zzz', 'c'], 2)
  • Test 4: no match keeps index ordertfidf_search([['x'], ['y']], ['q'], 2)