Algorithmcore
CombSUM and CombMNZ
Also called CombMNZ, CombSUM.
Fuses result lists by summing normalized scores (CombSUM), and in CombMNZ multiplies the sum by the number of lists that retrieved the document.
- Solves
- Rank aggregation
- Time
- O(N + n log n) worst
- Space
- O(N) extra
- Where
- N = the total number of entries in the input runs; n = the number of distinct documents in them
- Model
- Word RAM
- Properties
- not comparison baseddeterministiciterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Edward A. Fox, Joseph A. Shaw, 1994
CombSUM and CombMNZ merge the result lists of several retrieval systems by their scores. CombSUM gives each document the sum of its normalized scores over the lists that retrieved it. CombMNZ multiplies that sum by the number of lists that retrieved the document, so documents that many systems agree on get an extra reward. Edward Fox and Joseph Shaw defined both rules, with four others, for the second TREC conference, and they are the classic score-based methods of rank aggregation, also called data fusion. They need comparable scores, so each list is first normalized, most often by min-max scaling.
In plain words
Several search systems each return a list of documents with scores. The scores of different systems mean different things: one system may give scores from 0 to 1 and another from 5 to 30. So first we rescale each list, for example so that its best document gets 1 and its worst gets 0. Then each document gets the sum of its rescaled scores from all systems that returned it; that is CombSUM. CombMNZ goes one step further and multiplies the sum by the number of systems that returned the document. The idea is that a document found by many different systems is more likely to be relevant than one that only a single system likes, even if that system likes it a lot.
The problem
The input is runs for one query. Each run maps the documents that it retrieved to real scores, higher is better, and usually holds only the top few hundred or thousand documents. A document that a run did not retrieve has no score in it. The output is one ranking of the union of the runs. The scores of different runs need not be on the same scale, and the method does not know how they were made.
The algorithm
COMB(S1, ..., Sm, rule, ν)- 1
for each run l: Ŝl ← ν(Sl) ▷ min-max: (s - min) / (max - min) - 2
for each run l and each document d of Ŝl: append Ŝl(d) to the list of d - 3
for each document d: SUM(d) ← the sum of its list; h(d) ← the length of its list - 4
if rule = MNZ: score(d) ← h(d) · SUM(d) else score(d) ← SUM(d) - 5
return the documents sorted by score, highest first, ties to the smaller id
Line L1 is the normalization. Min-max scaling maps the best document of each run to 1 and the worst retrieved document to 0. Two other common choices are the sum normalization, which shifts the scores so that the lowest is 0 and divides by their sum, and the z-score, which subtracts the mean and divides by the standard deviation. Line L3 counts , the number of runs that retrieved . Fox and Shaw also defined CombMAX, CombMIN and CombMED (the largest, smallest and median score) and CombANZ (the sum divided by , the average of the nonzero scores); the code supports all six.
Example
Take query "sorted array search" on the toy collection. Run is BM25, which retrieves five documents. Run is the second run that the collection supplies for this query. The table shows each step for each document, with scores to 4 places.
| document | 1 | 2 | 8 | 7 | 4 | 6 |
|---|---|---|---|---|---|---|
| , raw | 3.0283 | 1.8893 | 1.6292 | 1.2743 | 0.6896 | none |
| , min-max | 1 | 0.5130 | 0.4018 | 0.2500 | 0 | none |
| , raw | 2.0 | 1.0 | 1.5 | none | 1.0 | 2.0 |
| , min-max | 1 | 0 | 0.5 | none | 0 | 1 |
| 2 | 2 | 2 | 1 | 2 | 1 | |
| CombSUM | 2 | 0.5130 | 0.9018 | 0.2500 | 0 | 1 |
| CombMNZ | 4 | 1.0260 | 1.8035 | 0.2500 | 0 | 1 |
CombSUM returns . CombMNZ returns : documents 8 and 2 double their sums because both runs found them, and they pass document 6, which only run found. Document 4 is in both runs but gets 0 from each, because min-max gives 0 to the lowest document of a run, and so it ends last even under CombMNZ. Without normalization, CombSUM gives , because run has the larger raw scores and decides more of the order. With z-scores, document 4 has a negative sum, and CombMNZ doubles it to the lowest score of all.
Correctness
Lines L1 to L5 compute and ; the invariant of line L2 is that after each run, the list of each document holds one normalized score for each run seen so far that retrieved it. The file proofs/correctness.md proves this and three further facts. With min-max, sum or z-score normalization, replacing a run's scores by with does not change the result, so the method does not depend on the scale of any system. With one run, both rules return that run's order. With nonnegative normalized scores, a further run that retrieves never lowers 's score; with z-scores this fails, which is the reason for the pitfall below.
That the rules give good rankings is a measured claim, not a proved one. Fox and Shaw found CombSUM the best of their six rules on their TREC-2 runs. Lee found CombMNZ the best on his runs with min-max scores, and argued that systems tend to retrieve the same relevant documents but different nonrelevant ones, which is what the factor rewards. Cormack, Clarke and Büttcher found reciprocal rank fusion better than CombMNZ on three of four TREC tasks, and CombMNZ slightly better on LETOR 3.
Proof: CombSUM and CombMNZ compute their formulas, and min-max normalization makes them blind to the scale of each runfull
Let be the input runs. Each run maps the documents that it retrieved to real scores, higher is better. A document that a run did not retrieve has no entry in it. For a normalization (one of min-max, sum, z-score or none, as defined in line L1), write . For a document in the union of the runs, let and , and define
Lemma 1 (the code computes the formulas). After line L2, the list stored for holds the values for , one for each run that retrieved , and no other values. Line L3 then sets the score of to for the rule SUM and to for the rule MNZ (line L4), and line L5 returns the union sorted by the fused score, high first, with ties broken by the document id.
Proof. Line L1 replaces each run by its normalized run and keeps the same set of documents. The loop of line L2 visits each pair of a run and a document of that run exactly once and appends the score to the list of that document, so after it the list of is in the order of the runs. Its sum is and its length is , which is what line L3 uses. The other rules of the code (ANZ, MAX, MIN, MED) read the same list.
The value is the number of runs that retrieved . Fox and Shaw define it as the number of nonzero similarities. The two agree when every retrieved document has a nonzero normalized score, which fails for min-max normalization at the lowest document of each run; the page discusses this case.
Theorem 1 (min-max is blind to scale and shift). Let and be real, and replace one run by . With min-max normalization, , so the SUM and MNZ scores of every document, and the output of line L5, do not change. The same holds for the sum normalization and for the z-score normalization.
Proof. Let and . Then and , because keeps the order. If , then . If , both runs have all scores equal and min-max gives 1 to each. For the sum normalization, each shifted score , so the factor cancels in the ratio, and the special case of a zero sum is the same for both. For the z-score, the mean becomes and the standard deviation , so . The other runs do not change, and the sets do not change, so by Lemma 1 nothing else changes.
Without normalization the claim is false: multiplying one run by 10 lets it decide the order alone.
Lemma 2 (one run). With and min-max normalization, SUM and MNZ both return the documents of the run by decreasing score, with equal scores ordered by id.
Proof. Here for every document, so , and min-max is a strictly increasing map of the scores when and a constant map when .
Theorem 2 (more runs never hurt, for nonnegative scores). Suppose all normalized scores are nonnegative, as they are for min-max and sum normalization. If one more run is added that retrieves , then and do not decrease. If the new score of is positive, both strictly increase.
Proof. Adding a run with score for changes to , and to , since both factors grow and are nonnegative. If , the sum grows strictly, and so does the product.
With the z-score, normalized scores can be negative. Then a document with a negative sum loses when another run retrieves it: if with and a new run gives the score , falls from to . The multiplier is meant as a reward, so CombMNZ should be used with a normalization whose values are nonnegative.
The tests in impl/python/test_combmnz.py check each normalization against its definition, each rule against a direct computation of its formula on random runs, Theorem 1 with random and , and the toy runs of the page.
Complexity
Line L1 reads each run twice, once for the minimum and maximum and once to rescale. Lines L2 to L4 touch each entry once with a hash map. So with entries and distinct documents, the time is , where the last term is the sort of line L5, and the extra space is for the lists of scores. SUM and MNZ need only a running sum and a count per document, which brings the extra space to ; only CombMED needs all the values.
Properties
- Uses the scores. Unlike rank-only methods, CombSUM keeps the size of the gaps between documents. A document far ahead in one run keeps that lead.
- Scale free after normalization. With min-max, sum or z-score normalization, a positive affine change of one run's scores changes nothing.
- Rewards overlap. CombMNZ multiplies by , so with runs a document in all of them can gain up to a factor over a document in one.
- Separable. Each run adds its part independently, so runs can be added one at a time, and per-run weights are a one-line change.
- One run is kept. With a single run both rules return its order.
Variants and improvements
- Weighted CombSUM. Multiply each run's normalized scores by a weight learned on training queries. This is a linear combination of systems, the most common form of score fusion in practice.
- Other normalizations. Montague and Aslam compared min-max, sum and z-score normalizations for metasearch. Scores can also be mapped to estimated probabilities of relevance, using training queries, which makes the sum more meaningful.
- Rank-based fusion. When the scores are not available or not trusted, reciprocal rank fusion or the Borda count use the ranks only. A Borda score is CombSUM on scores that are linear in the rank.
- Pairwise fusion. Condorcet fusion and Markov chain rank aggregation use pairwise majorities in place of sums.
- Federated search. When the runs come from different collections, not from different systems on the same collection, the overlap that CombMNZ rewards is rare, and federated search needs other merging methods.
When to use it
Use CombSUM or CombMNZ when the runs search the same collection, their scores carry information beyond the order, and the runs overlap enough that varies. CombMNZ suits a set of runs of similar quality whose relevant documents overlap. Weighted CombSUM suits a case with training queries, where weights can favour the better systems. If the scores are on very different scales, or one run's scores have a long tail that normalization handles badly, a rank-based method such as reciprocal rank fusion is safer.
Pitfalls
- Min-max gives 0 to the bottom. Line L1 with min-max sets the lowest retrieved document of each run to 0, so it adds nothing, and under CombMNZ counts it but multiplies 0. Document 4 in the example is in both runs and still ends last. If being retrieved should count, normalize with the minimum over the whole collection, or add a small constant to every retrieved score.
- Negative scores and the multiplier. With z-scores, line L4 multiplies a negative sum by and so punishes a document for being found by more runs. Use a normalization with nonnegative values for CombMNZ, or shift the z-scores so that the lowest is 0.
- No normalization. If line L1 is skipped, the run with the largest scores decides the order, as the unnormalized example shows. Always state the normalization; results in papers with different choices are not comparable.
- Outliers in min-max. One very high score in a run compresses all other scores of that run toward 0. A robust choice, such as dividing by a high percentile, or the z-score with a shift, can help.
- Counting nonzero scores. Fox and Shaw count the nonzero similarities, while the code counts the retrieved documents. The two differ when a retrieved document has the score 0 after normalization, as the bottom document under min-max does. Say which count you use.
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
# Part of https://algorithm.tamnd.com/combmnz/. The authors are listed in prov/HTFVCS.jsonl.
import statistics
from typing import Any, Hashable, Mapping, Sequence
Run = Mapping[Hashable, float]
def normalize(run: Run, method: str = "minmax") -> dict[Any, float]:
"""Rescale the scores of one run.
minmax maps the lowest score to 0 and the highest to 1 (all scores 1 when they are
equal); sum divides by the sum of the scores after a shift that makes the lowest 0;
zmuv subtracts the mean and divides by the standard deviation; none keeps the scores.
"""
if not run or method == "none":
return dict(run)
lo, hi = min(run.values()), max(run.values())
if method == "minmax":
return {d: (s - lo) / (hi - lo) if hi > lo else 1.0 for d, s in run.items()}
if method == "sum":
tot = sum(s - lo for s in run.values())
return {d: (s - lo) / tot if tot > 0 else 1.0 / len(run) for d, s in run.items()}
if method == "zmuv":
mu = statistics.fmean(run.values())
sd = statistics.pstdev(run.values())
return {d: (s - mu) / sd if sd > 0 else 0.0 for d, s in run.items()}
raise ValueError("method must be minmax, sum, zmuv or none")
def comb_scores(runs: Sequence[Run], rule: str = "MNZ", norm: str = "minmax") -> dict[Any, float]:
"""Return the fused score of each document of the union of the runs.
SUM is the sum of the normalized scores of a document over the runs that retrieved
it, and MNZ is that sum times h(d), the number of runs that retrieved it. MAX, MIN
and MED take the largest, smallest and median normalized score, and ANZ is SUM / h(d).
"""
normed = [normalize(r, norm) for r in runs] # @line L1
seen: dict[Any, list[float]] = {}
for r in normed: # @line L2
for d, s in r.items():
seen.setdefault(d, []).append(s)
out = {}
for d, ss in seen.items(): # @line L3
total, h = sum(ss), len(ss)
if rule == "SUM":
out[d] = total
elif rule == "MNZ":
out[d] = h * total # @line L4
elif rule == "ANZ":
out[d] = total / h
elif rule == "MAX":
out[d] = max(ss)
elif rule == "MIN":
out[d] = min(ss)
elif rule == "MED":
out[d] = statistics.median(ss)
else:
raise ValueError("rule must be SUM, MNZ, ANZ, MAX, MIN or MED")
return out
def comb(runs: Sequence[Run], rule: str = "MNZ", norm: str = "minmax") -> list[Any]:
"""Fuse the runs and return the documents by fused score, high first, ties by id."""
s = comb_scores(runs, rule, norm)
return sorted(s, key=lambda d: (-s[d], d)) # @line L5
irtoy.py 76 lines
# 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
test_combmnz.py 121 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/combmnz/. The authors are listed in prov/HTFVCS.jsonl.
import math
import random
import statistics
import irtoy
from combmnz import comb, comb_scores, normalize
def bm25_q1():
"""BM25 with k1 = 1.2, b = 0.75 and the Lucene idf on q1 of the toy collection."""
q = irtoy.tokenize(irtoy.QUERIES["q1"])
out = {}
for d in irtoy.DOCS:
s = 0.0
for t in q:
f = irtoy.tf(t, d)
if f:
idf = math.log(1 + (irtoy.N - irtoy.df(t) + 0.5) / (irtoy.df(t) + 0.5))
bd = 1 - 0.75 + 0.75 * irtoy.doc_len(d) / irtoy.avgdl()
s += idf * f * 2.2 / (f + 1.2 * bd)
if s:
out[d] = s
return out
def random_runs(rng):
runs = []
for _ in range(rng.randint(1, 5)):
docs = rng.sample(range(1, 11), rng.randint(1, 10))
runs.append({d: round(rng.uniform(-5, 20), 3) for d in docs})
return runs
def close(a, b):
return abs(a - b) < 1e-9
def test_normalizations():
rng = random.Random(1)
for _ in range(300):
run = random_runs(rng)[0]
mm = normalize(run, "minmax")
lo, hi = min(run.values()), max(run.values())
for d in run:
want = (run[d] - lo) / (hi - lo) if hi > lo else 1.0
assert close(mm[d], want)
sm = normalize(run, "sum")
assert close(sum(sm.values()), 1.0)
z = normalize(run, "zmuv")
if len(set(run.values())) > 1:
assert close(statistics.fmean(z.values()), 0.0)
assert close(statistics.pstdev(z.values()), 1.0)
assert normalize(run, "none") == run
def test_rules_match_the_formulas():
rng = random.Random(2)
for _ in range(300):
runs = random_runs(rng)
norm = rng.choice(["minmax", "sum", "zmuv", "none"])
normed = [normalize(r, norm) for r in runs]
union = {d for r in runs for d in r}
for rule in ("SUM", "MNZ", "ANZ", "MAX", "MIN", "MED"):
s = comb_scores(runs, rule, norm)
assert set(s) == union
for d in union:
vals = [r[d] for r in normed if d in r]
h = len(vals)
want = {
"SUM": sum(vals),
"MNZ": h * sum(vals),
"ANZ": sum(vals) / h,
"MAX": max(vals),
"MIN": min(vals),
"MED": statistics.median(vals),
}[rule]
assert close(s[d], want)
assert comb(runs, rule, norm) == sorted(union, key=lambda d: (-s[d], d))
def test_minmax_makes_fusion_blind_to_scale_and_shift():
rng = random.Random(3)
for _ in range(200):
runs = random_runs(rng)
a, b = rng.uniform(0.1, 10), rng.uniform(-50, 50)
moved = [{d: a * s + b for d, s in runs[0].items()}] + runs[1:]
for rule in ("SUM", "MNZ"):
s1 = comb_scores(runs, rule, "minmax")
s2 = comb_scores(moved, rule, "minmax")
for d in s1:
assert abs(s1[d] - s2[d]) < 1e-6
def test_toy_runs():
a = bm25_q1()
b = irtoy.RUN["q1"]
s = comb_scores([a, b], "SUM")
lo, hi = 0.6896, 3.0283
assert abs(s[1] - 2.0) < 1e-9 and abs(s[6] - 1.0) < 1e-9
assert abs(s[8] - ((1.6292 - lo) / (hi - lo) + 0.5)) < 1e-3
assert abs(s[2] - (1.8893 - lo) / (hi - lo)) < 1e-3
assert s[4] == 0.0
assert comb([a, b], "SUM") == [1, 6, 8, 2, 7, 4]
m = comb_scores([a, b], "MNZ")
assert abs(m[1] - 4.0) < 1e-9 and abs(m[8] - 2 * s[8]) < 1e-12 and abs(m[2] - 2 * s[2]) < 1e-12
assert comb([a, b], "MNZ") == [1, 8, 2, 6, 7, 4]
# Without normalization, document 4 rises above 6 and 7 on its raw scores 0.69 and 1.0.
assert comb([a, b], "SUM", "none") == [1, 8, 2, 6, 4, 7]
# With z-scores, MNZ multiplies a negative sum by h = 2, so document 4 falls further.
z = comb_scores([a, b], "MNZ", "zmuv")
assert z[4] < 0 and z[4] == min(z.values())
def test_edge_cases():
assert comb([]) == []
assert comb([{}]) == []
assert comb([{5: 3.0}], "MNZ") == [5]
assert comb_scores([{1: 2.0, 2: 2.0}], "SUM") == {1: 1.0, 2: 1.0}
History
Fox and Shaw described the six combination rules in their paper for TREC-2, which NIST published in 1994; the conference took place in 1993. They combined the runs of several retrieval methods on the same collection and found CombSUM the most effective. Lee, in 1997, normalized each run by min-max scaling, compared the rules again on TREC runs, and found CombMNZ the best; his analysis of overlap, that different systems retrieve similar relevant documents but different nonrelevant ones, became the usual explanation for why CombMNZ works. CombMNZ became the standard baseline for data fusion and was the main score-based method that later rank-based methods, such as reciprocal rank fusion in 2009, were measured against.
References
- Edward A. Fox and Joseph A. Shaw, Combination of multiple searches, The Second Text REtrieval Conference (TREC-2), NIST Special Publication 500-215 (1994), 243-252, the six combination rules CombMAX, CombMIN, CombMED, CombSUM, CombANZ and CombMNZ, with CombMNZ defined as the sum of the similarities times the number of nonzero similarities
- Joon Ho Lee, Analyses of multiple evidence combination, Proceedings of the 20th Annual International ACM SIGIR Conference (SIGIR 1997), 267-276, the min-max normalization of each run and the comparison of the combination rules on TREC runs, in which CombMNZ did best
- Gordon V. Cormack, Charles L. A. Clarke and Stefan Büttcher, Reciprocal rank fusion outperforms Condorcet and individual rank learning methods, Proceedings of the 32nd Annual International ACM SIGIR Conference (SIGIR 2009), 758-759, Tables 2 and 3, where CombMNZ is compared with reciprocal rank fusion and Condorcet fusion on TREC and LETOR 3
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 HTFVCS Edit this page History Report an error Markdown