Algorithmcore
Rocchio algorithm
Also called Rocchio relevance feedback.
Moves the query vector toward the centroid of the relevant documents and away from the centroid of the nonrelevant ones.
- Solves
- Ranked retrieval
- Time
- O(z) worst
- Space
- O(z) extra
- Where
- z = the total number of nonzero weights in the query and the judged document vectors
- Model
- Word RAM
- Properties
- not comparison baseddeterministiciterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Joseph J. Rocchio, 1971
The Rocchio algorithm is the classic method of relevance feedback in the vector space model. After a first search, the user marks some of the results as relevant and some as not relevant. Rocchio builds a new query vector from the old one by adding a multiple of the centroid (the mean vector) of the relevant documents and subtracting a smaller multiple of the centroid of the nonrelevant ones. The new query then runs again. It gains weight on terms that the relevant documents share, including terms that the user never typed, and loses weight on terms of the nonrelevant ones. Joseph Rocchio described it in 1971 for the SMART system.
In plain words
A short query often misses good documents because they use other words. After the first search, the user looks at a few results and says which ones are good and which are bad. Each document is a list of word weights. Rocchio takes the average of the good documents and adds it to the query, so the query now also asks for the words that the good documents have in common. It takes the average of the bad documents and subtracts a small part of it, so words that only the bad documents use count less. Words that end up with a negative weight are dropped. The new query then runs again, and documents that look like the good ones move up, even if they do not share a word with the first query.
The problem
The input is a query vector over the vocabulary, a set of document vectors that the user judged relevant, a set judged nonrelevant, and three weights . The vectors are sparse: each maps terms to weights, for example term frequencies or tf-idf weights, and most terms have weight 0. The output is a new query vector , which is then used to rank the collection by cosine similarity. Either set of judged documents may be empty.
The algorithm
For a nonempty set , the centroid is .
ROCCHIO(q, Dr, Dn, α, β, γ)- 1
q' ← α · q - 2
if Dr is not empty: q' ← q' + β · c(Dr) - 3
if Dn is not empty: q' ← q' - γ · c(Dn) - 4
remove every term t with q'(t) ≤ 0 - 5
return q'
So , taken term by term. Line L4 is the usual rule: Manning, Raghavan and Schütze write that negative term weights are ignored, that is, set to 0. A common setting, which their book gives as reasonable, is , and . The choice trusts positive feedback more than negative feedback. These values are conventions that came from experiments, not results of a proof.
Example
Take query "sorted array search" on the toy collection, with raw term counts as weights, so has weight 1 on each of its three terms. The first search ranks document 1, "binary search finds a key in a sorted array", first. The user marks document 1 relevant and document 6, "a hash table finds a key in constant expected time", nonrelevant. The table shows the weights after each line, with , and ; the five terms of document 6 that document 1 lacks behave alike, so one column stands for them.
| term | sorted | array | search | a | binary | finds | in | key | hash, table, constant, expected, time |
|---|---|---|---|---|---|---|---|---|---|
| after L1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 |
| after L2 | 1.75 | 1.75 | 1.75 | 1.5 | 0.75 | 0.75 | 0.75 | 0.75 | 0 |
| after L3 | 1.75 | 1.75 | 1.75 | 1.2 | 0.75 | 0.6 | 0.6 | 0.6 | -0.15 |
| after L4 | 1.75 | 1.75 | 1.75 | 1.2 | 0.75 | 0.6 | 0.6 | 0.6 | removed |
The word "a" occurs twice in each of the two documents. The cosine scores of the eight documents before and after feedback are below, to 4 places.
| document | 1 | 2 | 6 | 4 | 8 | 7 | 3 | 5 |
|---|---|---|---|---|---|---|---|---|
| before | 0.5222 | 0.5000 | 0 | 0.1543 | 0.3651 | 0.1826 | 0 | 0 |
| after | 0.8780 | 0.4327 | 0.3461 | 0.3166 | 0.3160 | 0.2663 | 0.1083 | 0 |
The new order is . Document 1 gains, as it should. But document 6, which the user rejected, climbs from a score of 0 to third place. It shares "a", "finds", "key" and "in" with document 1, and these words got positive weight from the relevant document, much more than the small penalty from the nonrelevant one. With the stop words "a" and "in" removed from all vectors, the new query is sorted, array and search at 1.75, binary at 0.75, and finds and key at 0.6. The order becomes , with document 6 sixth at 0.1402, and the scores of document 1 rise from 0.7071 to 0.9084.
Correctness
Lines L1 to L3 compute term by term, and line L4 keeps the positive part; the file proofs/correctness.md proves this, and that scaling all three weights by the same positive number does not change the ranking. It also proves the fact behind the method. If all document vectors have length 1, then among all unit query vectors, the one that maximizes the mean cosine with the relevant documents minus the mean cosine with the nonrelevant ones is the difference of the two centroids, scaled to length 1; the proof writes the objective as a dot product with and applies the Cauchy-Schwarz inequality. Rocchio's update is this optimal query, plus to stay near what the user asked, with .
The theorem is about the judged documents only. That the new query ranks unjudged relevant documents higher is a measured effect. Salton and Buckley compared twelve feedback methods on six collections and found clear gains for the vector methods, with the Ide dec-hi variant, which subtracts only the highest-ranked nonrelevant document, the best overall in their tests.
Proof: The Rocchio update computes its formula, and the difference of centroids is the best unit queryfull
Vectors are sparse maps from terms to real weights; a missing term has weight 0. For a nonempty finite set of vectors, the centroid is . Let be the query vector, the judged relevant documents, the judged nonrelevant documents, and . The Rocchio update is
where a term for an empty set is left out, and the clamped query is with , stored as the terms with .
Lemma 1 (the code computes the formula). Lines L1 to L3 build , and line L4 with clamping builds .
Proof. After line L1 the map holds for each term of . The function centroid adds for each weight of each vector in , so it returns on its nonzero terms. Line L2 adds to the entry of , creating it with 0 if needed, and line L3 subtracts in the same way. So after line L3, every term with is in the map with value , and every term not in the map has . Line L4 keeps exactly the entries with a positive value, which are the nonzero coordinates of .
Lemma 2 (only the ratios matter). For , the parameters give and . Ranking by cosine similarity, or by dot product, gives the same order for a query and its positive multiple.
Proof. The update is linear in , and for . The cosine of with equals the cosine of with , and the dot product is multiplied by for every document.
Theorem 1 (optimal query). Let and be nonempty, and let
be the mean dot product of a query with the relevant documents minus its mean dot product with the nonrelevant ones. If , then among all with , is maximized exactly by
and the maximum is . This is a positive multiple of the Rocchio update with , and no clamp.
Proof. The dot product is linear, so with . By the Cauchy-Schwarz inequality, for a unit vector , with equality exactly when is a nonnegative multiple of , that is, .
When all document vectors are scaled to length 1, the dot product with a unit query is the cosine similarity, so is the unit query that best separates the two judged sets by mean cosine. The theorem says nothing about documents that were not judged; that the new query also ranks unseen relevant documents higher is an empirical claim. The full Rocchio update adds , which keeps the new query near the user's words, and uses , which trusts the nonrelevant set less. These are choices, not consequences of the theorem.
Lemma 3 (clamping). If all document weights are nonnegative, then for every document , and is the nonnegative vector closest to in the Euclidean norm.
Proof. For each term, because and ; sum over . For the second claim, the squared distance to a nonnegative is , and each term is minimized separately over by .
So the clamp cannot lower any dot product, and it removes exactly the evidence that a term marks nonrelevant documents: a document that holds a clamped term loses its penalty. The ranking can change through these lost penalties, so the page treats the clamp as a deliberate choice.
The tests in impl/python/test_rocchio_algorithm.py check Lemma 1 in exact rational arithmetic on random vectors, with and without the clamp, check Theorem 1 by comparing with and with at random unit vectors, and check the toy example of the page.
Complexity
Line L1 copies the query, and lines L2 and L3 read each nonzero weight of each judged document once and add it into a hash map. So the update takes time and extra space, where is the total number of nonzero weights in and the judged vectors. Line L4 scans the result once. The real cost comes after: the new query can have hundreds of terms, and each term is a posting list to read in the second search, so the second search is much slower than the first. Systems often keep only the terms of largest weight, as the function top_terms of the code does.
Properties
- Linear. The new query is a linear combination of the old query and the two centroids, cut at 0. Adding a relevant document that equals the current centroid of does not change .
- Only ratios matter. Multiplying , and by the same positive number scales the query and leaves the cosine ranking the same.
- Expands the query. Every term of every relevant document gets a positive weight from line L2, so the new query can match documents that share no word with the old one.
- Order of judgments does not matter. The centroids are means, so the result depends on the sets and , not on the order in which the user judged them.
- No feedback, no change. With both sets empty, the result is , which ranks like .
Variants and improvements
- Ide regular and Ide dec-hi. Ide's variants add the relevant vectors without dividing by , and dec-hi subtracts only the top-ranked nonrelevant document. Salton and Buckley found dec-hi the best of the methods they tested.
- Positive feedback only. Setting is common, because nonrelevant documents are many and varied, and their centroid says little about what to avoid.
- Pseudo relevance feedback. Treat the top results of the first search as relevant, with no user, and apply the same update. This is pseudo-relevance feedback; Rocchio with is one of its standard forms.
- Language model feedback. In the language modeling approach, the analogue of Rocchio mixes the query model with a model estimated from the feedback documents, as the relevance model does.
- Term selection. Keep only the top terms by weight, or only terms with a high tf-idf in the relevant set, to bound the cost of the second search and reduce noise.
When to use it
Use Rocchio when you have a vector space retrieval system and some judgments, from users, from clicks, or from a pseudo feedback step, and you want a cheap way to expand the query. It works best when the relevant documents form one cluster in the vector space, so that their centroid is a good representative. It works badly when the relevant documents are of several kinds, such as documents in two languages or about two senses of a word, because their centroid then lies between the clusters and may be close to neither.
Pitfalls
- Stop words and common words. Line L2 gives positive weight to every word of the relevant documents, including "a" and "in". In the example these words lift the rejected document 6 to third place. Remove stop words or use idf weights before the update, not raw counts.
- Keeping negative weights. Without line L4, the new query has negative weights, and a document gets a lower score for containing a term of the nonrelevant set. With cosine similarity this can rank a document below one that shares nothing with the query. Drop the negative weights as in line L4, unless you have tested the other choice.
- Too much feedback weight. A large relative to lets the relevant documents replace the user's query. If the judged documents are about a side topic, the new query follows them. Keep large enough that the original terms stay among the strongest, as sorted, array and search do in the example.
- Evaluating on the judged documents. The judged relevant documents rise after feedback almost by construction. Measure the gain on the documents the user has not seen yet, the residual collection, as Salton and Buckley do.
- Long queries. The new query holds every term of every relevant document, so the second search reads many posting lists. Cut the query to its top terms.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the information retrieval pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy collection of the information retrieval pages.
Eight short documents, four queries with graded judgments and one fixed
run. Tokens are the lower-case words split on spaces, with no stemming
and no stop words. The helper holds only the data and the statistics
tokenize, tf, df, cf, doc_len and avgdl. Scoring and metrics live on the
pages that define them.
"""
DOCS = {
1: "binary search finds a key in a sorted array",
2: "merge sort merges two sorted runs into one sorted array",
3: "an inverted index maps each term to a posting list",
4: "a posting list is a sorted list of document ids",
5: "skip pointers speed up the merge of two posting lists",
6: "a hash table finds a key in constant expected time",
7: "search engines rank documents by a score for the query",
8: "the sorted array of ids is compressed with gap encoding",
}
N = len(DOCS)
QUERIES = {
"q1": "sorted array search",
"q2": "posting list merge",
"q3": "rank documents",
"q4": "quantum circuit",
}
# Graded judgments: 2 is highly relevant, 1 is relevant, absent is 0.
QRELS = {
"q1": {1: 2, 2: 1, 8: 1},
"q2": {5: 2, 4: 1, 3: 1},
"q3": {7: 2},
"q4": {},
}
# A fixed run for the metric pages, as scores per query.
RUN = {
"q1": {1: 2.0, 6: 2.0, 8: 1.5, 2: 1.0, 4: 1.0},
}
def tokenize(text):
"""Lower-case words split on spaces."""
return text.lower().split()
_TOKENS = {d: tokenize(t) for d, t in DOCS.items()}
def tf(term, doc_id):
"""Number of times term occurs in document doc_id."""
return _TOKENS[doc_id].count(term)
def df(term):
"""Number of documents that contain term."""
return sum(1 for toks in _TOKENS.values() if term in toks)
def cf(term):
"""Number of occurrences of term in the whole collection."""
return sum(toks.count(term) for toks in _TOKENS.values())
def doc_len(doc_id):
"""Number of tokens in document doc_id."""
return len(_TOKENS[doc_id])
def avgdl():
"""Average document length in tokens."""
return sum(len(toks) for toks in _TOKENS.values()) / N
rocchio_algorithm.py 47 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rocchio-algorithm/. The authors are listed in prov/SMAEPR.jsonl.
from typing import Any, Hashable, Mapping, Sequence
Vector = Mapping[Hashable, float]
def centroid(docs: Sequence[Vector]) -> dict[Any, float]:
"""Return the mean of sparse vectors, as a dict of the nonzero coordinates."""
out: dict[Any, float] = {}
for v in docs:
for t, w in v.items():
out[t] = out.get(t, 0) + w / len(docs)
return out
def rocchio(
query: Vector,
relevant: Sequence[Vector],
nonrelevant: Sequence[Vector],
alpha: float = 1.0,
beta: float = 0.75,
gamma: float = 0.15,
clamp: bool = True,
) -> dict[Any, float]:
"""Return alpha q + beta centroid(relevant) - gamma centroid(nonrelevant).
The vectors are sparse dicts from terms to weights. An empty set adds nothing. With
clamp=True, terms whose weight is 0 or less are dropped from the new query.
"""
new = {t: alpha * w for t, w in query.items()} # @line L1
if relevant: # @line L2
for t, w in centroid(relevant).items():
new[t] = new.get(t, 0) + beta * w
if nonrelevant: # @line L3
for t, w in centroid(nonrelevant).items():
new[t] = new.get(t, 0) - gamma * w
if clamp: # @line L4
new = {t: w for t, w in new.items() if w > 0}
return new # @line L5
def top_terms(query: Vector, m: int) -> dict[Any, float]:
"""Keep the m terms of largest weight, ties by term."""
keep = sorted(query, key=lambda t: (-query[t], t))[:m]
return {t: query[t] for t in keep}
test_rocchio_algorithm.py 124 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rocchio-algorithm/. The authors are listed in prov/SMAEPR.jsonl.
import math
import random
from fractions import Fraction
import irtoy
from rocchio_algorithm import centroid, rocchio, top_terms
STOP = {"a", "an", "the", "in", "of", "is", "by", "for", "with", "to", "into", "up", "each"}
def tf_vector(d, stop=frozenset()):
v = {}
for t in irtoy.tokenize(irtoy.DOCS[d]):
if t not in stop:
v[t] = v.get(t, 0) + 1
return v
def query_vector(q):
return {t: 1 for t in irtoy.tokenize(irtoy.QUERIES[q])}
def dot(a, b):
return sum(w * b.get(t, 0) for t, w in a.items())
def cosine(a, b):
na, nb = math.sqrt(dot(a, a)), math.sqrt(dot(b, b))
return dot(a, b) / (na * nb) if na and nb else 0.0
def rank(q, stop=frozenset()):
s = {d: cosine(q, tf_vector(d, stop)) for d in irtoy.DOCS}
return sorted(s, key=lambda d: (-s[d], d)), s
def random_vector(rng, terms):
return {t: Fraction(rng.randint(0, 4)) for t in rng.sample(terms, rng.randint(1, len(terms)))}
def test_matches_the_formula_exactly():
rng = random.Random(1)
terms = list("abcdefgh")
for _ in range(300):
q = random_vector(rng, terms)
rel = [random_vector(rng, terms) for _ in range(rng.randint(0, 4))]
non = [random_vector(rng, terms) for _ in range(rng.randint(0, 4))]
al, be, ga = Fraction(1), Fraction(3, 4), Fraction(3, 20)
for clamp in (False, True):
got = rocchio(q, rel, non, al, be, ga, clamp)
for t in terms:
want = al * q.get(t, 0)
if rel:
want += be * sum(d.get(t, 0) for d in rel) / len(rel)
if non:
want -= ga * sum(d.get(t, 0) for d in non) / len(non)
if clamp:
assert got.get(t, 0) == max(want, 0)
assert all(w > 0 for w in got.values())
elif t in got:
assert got[t] == want
else:
assert want == 0
def test_centroid_difference_is_the_optimal_unit_query():
rng = random.Random(2)
dim = 5
for _ in range(100):
def unit():
v = [rng.gauss(0, 1) for _ in range(dim)]
n = math.sqrt(sum(x * x for x in v))
return {i: x / n for i, x in enumerate(v)}
rel = [unit() for _ in range(rng.randint(1, 4))]
non = [unit() for _ in range(rng.randint(1, 4))]
def objective(q):
return sum(dot(q, d) for d in rel) / len(rel) - sum(dot(q, d) for d in non) / len(non)
diff = rocchio({}, rel, non, alpha=0.0, beta=1.0, gamma=1.0, clamp=False)
norm = math.sqrt(dot(diff, diff))
q_opt = {t: w / norm for t, w in diff.items()}
best = objective(q_opt)
assert abs(best - norm) < 1e-9
for _ in range(50):
assert objective(unit()) <= best + 1e-12
def test_empty_feedback_keeps_the_scaled_query():
q = {"x": 2.0, "y": 1.0}
assert rocchio(q, [], []) == q
assert rocchio(q, [], [], alpha=0.5) == {"x": 1.0, "y": 0.5}
assert centroid([{"x": 1.0}, {"y": 3.0}]) == {"x": 0.5, "y": 1.5}
def test_toy_feedback_on_q1():
q = query_vector("q1")
d1, d6 = tf_vector(1), tf_vector(6)
new = rocchio(q, [d1], [d6])
want = {"sorted": 1.75, "array": 1.75, "search": 1.75, "a": 1.2, "binary": 0.75, "finds": 0.6, "in": 0.6, "key": 0.6}
assert new.keys() == want.keys()
for t in want:
assert abs(new[t] - want[t]) < 1e-12
before, _ = rank(q)
after, s = rank(new)
assert before == [1, 2, 8, 7, 4, 3, 5, 6]
# The nonrelevant d6 shares "a", "finds", "key" and "in" with d1 and climbs to rank 3.
assert after == [1, 2, 6, 4, 8, 7, 3, 5]
assert abs(s[1] - 0.8780) < 1e-4 and abs(s[6] - 0.3461) < 1e-4
def test_toy_feedback_on_q1_without_stop_words():
q = query_vector("q1")
new = rocchio(q, [tf_vector(1, STOP)], [tf_vector(6, STOP)])
want = {"sorted": 1.75, "array": 1.75, "search": 1.75, "binary": 0.75, "finds": 0.6, "key": 0.6}
assert new.keys() == want.keys()
after, s = rank(new, STOP)
assert after == [1, 2, 8, 7, 4, 6, 3, 5]
assert top_terms(new, 3) == {"array": 1.75, "search": 1.75, "sorted": 1.75}
History
Rocchio developed the method for the SMART retrieval system that Gerard Salton led, first at Harvard and then at Cornell, and his chapter in the 1971 book on SMART is the usual reference. The update is usually explained by the query that best separates the relevant from the nonrelevant documents, which is the centroid difference of the correctness section. Eleanor Ide studied variants in the same period. In 1990 Salton and Buckley compared the main feedback methods on six collections and showed consistent gains from feedback. The method then became the standard way to expand queries in vector space systems, and the TREC experiments of the 1990s used it in automatic form, with the top results of a first search taken as relevant.
References
- J. J. Rocchio, Relevance feedback in information retrieval, in Gerard Salton (editor), The SMART Retrieval System: Experiments in Automatic Document Processing, Prentice-Hall (1971), the query modification that adds the relevant document vectors and subtracts the nonrelevant ones
- Christopher D. Manning, Prabhakar Raghavan and Hinrich Schuetze, Introduction to Information Retrieval, Cambridge University Press, 2008, Chapter 9, Section 9.1.1 (the Rocchio algorithm, the weights alpha = 1, beta = 0.75 and gamma = 0.15, and the rule that negative term weights are ignored)
- Gerard Salton and Chris Buckley, Improving retrieval performance by relevance feedback, Journal of the American Society for Information Science 41(4) (1990), 288-297, the comparison of twelve feedback methods on six test collections, evaluated on the residual collection, in which the Ide dec-hi variant did best overall
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag SMAEPR Edit this page History Report an error Markdown