Computing Vector Scores

Ranking a collection by cosine similarity without comparing the query with every document. Term-at-a-time scoring with accumulators, precomputed document lengths, selecting the top K with a heap, a tested implementation, both evaluation orders traced on the running example, and the shortcuts used when exact scores are too expensive, with index elimination, champion lists and cluster pruning measured on Cranfield.

CosineScore computes exact cosine scores while reading only the postings of the query's terms. It adds $w_{t,q}\,w_{t,d}$ to a per-document accumulator one term at a time, divides by document lengths stored at indexing time, and keeps the top $K$ in a min-heap. For $J$ scores in random order the heap's root is replaced $K(H_J - H_K) \approx K \ln(J/K)$ times. Document-at-a-time evaluation gives the same scores with memory proportional to $K$. On Cranfield (1,400 abstracts, 225 queries, lnc.ltc) exact scoring creates a median of 1,027 accumulators per query, with mean average precision 0.294. Skipping terms with IDF below 0.5, or champion lists of 50, each cost 0.007 of it. Cluster pruning with 37 random leaders did far worse at similar cost (30 seeds).

Cosine similarity put the four documents of this topic's running example in the right order for best car insurance. It did so by a definition that sums over the whole vocabulary, for every document. Computed literally for a collection of millions, that would mean millions of dot products over vectors with hundreds of thousands of dimensions, nearly all of whose components are zero. Yet a search engine answers in milliseconds. How does it compute the same cosines while doing almost none of that work?

Three facts make it possible. A document that shares no terms with the query has a dot product of zero, so it never needs to be examined. The terms it does share are found in the inverted index. And the document lengths do not depend on the query, so they can be computed once at indexing time. The standard algorithm built on these facts is CosineScore (Manning, Raghavan, and Schütze, 2008, §6.3.3).

Here is the route. First we state CosineScore and show why it computes exact cosines. Then we give a tested Python implementation and run it by hand, first on the thesis student's four Arctic sentences and then on the car-insurance running example. Next we select the top results with a heap and compare the two orders in which postings can be read. Finally we measure, on the Cranfield collection, what three of the shortcuts used at scale save and what they cost, and solve four problems on the running example.

The algorithm

CosineScore processes the query one term at a time, accumulating partial scores:

  1. Prepare an accumulator for each document, initially zero, created when the document is first encountered.
  2. For each query term $t$, compute the query weight $w_{t,q}$ and fetch the postings list of $t$.
  3. For each posting $(d, \mathit{tf}_{t,d})$ in that list, compute the document weight $w_{t,d}$ and add $w_{t,d} \times w_{t,q}$ to $d$'s accumulator.
  4. When every query term has been processed, divide each accumulator by the length of its document's vector, read from an array computed at indexing time.
  5. Return the $K$ documents with the largest scores.

After step 3 has run for every query term, each accumulator holds the dot product of the query vector with the document vector. Only terms present in both contribute, and each such term contributes exactly once. Step 4 turns dot products into cosines. Documents containing no query term never receive an accumulator. The work is proportional to the total length of the query terms' postings lists, not to the size of the collection.

A common worry is that skipping most documents must make the scores approximate. It does not. The dot product is a sum over all terms, $\sum_t w_{t,q}\, w_{t,d}$, and the order of a sum does not matter. The naive method sums it document by document. CosineScore sums the same products term by term, one row of the term-document matrix per query term, and skips every product in which either factor is zero. It computes exactly the same numbers.

Dividing by the query vector's length is unnecessary. It scales every score equally and does not change the ranking.

An implementation

The following Python implementation uses logarithmic term frequency for document weights. For query weights it uses IDF alone, ignoring how many times a term appears in the query. In the SMART notation of variants of TF-IDF this is lnc.btn, a simple choice that keeps the example short.

import heapq
import math
from collections import defaultdict


def cosine_score(query_terms, postings, df, lengths, n_docs, k=10):
    """Term-at-a-time cosine scoring with accumulators.

    postings: {term: [(doc_id, tf), ...]}
    lengths:  {doc_id: Euclidean length of the document's weight vector}
    """
    scores = defaultdict(float)                      # the accumulators
    for term in set(query_terms):
        if term not in postings:
            continue
        w_tq = math.log10(n_docs / df[term])          # query weight: idf
        for doc_id, tf in postings[term]:
            w_td = 1 + math.log10(tf)                 # document weight: log tf
            scores[doc_id] += w_td * w_tq
    for doc_id in scores:
        scores[doc_id] /= lengths[doc_id]             # length normalization
    return heapq.nlargest(k, scores.items(), key=lambda item: item[1])

The document lengths are computed while indexing, as the square root of the sum of the squared document weights.

A worked example: the Arctic sentences

Start with the collection the course has carried since the architecture article: the thesis student's four Arctic sentences and the query arctic climate warming. Analyzed as in the inverted index article (lowercased, the eight-word stop list removed, stemmed with the original Porter algorithm), they have these index terms:

docID Index terms
1 arctic, sea, ic, declin, climat, warm
2 warm, climat, threaten, arctic, seabird, food
3 climat, model, predict, warmer, winter, europ
4 seabird, arctic, field, guid

Every term occurs once in each document that contains it, so every document weight is $1 + \log_{10} 1 = 1$. Documents 1, 2 and 3 have six terms each and length $\sqrt{6} \approx 2.449$. Document 4 has four and length $\sqrt{4} = 2$.

The query is analyzed to arctic, climat and warm, and the query weights are the IDF values. arctic appears in 3 of 4 documents, so its weight is $\log_{10}(4/3) \approx 0.125$. climat also appears in 3, for 0.125. warm appears in 2, for $\log_{10}(4/2) \approx 0.301$.

Example (documents 3 and 4). Documents 3 and 4 each contain one query term with weight 0.125, and document 4 ranks higher once the accumulators are divided by the lengths. It is shorter, so the same query term makes up a larger share of it. The accumulators and scores are:

Document Accumulated dot product Length Score
1 0.125 + 0.125 + 0.301 = 0.551 2.449 0.225
2 0.125 + 0.125 + 0.301 = 0.551 2.449 0.225
4 0.125 2.000 0.062
3 0.125 2.449 0.051

The accumulated dot products, 0.551 and 0.125, are the scores of the architecture article's hand calculation, which ended in two ties. Length normalization breaks one of them. Documents 1 and 2 stay tied, since they contain the same query terms and have the same length.

The example also shows where the work goes. Arctic and climat have the lowest IDF, and their lists supply six of the eight postings read. They alone create the accumulators for documents 3 and 4. Skipping query terms with IDF below 0.2 would read only the two postings of warm and create two accumulators. The top two would still be documents 1 and 2, now each scoring 0.123. A query term that occurs in every document would be the extreme case: with IDF 0, its postings would create accumulators and add nothing to them. Real systems take such shortcuts, as described below.

Tracing the running example

Every term in the Arctic sentences occurs once, so they cannot show term frequency at work. The running example of this topic, introduced in TF-IDF weighting, can. Its postings lists for the query best car insurance, written $(d, \mathit{tf})$, are

  • best: $(d_2, 2), (d_3, 1), (d_4, 2)$
  • car: $(d_1, 1), (d_2, 5), (d_4, 3)$
  • insurance: $(d_1, 1), (d_3, 2)$

with IDFs 0.125, 0.125 and 0.301. The lnc lengths, computed at indexing time from $1 + \log_{10} \mathit{tf}$ over every term of each document, are 1.732, 2.362, 2.208 and 2.937 for $d_1$ to $d_4$. Given these postings, the code above adds to the accumulators as follows. Each entry is $(1 + \log_{10} \mathit{tf}) \times \mathit{idf}$, rounded to three decimals:

After the list of $w_{t,q}$ $d_1$ $d_2$ $d_3$ $d_4$
best 0.125 1.301 × 0.125 = 0.163 0.125 0.163
car 0.125 0.125 0.163 + 1.699 × 0.125 = 0.375 0.125 0.163 + 1.477 × 0.125 = 0.347
insurance 0.301 0.125 + 0.301 = 0.426 0.375 0.125 + 1.301 × 0.301 = 0.517 0.347
÷ length 0.426 / 1.732 = 0.246 0.375 / 2.362 = 0.159 0.517 / 2.208 = 0.234 0.347 / 2.937 = 0.118

The accumulator for $d_1$ does not exist until the second list, since $d_1$ does not contain best. Before normalization $d_3$ leads, because it has two occurrences of insurance. After it, the short headline $d_1$ edges ahead. The top two are $d_1$ and $d_3$, the two documents about car insurance. Running the code confirms it:

import math

docs = {
    'd1': {'car': 1, 'insurance': 1, 'rate': 1},
    'd2': {'auto': 1, 'best': 2, 'car': 5},
    'd3': {'auto': 3, 'best': 1, 'insurance': 2},
    'd4': {'best': 2, 'car': 3, 'loan': 4, 'rate': 3},
}
postings, lengths = {}, {}
for d, counts in docs.items():
    for t, tf in counts.items():
        postings.setdefault(t, []).append((d, tf))
    lengths[d] = math.sqrt(sum((1 + math.log10(tf)) ** 2 for tf in counts.values()))
df = {t: len(p) for t, p in postings.items()}

print(cosine_score(['best', 'car', 'insurance'], postings, df, lengths, len(docs), k=2))
# [('d1', 0.2459...), ('d3', 0.2339...)]

The last line of cosine_score keeps only the best $K$ scores. The next section explains how it finds them.

Selecting the top K

The final step needs only the $K$ best documents, typically 10 to 1,000, not a full sort of every scored document. Selecting them with a heap is cheaper than sorting. A min-heap of size $K$ holds the best documents seen so far. Each new score is compared with the smallest in the heap and replaces it only if larger. Selection then takes $O(J \log K)$ time for $J$ scored documents, against $O(J \log J)$ for a full sort.

Alternatively, a max-heap can be built over all $J$ scores in linear time, and the top $K$ extracted at a cost of $O(\log J)$ each (Manning, Raghavan, and Schütze, 2008, §7.1). Python's heapq.nlargest, used above, implements the first approach.

Example (which end of the heap). To keep the $K$ largest scores, the heap's root holds the smallest of them, so it is a min-heap. The question each new score must answer is "is it better than the worst of the current top $K$?", and a min-heap keeps exactly that worst score at its root, readable in constant time. Only when a new score beats it does the heap change. The new score replaces the root, and the heap order is restored in $O(\log K)$ steps.

For a million matching documents and $K = 10$, a replacement restores a heap about $\log_2 10 \approx 3.3$ levels deep. A full sort needs about $\log_2 10^6 \approx 20$ comparisons per document. Most scores are rejected at the first comparison, and when the scores arrive in random order the number that are not can be computed.

Proposition. Suppose $J$ distinct scores arrive in an order in which every arrangement is equally likely. Then the expected number of scores that replace the root of a min-heap of size $K$ is $K(H_J - H_K)$, where $H_n = 1 + \tfrac{1}{2} + \dots + \tfrac{1}{n}$. That is about $K \ln(J/K)$.

Proof. The first $K$ scores fill the heap. For $j > K$, the $j$-th score replaces the root exactly when it is among the $K$ largest of the first $j$ scores. Among those $j$ scores each is equally likely to be the one that arrived last, so that happens with probability $K/j$. The expected number of replacements is the sum of these probabilities, $\sum_{j=K+1}^{J} K/j = K(H_J - H_K)$. Since $H_n$ is close to $\ln n$ plus a constant, the difference is close to $\ln J - \ln K$.

For $J = 10^6$ and $K = 10$ the exact value is 114.6, against $10 \ln 10^5 \approx 115.1$. Of a million scores, about 115 cause any heap work, and the rest cost one comparison each. The assumption matters. Scores that arrive in increasing order replace the root every time, which is the worst case, and documents arrive in docID order, which need not be random with respect to score.

Term-at-a-time and document-at-a-time

CosineScore is term-at-a-time: it reads one postings list completely, then the next, and keeps an accumulator for every document seen so far. Its memory use grows with the number of documents that contain any query term. For a query with a common term, that can be a large fraction of the collection.

The alternative, compared with it by Turtle and Flood (1995), is document-at-a-time evaluation. Open all of the query terms' postings lists at once and advance through them together in docID order, as in multi-way intersection. Each document's full score is computed when it is reached, and the document is then either placed in the top-$K$ heap or discarded. Only $K$ documents need to be held in memory at a time.

With an upper bound on how much each term can contribute to a score, the algorithm can also skip documents that cannot enter the top $K$. The MaxScore method of Turtle and Flood (1995) and the WAND method of Broder et al. (2003) do this. WAND is a document-at-a-time method by construction, since it moves the cursors of all the query terms together. Implementing BM25 traces a document-at-a-time evaluation with such bounds, and search at scale describes their use for early termination.

The same eight postings of the running example, read in two orders. Term at a time (left) reads the whole list for best, then car, then insurance, and must keep a partial score for every document until the last pass. Document at a time (right) keeps a cursor in each list and finishes one document per step, d1 first. Notice that each document's score is final as soon as its column has been read.
The same eight postings of the running example, read in two orders. Term at a time (left) reads the whole list for best, then car, then insurance, and must keep a partial score for every document until the last pass. Document at a time (right) keeps a cursor in each list and finishes one document per step, d1 first. Notice that each document's score is final as soon as its column has been read.

On the running example with $K = 2$, document-at-a-time evaluation proceeds as follows. At each step the cursors that point at the smallest docID advance together, and that document's score is complete.

Step Document Postings read Score Heap action Heap after (smallest first)
1 $d_1$ car, insurance 0.246 push $d_1$ 0.246
2 $d_2$ best, car 0.159 push $d_2$ 0.159, $d_1$ 0.246
3 $d_3$ best, insurance 0.234 0.234 > 0.159: replace $d_2$ $d_3$ 0.234, $d_1$ 0.246
4 $d_4$ best, car 0.118 0.118 < 0.234: discard $d_3$ 0.234, $d_1$ 0.246

The answer is the same as term-at-a-time, as it must be. What differs is the state kept along the way. Term-at-a-time held four accumulators before it could rank anything. Document-at-a-time never held more than two scored documents and three cursors. On a real collection the difference is between memory proportional to the number of matching documents and memory proportional to $K$.

The trace also shows where skipping comes from. When $d_4$ is reached, the heap's smallest score, 0.234, is the bar to clear. Suppose the system knew in advance that no document lacking insurance can score above, say, 0.2. It could then skip every such document without computing its score. MaxScore and WAND precompute, for each term, the largest contribution it can make to any document. They use these bounds to skip documents, or whole stretches of a postings list, that cannot clear the bar. Dynamic pruning with MaxScore and WAND states both methods in full, traces them, and proves that they return exactly the top $K$, ties included.

Shortcuts when exact scores cost too much

For very large collections, even the postings of a query's terms are too long to process completely. Manning, Raghavan, and Schütze (2008, §§7.1 and 7.2.1) describe heuristics that return the top $K$ documents approximately. They accept a small risk of missing one of the true top $K$ in exchange for much less work:

  • Index elimination. Skip query terms with low IDF, like arctic and climat in the Arctic example, since their contributions are small and their postings lists long. Or consider only documents that contain several of the query terms.
  • Champion lists. For each term, precompute a short list of the $r$ documents with the highest weights for it, and score only documents on the query terms' champion lists (§7.1.3).
  • Static quality ordering. Order postings by a query-independent quality score, such as PageRank, so that processing can stop early with good documents already found (§7.1.4).
  • Impact ordering. Order each postings list by decreasing term frequency instead of by docID, so that the postings that add most to a score come first, and stop reading a list after a fixed number of postings or when the term frequency falls below a threshold (§7.1.5). The lists no longer share one order, so this suits term-at-a-time evaluation. Learned sparse retrieval stores per-term weights set by a trained model in ordinary postings, so its scores are accumulated over postings in the same way.
  • Cluster pruning. Choose about $\sqrt{N}$ documents at random as leaders and attach every other document, as a follower, to the leader nearest to it. At query time, compare the query with the leaders only, then score the followers of the nearest leader, or of the nearest few (§7.1.6).
  • Tiered indexes. Divide each postings list into tiers by term weight, for example documents in which the term occurs more than 20 times in the first tier. Consult lower tiers only if the first returns too few results (§7.2.1).

Three of these are measured below on one collection with one scoring function, so that their costs can be compared.

Index elimination measured

The first measurement is of skipping low-IDF terms: what it saves and what it costs. The Cranfield collection has 1,400 abstracts and 225 queries, with a median of 11 distinct terms per query after stop-word removal. Its queries are full sentences that contain common words of the field. So lnc.ltc scoring term at a time creates a median of 1,027 accumulators per query, for nearly three-quarters of the collection. Skipping query terms below an IDF threshold changes the picture as follows:

Skip terms with IDF below Median accumulators Postings read (all queries) Median overlap with exact top 10 Mean average precision
none (exact) 1,027 465,318 10 0.294
0.5 816 322,731 9 0.287
0.75 563 182,094 8 0.281
1.0 276 78,779 6 0.234
1.5 47 13,191 3 0.140

An IDF of 0.5 corresponds to a term in about a third of the documents, and 1.0 to one in a tenth. Skipping only the commonest terms cuts the postings read by about a third and costs little. Nine of the ten top results are unchanged, and mean average precision falls by 0.007.

Pushed further, the savings keep growing but the results degrade quickly. Terms that occur in a tenth of an abstract collection still carry much of a query's meaning. The right threshold is a trade-off measured on the collection at hand, which is why such shortcuts are tuned with evaluation rather than set by rule.

Champion lists measured

For champion lists, every term's list holds the $r$ documents with the largest lnc weight for that term, with ties broken by docID. A query scores only the union of its terms' champion lists, and each of those documents gets its exact lnc.ltc score. The cost is counted in documents scored, the size of that union:

$r$ Median documents scored Median overlap with exact top 10 (mean) Mean average precision
exact 1,027 10 0.294
10 93 7 (6.97) 0.223
25 216 10 (9.16) 0.268
50 375 10 (9.89) 0.287
100 597 10 (10.00) 0.293

With $r = 50$ a query scores a median of 375 documents, a little over a third of the 1,027 that the exact method scores, and returns the exact top ten for at least half the queries. Mean average precision falls by 0.007, the same loss as the mildest index elimination above. Lists of 10 are too short: three of the true top ten are missing at the median.

The method can fail in a way a table of averages hides. A document can be in the true top $K$ without being among the $r$ heaviest documents for any single query term, if it matches several terms moderately. The fourth worked problem below shows this on the running example.

Cluster pruning measured

For cluster pruning, 37 documents (the nearest whole number to $\sqrt{1400}$) are drawn at random as leaders. Every other document follows the leader with which its lnc vector has the largest cosine. A query is scored against the 37 leaders, and then against the members of the $b_2$ groups whose leaders scored highest. The cost is counted in documents compared with the query, the 37 leaders plus the members of the chosen groups. The leaders are random, so each setting is run with 30 seeds. The table gives the median over the seeds, with the quartiles in brackets:

Groups searched $b_2$ Documents compared (median query) Mean overlap with exact top 10 Mean average precision
1 72 [68, 78] 2.27 [2.17, 2.34] 0.105 [0.094, 0.110]
2 113 [109, 122] 3.42 [3.27, 3.58] 0.140 [0.127, 0.152]
4 209 [199, 221] 4.85 [4.69, 5.01] 0.181 [0.174, 0.192]
8 402 [387, 416] 6.52 [6.34, 6.69] 0.223 [0.214, 0.232]

On this collection cluster pruning does much worse than champion lists at the same cost. Searching one group finds about two of the true top ten. Searching eight groups, about 400 comparisons, reaches the mean average precision that champion lists of 10 reach with 93 documents scored, and champion lists of 50 keep nearly all ten at a similar cost. The quartiles are narrow, so the result does not depend on a lucky or unlucky draw of leaders.

These are measurements on one small collection, not a general ranking of the methods. Two features of Cranfield are relevant, though the experiment does not separate their effects. Its 1,400 abstracts are all about aeronautics, so the groups formed around random leaders are not well separated by subject. And its queries are sentences with a median of 11 terms, so a high-scoring document can lie in a different group from the leader that the query as a whole resembles most. Cluster pruning also differs in kind from the other two shortcuts: it does not use the inverted index at query time at all, only comparisons between vectors. The inverted-file indexes used for approximate nearest-neighbor search over dense vectors follow the same plan, with cluster centers found by k-means in place of random leaders (Jégou, Douze, and Schmid, 2011). Benchmarking vector indexes compares such indexes by the same trade-off measured here, recall against the work done per query.

Ranking does not require exact scores, only the right order at the top. That is why approximate methods are acceptable in practice. Approximation is not the only way to save work. Dynamic pruning, described above, skips a document only when an upper bound on its score shows that it cannot reach the top $K$. Broder et al. (2003) call this safe evaluation. When each term's bound is a true upper bound and the threshold is the smallest score among the current top $K$, WAND returns the exact top $K$ with exact scores. On TREC Web Track data they report 92.6% fewer full evaluations for short queries and 95.2% fewer for long ones than scoring every document that contains a query term, without any loss in precision or recall. Their method also lets the threshold be raised above that score, which skips more documents and can then miss some of the true top $K$ (see search at scale).

Worked problems

The four problems are posed on this topic's running example and on the Cranfield figures above. Their numbers are computed by tools/experiments/vsm/running_example.py and tools/experiments/vsm/cranfield_elimination.py.

Problem 1 (term at a time). Score the running example for the query auto insurance with the article's cosine_score (lnc.btn), showing the accumulators after each postings list.

Solution. The ranking is $d_3$ (0.379), $d_1$ (0.174), $d_2$ (0.127), and $d_4$ never receives an accumulator. The postings lists are auto: $(d_2, 1), (d_3, 3)$ and insurance: $(d_1, 1), (d_3, 2)$. Both terms occur in two of the four documents, so both query weights are $\log_{10}(4/2) = 0.301$. Each posting adds $(1 + \log_{10} \mathit{tf}) \times 0.301$:

After the list of $d_1$ $d_2$ $d_3$
auto 1 × 0.301 = 0.301 1.477 × 0.301 = 0.445
insurance 1 × 0.301 = 0.301 0.301 0.445 + 1.301 × 0.301 = 0.836
÷ length 0.301 / 1.732 = 0.174 0.301 / 2.362 = 0.127 0.836 / 2.208 = 0.379

Four postings are read and three accumulators created. The headline and the car review have the same accumulated dot product, 0.301, each from one occurrence of one query term. Dividing by the lengths separates them: the headline's three terms give it the shorter vector.

Problem 2 (document at a time). Evaluate the same query document at a time with $K = 1$, showing the heap after each step.

Solution. The heap ends holding $d_3$ with 0.379, after one push, one discard and one replacement. The two cursors start at $d_2$ (auto) and $d_1$ (insurance), and at each step the cursors on the smallest docID advance:

Step Document Postings read Score Heap action Heap after
1 $d_1$ insurance 0.174 push $d_1$ 0.174
2 $d_2$ auto 0.127 0.127 < 0.174: discard $d_1$ 0.174
3 $d_3$ auto, insurance 0.379 0.379 > 0.174: replace $d_1$ $d_3$ 0.379

Both lists are then exhausted. The document $d_4$ is in neither list, so no cursor ever points at it. The scores equal those of Problem 1, and the state held at any moment is one scored document and two cursors, against three accumulators there.

Problem 3 (heap work on Cranfield). A Cranfield query creates a median of 1,027 accumulators. If their scores reach the heap in random order, find the expected number that replace the root of a heap of $K = 10$, and compare it with a full sort.

Solution. About 46 of the 1,027 scores change the heap. By the proposition above the expected number is $K(H_J - H_K) = 10\,(H_{1027} - H_{10}) = 45.8$, and the approximation $K \ln(J/K) = 10 \ln 102.7$ gives 46.3. The other 971 or so scores, after the first ten, cost one comparison each. Each replacement moves an entry down a heap of 10, at most $\lfloor \log_2 10 \rfloor = 3$ levels. A full sort of 1,027 scores takes about $\log_2 1027 \approx 10$ comparisons per score. The saving is smaller than in the million-document case of the text, because $J/K$ is only about a hundred.

Problem 4 (a champion list that misses the best document). For the running example and the query best car insurance, build champion lists of $r = 1$ and of $r = 2$ documents per term from the lnc weights, and find the top $K = 2$ each returns.

Solution. With $r = 1$ the method returns $d_3$ and $d_2$ and misses $d_1$, the true first result. With $r = 2$ it returns the exact top two, $d_1$ and $d_3$. The lnc weight of a term in a document is $(1 + \log_{10} \mathit{tf})$ divided by the document's length:

Term Weights by document Champion list, $r = 1$ Champion list, $r = 2$
best $d_2$ 0.551, $d_3$ 0.453, $d_4$ 0.443 $d_2$ $d_2$, $d_3$
car $d_2$ 0.719, $d_1$ 0.577, $d_4$ 0.503 $d_2$ $d_2$, $d_1$
insurance $d_3$ 0.589, $d_1$ 0.577 $d_3$ $d_3$, $d_1$

With $r = 1$ the union of the lists is $\{d_2, d_3\}$. Their exact scores are 0.159 and 0.234 (the trace above), so the result is $d_3$, $d_2$. The headline $d_1$ has the highest exact score, 0.246, but it is second for car and second for insurance and so on no list: it wins by matching two terms moderately well, not one term best. With $r = 2$ the union is $\{d_1, d_2, d_3\}$, which contains both of the true top two, and scoring them gives $d_1$ (0.246) and $d_3$ (0.234). This is the failure described in the measurements: champion lists judge a document one term at a time.

What we have learned

CosineScore computes exact cosines by reading only the postings of the query's terms: accumulate the products term by term, divide by lengths stored at indexing time, and keep the top $K$ in a min-heap. Document-at-a-time evaluation computes the same scores with memory proportional to $K$, and its bounds let it skip documents that cannot win. When even that is too slow, index elimination and its relatives trade a little effectiveness for much less work. On Cranfield, champion lists of 50 and the mildest index elimination each cost 0.007 of mean average precision, and cluster pruning cost far more.

The code used one weighting, lnc.btn, chosen to keep it short. The running example has already met several others, with and without IDF on each side, with and without logarithms. The next article, Variants of TF-IDF Weighting, explains what those letters mean and compares the combinations.

The running-example traces and the Arctic example are computed by tools/experiments/vsm/running_example.py. The code blocks are run and checked, on both examples, by tools/experiments/vsm/check_cosine_score.py. The Cranfield measurements come from tools/experiments/vsm/cranfield_elimination.py (index elimination and champion lists are deterministic; cluster pruning uses seeds 790 to 819), and the figure from tools/figures/computing-vector-scores.py, all in the site repository.

References

  • Broder, A. Z., Carmel, D., Herscovici, M., Soffer, A., and Zien, J. (2003). Efficient query evaluation using a two-level retrieval process. In Proceedings of CIKM 2003, 426–434. record · 3 pages
  • Jégou, H., Douze, M., and Schmid, C. (2011). Product quantization for nearest neighbor search. IEEE Transactions on Pattern Analysis and Machine Intelligence, 33(1), 117–128. record · 6 pages
  • Manning, C. D., Raghavan, P., and Schütze, H. (2008). Introduction to Information Retrieval, sections 6.3.3, 7.1, and 7.2.1. Cambridge University Press. record · 102 pages
  • Turtle, H., and Flood, J. (1995). Query evaluation: Strategies and optimizations. Information Processing and Management, 31(6), 831–850. record · 2 pages

Reviewed: verified, 16 Nov 2026 · checked against sources, 23 Nov 2026 · citations checked, 16 Nov 2026 · editorial review, 23 Nov 2026 · 11 revisions