361. 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.
def tfidf_search(docs, query, k)Example 1
Input: tfidf_search([['cat', 'sat'], ['dog', 'sat'], ['cat', 'cat', 'ran']], ['cat'], 2)
Output: about [(2, 0.8356), (0, 0.7071)]
Example 2
Input: docs = [['the', 'gpu', 'is', 'fast'], ['the', 'cpu', 'is', 'slow'], ['the', 'gpu', 'gpu', 'kernel']], query = ['the', 'gpu'], k = 3
Output: [(2, 0.817033), (0, 0.608324), (1, 0.211733)]
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
Hint 1
Build a count matrix, scale columns by idf, divide each row by its norm (guard zeros), do the same for the query, and sort by -score then index.
Hint 2
Build a document by word count matrix first.
Hint 3
Multiply columns by idf, then normalize rows to unit length.
Hint 4
Vectorize the query with the same vocab and idf, dot, and sort.
Common mistakes
- Using unsmoothed idf, which zeroes words present in every doc.
- Forgetting to normalize, so long documents win.
- Dividing by a zero norm for empty documents.
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.
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.
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.
Topics
Companies1
- Apple a candidate reported this question Apple Machine Learning Engineer Interview Questions | Screna AI
From public interview reports and guides. Not affiliated with or endorsed by these companies.