Skip to content

Unit 7 · Ranked Retrieval and the Vector Space Model

3 h contact · 8 h self study Prerequisites: Units 3 & 4 CLO 5

1. Setting the scene

Scenario: Feast or famine

A case worker types a short query into the Boolean CityDocs search:

  • standard user dlink 650 → 200,000 hits. Nobody reads 200,000 documents.
  • She adds words to narrow it: standard user dlink 650 no card found → 0 hits. The useful documents are gone.

Boolean retrieval forces users to design the perfect query. Ordinary staff will not. They want what web search gives them: the best ten results first.

Guiding questions

  1. How can a document match a query partially?
  2. Should the word the count as much as the word Mordor?
  3. Should a 300 page report beat a one page memo just because it contains more words?

2. Intended learning outcomes

# Outcome Bloom CLO
ILO 7.1 Explain why ranked retrieval is needed and what properties a good scoring function has. UNDERSTAND 5
ILO 7.2 Compute Jaccard, TF, IDF and TF·IDF weights for a small collection. APPLY 5
ILO 7.3 Compute cosine similarity and justify why angle beats Euclidean distance for documents. EVALUATE 5
ILO 7.4 Apply unit and pivoted length normalisation and interpret SMART notation (e.g. ltc). APPLY 5
ILO 7.5 Describe techniques that speed up ranked retrieval (index elimination, champion lists, tiers, clustering, LSH, random projections). UNDERSTAND 5

3. Where we are

flowchart LR
    D["Documents"] --> P["Preprocess<br/>U3"] --> I["Index<br/>U4, U6"] --> S["<b>Score</b><br/>today"] --> T["Top k results"]

Instead of match / no match we ask: how strongly does this document match the query? A ranked retrieval model assigns every document a score \(\text{score}(q, d)\) and sorts by it.

Desirable properties:

  • more matching query terms ⇒ higher score;
  • rare terms matter more than common ones;
  • long documents should not win merely because they contain more words.

4. A naive score: Jaccard similarity

\[ J(A, B) = \frac{|A \cap B|}{|A \cup B|} \]

\(q = \{\text{frodo}, \text{orc}\}\), \(d = \{\text{frodo}, \text{sam}, \text{orc}, \text{sword}\}\) → \(J = 2/4 = 0.5\).

Exercise: compute Jaccard

Pair Query Document
1 car insurance car insurance car accident
2 data science data science data analysis science
3 machine learning deep learning machine learning model
Answers
  1. \(\{car, insurance\}\) vs \(\{car, insurance, accident\}\) → \(2/3\)
  2. \(\{data, science\}\) vs \(\{data, science, analysis\}\) → \(2/3\)
  3. \(\{machine, learning\}\) vs \(\{deep, learning, machine, model\}\) → \(2/4 = 0.5\)

Note pair 1 and 2 score identically even though pair 2's document repeats the query terms: Jaccard ignores frequency.

Limitations: it ignores term frequency, treats all terms as equally important (the = Frodo), and handles document length poorly.

5. From sets to vectors

Level Value per term Example: car / insurance / the
Binary 0 or 1: does the term appear? 1 / 1 / 1
Count tf: how many times? 2 / 4 / 20
Weighted tf·idf: how important? 1.30 / 2.60 / 0.02

This is still bag of words: John is quicker than Mary and Mary is quicker than John get the same vector.

6. Term weighting: TF·IDF

Term frequency: local importance:

\[ \mathrm{tf}_{t,d} = \text{number of occurrences of } t \text{ in } d, \qquad \text{often log-scaled: } 1 + \log \mathrm{tf}_{t,d} \]

Inverse document frequency: global rarity, with \(N\) documents and \(\mathrm{df}_t\) documents containing \(t\):

\[ \mathrm{idf}_t = \log \frac{N}{\mathrm{df}_t} \]

TF·IDF:

\[ w_{t,d} = \mathrm{tf}_{t,d} \times \mathrm{idf}_t \]

A term gets a high weight when it is frequent in this document and rare in the collection.

\(N = 5\), orc appears in 2 documents: \(\mathrm{idf} = \ln(5/2) \approx 0.92\).

\(\mathrm{tf}(\text{orc}, d_1) = 3 \Rightarrow w = 2.76\); \(\mathrm{tf}(\text{orc}, d_2) = 1 \Rightarrow w = 0.92\).

\(N = 5\); Mordor in 1 document, the in all 5; both appear twice in \(d\).

\(w(\text{Mordor}) = 2 \times \ln 5 \approx 3.22\); \(w(\text{the}) = 2 \times \ln 1 = 0\).

IDF eliminates terms that appear everywhere.

\(d_1\) = car insurance, \(d_2\) = car car car car car insurance. Raw TF says \(d_2\) is 5× stronger for car. Log TF: \(1 + \log_{10} 1 = 1\) vs. \(1 + \log_{10} 5 \approx 1.70\). Repetition helps, but with diminishing returns.

Raw versus logarithmic term frequency

\[ w_{t,d} = \begin{cases} 1 + \log_{10} \mathrm{tf}_{t,d} & \text{if } \mathrm{tf}_{t,d} > 0 \\ 0 & \text{otherwise} \end{cases} \]
xychart-beta
    title "Raw tf grows linearly, log tf flattens"
    x-axis "Occurrences tf" [1, 2, 3, 5, 10, 20]
    y-axis "Weight" 0 --> 20
    line [1, 2, 3, 5, 10, 20]
    line [1.0, 1.3, 1.48, 1.7, 2.0, 2.3]

Twenty occurrences are worth 20 times one occurrence under raw TF, but only 2.3 times under log TF. BM25 (Unit 8) goes one step further and puts a hard ceiling on the weight.

7. Documents and queries as vectors

Choose a vocabulary \(t_1, \dots, t_m\). Every document and the query become vectors in the same \(m\) dimensional space:

\[ \vec d = \big(w(t_1,d), \dots, w(t_m,d)\big), \qquad \vec q = \big(w(t_1,q), \dots, w(t_m,q)\big) \]

Why not Euclidean distance?

Take a document \(d\) and create \(d'\) by pasting \(d\) onto itself ten times. \(d'\) has the same content and is equally relevant to any query. But its vector is ten times longer, so the Euclidean distance between \(\vec q\) and \(\vec d'\) is large. The angle between \(\vec d\) and \(\vec d'\), however, is zero.

flowchart LR
    Q["q = [1, 2, 3, 4, 5]"] --- SAME["same direction<br/>angle = 0"] --- D["d = [2, 4, 6, 8, 10]"]
    SAME --- E["but Euclidean distance ≈ 7.4"]

Rank by angle, not by distance.

Cosine similarity

\[ \cos(\vec q, \vec d) = \frac{\vec q \cdot \vec d}{\lVert \vec q \rVert \, \lVert \vec d \rVert} = \frac{\sum_{i} q_i d_i}{\sqrt{\sum_i q_i^2}\,\sqrt{\sum_i d_i^2}} \]

The numerator measures overlap; the denominator normalises away length. With nonnegative weights, cosine ranges from 0 (no shared terms) to 1 (same direction).

Worked example: query database index

d1 database systems use indexes for fast queries · d2 a database stores data in tables · d3 an index helps search engines find documents

Restricting to the query terms (binary weights): \(\vec q = [1,1]\), \(\vec d_1 = [1,1]\), \(\vec d_2 = [1,0]\), \(\vec d_3 = [0,1]\).

Doc \(\vec q \cdot \vec d\) \(\lVert \vec d \rVert\) cosine
d1 2 \(\sqrt 2\) \(2 / (\sqrt2 \cdot \sqrt2) = \mathbf{1.00}\)
d2 1 1 \(1/\sqrt2 = 0.707\)
d3 1 1 \(1/\sqrt2 = 0.707\)

8. Length normalisation

Unit normalisation

Divide a vector by its length: \([3, 4] \to [3/5, 4/5] = [0.6, 0.8]\), and \(\sqrt{0.36 + 0.64} = 1\). Direction (topic) is kept; length is removed.

For unit vectors, cosine is the dot product, and Euclidean distance becomes a function of the angle:

\[ \lVert \hat q - \hat d \rVert^2 = 2 - 2\cos(\hat q, \hat d) \]

So ranking by cosine and ranking by normalised Euclidean distance give the same order.

When cosine normalisation goes too far

Query anti-doping rules Beijing Olympics: d1 is a short, focused article; d2 is a long article with the same relevant content plus other Olympic stories; d3 is short but about the wrong Olympics. Pure cosine normalisation may punish d2 heavily just for being long. Empirically, cosine normalisation tends to overfavour short documents.

Pivoted length normalisation

Soften the length penalty around a pivot, usually the average document length:

\[ \text{pivoted length} = (1 - s)\cdot \text{pivot} + s \cdot \text{doc length}, \qquad \text{score} = \frac{\text{raw score}}{\text{pivoted length}} \]

\(s = 0\) ignores length, \(s = 1\) uses the raw length, \(0 < s < 1\) balances.

Worked example: pivot = 100, s = 0.5, raw score 30 for both

Doc Length Divide by (no pivot) Pivoted length Pivoted score
d1 (short) 50 50 → 0.60 \(0.5\cdot100 + 0.5\cdot50 = 75\) \(30/75 = \mathbf{0.40}\)
d2 (long) 200 200 → 0.15 \(0.5\cdot100 + 0.5\cdot200 = 150\) \(30/150 = \mathbf{0.20}\)

The short document still wins (it is more focused), but by a factor of 2 instead of 4. The same idea returns as the \(b\) parameter of BM25 in Unit 8.

9. Full worked example: Frodo stabs orc

Documents: d1 Frodo accidentally stabbed Sam and then some orcs · d2 Frodo was stabbing regular orcs but never stabbed super orcs · d3 Sam was having a barbecue with some friendly orcs. After stemming, stabs/stabbed/stabbing → stab, orcs → orc.

Step 1: term frequencies (query terms only)

Frodo stab orc
d1 1 1 1
d2 1 2 2
d3 0 0 1
q 1 1 1

Step 2: IDF (\(N = 3\), \(\log_{10}\))

Term df idf
Frodo 2 \(\log_{10}(3/2) = 0.176\)
stab 2 \(0.176\)
orc 3 \(\log_{10}(3/3) = 0\)

orc appears everywhere, so it cannot distinguish documents, so its weight vanishes.

Step 3: TF·IDF vectors: \(\vec q = [0.176, 0.176, 0]\), \(\vec d_1 = [0.176, 0.176, 0]\), \(\vec d_2 = [0.176, 0.352, 0]\), \(\vec d_3 = [0, 0, 0]\).

Step 4: cosine

Doc Cosine Rank Why
d1 1.00 1 same direction as the query
d2 0.95 2 overweights stab relative to the query
d3 0.00 3 no discriminative query term (zero vector → defined as 0)
import math
from collections import Counter

docs = {  # after stemming and stopword removal
    "d1": "frodo stab sam orc",
    "d2": "frodo stab regular orc stab super orc",
    "d3": "sam barbecue friendly orc",
}
query = "frodo stab orc"

N = len(docs)
tokens = {d: t.split() for d, t in docs.items()}
df = Counter(t for toks in tokens.values() for t in set(toks))
idf = {t: math.log10(N / df[t]) for t in df}

def tfidf(toks):
    tf = Counter(toks)
    return {t: tf[t] * idf.get(t, 0.0) for t in tf}

def cosine(u, v):
    dot = sum(w * v.get(t, 0.0) for t, w in u.items())
    nu, nv = (math.sqrt(sum(w * w for w in x.values())) for x in (u, v))
    return dot / (nu * nv) if nu and nv else 0.0

q = tfidf(query.split())
for d, toks in tokens.items():
    v = {t: w for t, w in tfidf(toks).items() if t in q}   # query terms only, as above
    print(d, round(cosine(q, v), 2))      # d1 1.0 · d2 0.95 · d3 0.0
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

raw = ["Frodo accidentally stabbed Sam and then some orcs",
       "Frodo was stabbing regular orcs but never stabbed super orcs",
       "Sam was having a barbecue with some friendly orcs"]
vec = TfidfVectorizer(stop_words="english")
X = vec.fit_transform(raw)
print(cosine_similarity(vec.transform(["Frodo stabs orc"]), X).round(2))
# [[0.43 0.32 0.  ]] : 'stabs'≠'stabbed', 'orc'≠'orcs': preprocessing matters!

scikit-learn uses smoothed IDF, L2 normalisation over the whole vocabulary and no stemming, so the numbers differ: a live demonstration that Unit 3 decisions change Unit 7 rankings.

10. Weighting schemes: SMART notation

A term weight is built from three choices: TF part × IDF part × normalisation.

Letter Term frequency Letter Document frequency Letter Normalisation
n natural: \(\mathrm{tf}\) n none: 1 n none
l logarithm: \(1 + \log \mathrm{tf}\) t idf: \(\log(N/\mathrm{df})\) c cosine
b boolean: 0/1

ltc = log TF, IDF, cosine normalisation:

\[ w_{t,d} = \frac{(1 + \log \mathrm{tf}_{t,d}) \cdot \log \frac{N}{\mathrm{df}_t}}{\text{vector length}} \]

A classic combination is lnc.ltc. Documents: log TF, no IDF, cosine; queries: log TF, IDF, cosine.

11. Making ranked retrieval fast

Scoring the query against all \(N\) documents is too slow. The strategy is to find a small set of candidates first, then score only those.

flowchart LR
    Q["Query"] --> A["All documents<br/>1,000,000"] --> C["Candidates<br/>~2,000"] --> R["Exact scoring<br/>cosine / BM25"] --> K["Top k"]
Technique Idea Risk
Index elimination Only documents containing ≥ 1 query term (union of postings); ignore very low IDF query terms (the, of) none / small
Champion lists For each term, precompute the top \(r\) documents by weight (e.g. Frodo → [d2, d7, d1]); fall back to full postings if too few may miss results
Tiered index Split postings into tiers by importance; search tier 1, go to tier 2 only if too few results may miss results
Preclustering Pick \(\sqrt N\) leaders; attach every doc to its nearest leader; at query time compare only with leaders, then with one cluster (\(\approx 2\sqrt N\) cosines instead of \(N\)) lower recall
LSH (MinHash) Hash similar documents into the same bucket; compare only within buckets approximate
Random projections Reduce long vectors to short bit codes; candidates = similar codes approximate

Worked example: tiered index, need ≥ 3 results for Frodo AND Sam

Term Tier 1 Tier 2 Tier 3
Frodo 2, 19, 24, 126 1, 3, 12, 27 7, 20, 76
Sam 2, 18, 24, 158 1, 6, 69, 126 44, 90

Tier 1 ∩ Tier 1 = {2, 24}: only two results, so extend to tier 2: Frodo {…, 1, 3, 12, 27} and Sam {…, 1, 6, 69, 126} add documents 1 and 126 → {1, 2, 24, 126}.

Worked example: MinHash signature

d1 Frodo and Sam travel to Mordor → 2 word shingles: Frodo and, and Sam, Sam travel, travel to, to Mordor. Apply three hash functions \(h_1, h_2, h_3\) to every shingle and keep the minimum per function:

Shingle \(h_1\) \(h_2\) \(h_3\)
Frodo and 12 44 18
and Sam 7 20 55
Sam travel 31 5 40
travel to 16 33 9
to Mordor 3 28 22

signature(d1) = [3, 5, 9]. The probability that two documents share a MinHash value equals their Jaccard similarity, so near duplicates (d2 Sam and Frodo go to Mordor) land in the same bucket, while d3 The car is parked near Berlin does not.

Worked example: random projection to 2 bits

\(\vec d = [0.2, 0.8, 0.5]\), random vectors \(\vec r_1 = [1, -1, 1]\), \(\vec r_2 = [1, 1, -1]\).

\(\vec d \cdot \vec r_1 = 0.2 - 0.8 + 0.5 = -0.1 < 0 \Rightarrow 0\); \(\vec d \cdot \vec r_2 = 0.2 + 0.8 - 0.5 = 0.5 > 0 \Rightarrow 1\). Code: [0, 1]. Vectors with a small angle get similar bit codes (a "barcode" for direction).

Term at a time scoring

Search engines rarely compute a full cosine against every document. They walk the postings of each query term and add partial scores into accumulators, one per candidate document:

sequenceDiagram
    participant Q as Query
    participant IX as Index
    participant A as Accumulators
    participant H as Top k heap
    Q->>IX: postings(frodo)
    IX-->>A: add to d1, d2, d24
    Q->>IX: postings(sam)
    IX-->>A: add to d2, d6, d24
    A->>A: divide by length
    A->>H: push candidates
    H-->>Q: best k
\[ \text{score}(q, d) = \frac{1}{\lVert \vec d \rVert} \sum_{t \in q \cap d} w_{t,q}\, w_{t,d} \]

Selecting the best \(k\) of \(n\) candidates with a heap costs \(O(n \log k)\) instead of \(O(n \log n)\) for a full sort.

12. Beyond bag of words

  • Phrases in VSM. hot potato ≠ potato hot, but BoW cannot tell. Use a positional index, either as a hard requirement (exact phrase must appear) or a soft one (closer terms score higher).
  • Query parsing / spawning. rising interest rates → try the phrase "rising interest rates" → if too few results, "rising interest" AND "interest rates" → then single terms. Start strict, relax as needed.
  • Document quality. Among similarly relevant documents, prefer high quality: static (clean HTML, reliable source, no OCR noise) and dynamic (e.g. many important pages link to it).

Worked example: aggregating signals: score = 0.6·cosine + 0.2·proximity + 0.2·quality

Doc Cosine Proximity Quality Final
d1 0.90 0.80 0.60 0.82
d2 0.85 0.40 0.95 0.78
d3 0.70 0.95 0.50 0.71

In production, such weights are learned from relevance judgements (learning to rank).

flowchart TB
    subgraph R1["Find"]
      direction LR
      U["User query"] --> P["Parse / rewrite"] --> F["Fetch candidates<br/>from inverted index"]
    end
    subgraph R2["Rank"]
      direction LR
      S["Compute scores<br/>cosine · proximity · quality"] --> R["Return ranking"]
    end
    R1 --> R2

13. Check your understanding

Why does IDF not affect the ranking for a one term query?

Every document's score is multiplied by the same \(\mathrm{idf}_t\), so the order is unchanged. IDF matters when a query has several terms of different rarity.

Show that cosine and normalised Euclidean distance give the same ranking.

For unit vectors \(\lVert \hat q - \hat d\rVert^2 = \lVert\hat q\rVert^2 + \lVert\hat d\rVert^2 - 2\hat q\cdot\hat d = 2 - 2\cos\). Distance decreases exactly when cosine increases.

What does ltc mean?

Logarithmic term frequency, IDF weighting, cosine normalisation.

14. Key takeaways

  • Ranked retrieval scores documents instead of filtering them, curing "feast or famine".
  • TF·IDF: frequent in the document × rare in the collection.
  • Rank by angle (cosine), not Euclidean distance; normalisation removes length bias, and pivoting stops it from overfavouring short documents.
  • Real systems score only candidates (index elimination, champion lists, tiers, clustering, LSH).
  • Final rankings often combine textual relevance, proximity and quality.

If you choose the Vector Space Model for your project, implement TF·IDF weighting and cosine ranking yourself (a library may be used for comparison) and state your weighting scheme in SMART notation. Show at least one query where your preprocessing choices visibly change the ranking.

Further reading

  • Manning, Raghavan & Schütze, Introduction to IR, ch. 6 to 7.
  • Salton, Wong & Yang (1975), A vector space model for automatic indexing, CACM 18(11), 613 to 620.
  • Singhal, Buckley & Mitra (1996), Pivoted document length normalization, SIGIR.