Algorithmadvanced
Markov chain rank aggregation
Also called MC4 aggregation, Dwork-Kumar-Naor-Sivakumar aggregation.
Builds a Markov chain that moves from an item to one that a majority of rankings prefer, and ranks items by its stationary distribution.
- Solves
- Rank aggregation
- Time
- O(n^2 k + n^2 t) worst
- Space
- O(n^2 + n k) extra
- Where
- k = the number of lists; n = the number of distinct items in the input lists; t = the number of rounds of power iteration
- Model
- Word RAM
- Properties
- not comparison baseddeterministiciterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Cynthia Dwork, Ravi Kumar, Moni Naor, D. Sivakumar, 2001
Markov chain rank aggregation combines several ranked lists into one by a random walk on the items. Each list is a vote. The walk moves from an item to an item that the lists rank higher, and the final ranking orders the items by how much time the walk spends at each one in the long run, which is the stationary distribution of the Markov chain. Cynthia Dwork, Ravi Kumar, Moni Naor and D. Sivakumar defined four such chains, MC1 to MC4, in 2001 for metasearch, the rank aggregation of the result lists of several search engines. The same paper defines local Kemenization, a cheap clean-up pass that makes any aggregate agree with every strict majority on neighbouring items.
In plain words
Several search engines each give a ranked list of results. We want one list. Put a walker on one of the results. At each step the walker looks at another result and asks the lists which of the two is better. If most of the lists that show both results prefer the other one, the walker moves there, else it stays. Good results pull the walker in and keep it, so after many steps the walker is mostly at good results. We rank the results by how often the walker is at each one. To keep the walker from being stuck in a corner of the graph, it sometimes jumps to a random result, as in PageRank. A last pass then walks down the list and swaps any two neighbours when most lists prefer the lower one.
The problem
The input is ranked lists . Each list holds distinct items, best first, and it may be partial: a search engine returns only its top results, so two lists can hold different items. Let be the union of the items and . The output is one full ranking of . For a list that holds , is the rank of in it. Item beats item , written , when strictly more of the lists that hold both items put above than put above . A list that misses one of the two items does not vote on that pair.
The ideal answer is a Kemeny ranking, which minimizes the total Kendall tau distance to the lists. Finding it is NP-hard, as the Kemeny rank aggregation page explains, so this method gives a fast heuristic answer, with no bound on its distance from the Kemeny optimum.
The algorithm
Line L2 fills one row of the transition matrix for each item . The four chains differ only in the rule that picks the next state.
| chain | next state when the walk is at |
|---|---|
| MC1 | an item chosen uniformly from the multiset of all items that some list holding ranks at or above |
| MC2 | a list chosen uniformly among the lists that hold , then an item chosen uniformly among the items it ranks at or above |
| MC3 | a list chosen uniformly among the lists that hold , then an item chosen uniformly from that list; go to if the list ranks above , else stay at |
| MC4 | an item chosen uniformly from ; go to if , else stay at |
MC4 is the majority chain: it moves only along pairwise majorities. MC3 is the same walk with one list as the judge in place of the majority.
MC-AGGREGATE(τ1, ..., τk, chain, ε)- 1
U ← the union of the items of τ1, ..., τk, in sorted order; n ← |U| - 2
for each P in U: fill row P of M by the move rule of chain - 3
M ← (1 - ε) M + (ε / n) J ▷ J is the n × n matrix of ones - 4
π ← (1/n, ..., 1/n) - 5
repeat π ← π M until the L1 change of π is below tol - 6
return U sorted by π, highest first, ties to the smaller item LOCAL-KEMENIZE(σ, τ1, ..., τk)- 7
for each x of σ, in order: append x to the end of ρ - 8
while x has an upper neighbour y in ρ and x ≻ y - 9
swap x and y in ρ return ρ
Line L3 is the teleport of PageRank: with probability the walk jumps to a uniform random item. Line L5 is power iteration. Lines L7 to L9 are insertion sort with the majority relation as the comparison, but need not be transitive, so the result is not a sorted order in general. The usual use is to run lines L7 to L9 on the output of line L6, or on the output of any other aggregation method.
Example
Take three items and five voters: three lists say and two lists say . The majorities are (3 to 2), (3 to 2) and (5 to 0), so is the Condorcet winner, the item that beats every other item. The Borda count gives 12 points and 11, so it puts first.
For MC4, the walk at never moves, because nothing beats . At it moves to with probability . At it moves to or with probability each. With , line L3 gives the rows , and . The table shows the state of line L5 after each round, to 4 places.
| round | |||
|---|---|---|---|
| 0 | 0.3333 | 0.3333 | 0.3333 |
| 1 | 0.5222 | 0.3333 | 0.1444 |
| 2 | 0.6293 | 0.2798 | 0.0909 |
| 3 | 0.6899 | 0.2343 | 0.0758 |
| 4 | 0.7243 | 0.2042 | 0.0715 |
| 5 | 0.7438 | 0.1860 | 0.0702 |
| 6 | 0.7548 | 0.1753 | 0.0699 |
| 7 | 0.7611 | 0.1691 | 0.0698 |
| 8 | 0.7646 | 0.1656 | 0.0698 |
| limit |
The order is from round 1 on, and it is the Kemeny ranking of this profile (total distance 4, against 5 for the Borda order ). With all the mass ends at , and and both get 0. MC3 on the same lists, with , has the stationary distribution and gives , like Borda. Local Kemenization of inserts , then inserts and swaps it up because , then inserts , which stays because . The result is .
On the two runs of the toy collection for the query "sorted array search", the BM25 list and the second list , MC4 with gives the exact stationary values , , , and . The order is . Document 6 comes second although only one list holds it: that list puts it above 8, 2 and 4, and the other list does not vote on those pairs, so 6 beats each of them 1 to 0. Documents 2 and 8 tie because the two lists disagree on them.
Correctness
The file proofs/correctness.md proves four facts. Every row of is a probability distribution, for each of the four chains. For , line L3 makes the map shrink the distance between two distributions by the factor , so the stationary distribution is unique and the vectors of line L5 are within of it after rounds. With and a Condorcet winner, MC4 makes the winner absorbing and puts all the mass on it. On full lists, one round of MC3 from the uniform vector already gives the Borda order.
For lines L7 to L9 the invariant is that, after each insertion, no item of is directly below an item that it beats. Each swap of line L9 exchanges two neighbours of a full ranking with the lower one beating the upper one, so it lowers the total Kendall distance by at least 1. The output is therefore locally Kemeny optimal, it is never worse than its input, and it satisfies the extended Condorcet criterion: if every item of a set beats every item outside , the items of come first.
The method itself has no approximation guarantee for the Kemeny objective. Its order is the order of a stationary distribution, which is a different objective, and the toy example shows how far apart the two can be on partial lists.
Proof: The chains are stochastic, the teleported chain converges, and local Kemenization is locally optimalfull
Let be rankings of items from the union , with . A ranking may be partial. For a list and an item in it, is its rank, and " puts above " means . Write when strictly more of the lists that rank both and put above than put above . The matrix is the one that line L2 builds, and is the matrix of line L3, where is the matrix of ones.
Lemma 1. For each of MC1 to MC4, every row of is a probability distribution.
Proof. The entries are sums of nonnegative terms, so it is enough to show that each row sums to 1. For MC1 the row of spreads weight on each element of a nonempty multiset ; holds itself, since each list that holds ranks at or above . For MC2 the row is the average, over the lists that hold , of a uniform distribution on a nonempty set. For MC3 the row is the average, over the lists that hold , of a distribution that sends each of the items of either to or to , with weight each. For MC4 each of the items sends weight either to or to . Each item of is in at least one list, so the set of lists that hold is never empty.
The matrix is then stochastic too, because is stochastic and the set of stochastic matrices is convex.
Lemma 2 (contraction). Let . For any two probability row vectors , .
Proof. Let . Its entries sum to 0, so and . For a stochastic , .
Theorem 1. For , has exactly one stationary distribution , and the vectors of line L5, started from the uniform vector of line L4, satisfy .
Proof. The set of probability vectors with the distance is complete, and by Lemma 2 the map is a contraction on it. By the Banach fixed point theorem it has exactly one fixed point , which is a stationary distribution, and no other stationary distribution exists. Since , Lemma 2 gives .
So line L5 stops after at most steps, since , and the order of line L6 is the order of the unique , up to items whose probabilities differ by less than the error.
Theorem 2 (MC4 and a Condorcet winner). Take and the chain MC4. Suppose some item satisfies for every . Then is absorbing, the stationary distribution is unique and equal to the unit vector , and power iteration from any start converges to it.
Proof. From , a move to needs , which fails because and the relation is asymmetric. So the row of is . From any , the chain picks with probability and then moves, because . So for any distribution , the mass off after one step is at most times the mass off before: mass at stays, and each state sends at least to . After steps the mass off is at most , which tends to 0. A stationary is its own image after steps for each , so its mass off is 0, and .
Theorem 3 (MC3 after one step). Let all lists be full rankings of , and let be the total rank of . For MC3 with , one step from the uniform vector gives
So the order of is the order of increasing total rank, which is the Borda order.
Proof. Each list holds each item. From , the chain moves to when it picks a list (probability ) with and then picks (probability ). So . Summing over counts, for each list, the items below : . The chain leaves for when it picks a list with and then , so . Then , which is the formula.
Lemma 3 (one swap). Let be a ranking of in which is directly above , and let be with the two swapped. Then , where is the sum over the lists of the number of pairs that both rank in opposite orders, is the number of lists that rank both and put above , and the number that put above .
Proof. The swap changes the relative order of the pair only. Every other pair keeps its order in , so its disagreements do not change. The pair was a disagreement for the lists before the swap and is one for the lists after.
So means exactly that the swap lowers . A ranking is locally Kemeny optimal when no swap of two neighbours lowers , that is, when no item is directly below an item that it beats.
Theorem 4 (local Kemenization). Lines L7 to L9 return a permutation of the input order such that (a) is locally Kemeny optimal, (b) , and (c) if is a nonempty proper subset with for all and , then the items of are the first items of .
Proof. (a) Invariant: after the step that inserts the -th item of , the output list holds the first items of and no item of it is directly below an item that it beats. It holds after the first step. Assume it before the insertion of . The new item starts at the bottom and moves up only past a neighbour that it beats. When it stops, its upper neighbour (if any) is not beaten by . Its lower neighbour (if any) is the item it passed last, so and, by asymmetry, does not beat . The pair is no longer adjacent. All other adjacent pairs were adjacent before, in the same order, so the invariant holds.
(b) Consider the full ranking that has the current output list on top and the items of not yet inserted below it, in the order of . At the start it is , and at the end it is . Appending the next item does not change it. Each swap in line L9 exchanges two neighbours of this full ranking, with the lower one beating the upper one, so by Lemma 3 it lowers by .
(c) Suppose not. Then some is above some in . Walk down from to : the walk starts outside and ends inside , so at some step an item is directly above an item . By hypothesis , which contradicts (a).
Each of the four theorems is checked on random small inputs in impl/python/test_markov_chain_rank_aggregation.py, with Theorem 1 compared against an exact solve of over the rationals.
Complexity
Line L2 takes time for each of the four chains with a position map for each list: MC4 asks each list about each pair of items, and MC1 to MC3 scan, for each item, the lists that hold it. Each round of line L5 is a vector times a dense matrix, time. By the contraction bound, rounds reach the tolerance, so with and at most 190 rounds are needed. Line L6 sorts in . The total is time and extra space for the matrix and the position maps. Lines L7 to L9 make comparisons in the worst case, each a count over the lists, so time as written; the paper notes a faster way that uses comparisons.
Properties
- Majority driven. MC4 depends on the lists only through the majority relation . Two profiles with the same majorities give the same chain, however large the margins are.
- Condorcet consistent at . A Condorcet winner takes all the mass. With it gets the largest share in the examples above, but the theorem covers only .
- Handles partial lists. No chain needs a full ranking. A list votes only on items that it holds.
- Deterministic. The chain and the tie rule of line L6 depend only on the input. The walk is a way to define the scores; nothing in the computation is random.
- Not a metric optimum. The output need not minimize the Kendall or the footrule distance, and Dwork and coauthors note that the chains need not satisfy the extended Condorcet criterion, which is why the paper adds local Kemenization.
Variants and improvements
- MC1 to MC3. These chains move to an item that one list ranks higher, with no majority vote. MC1 favours items that many lists hold near the top, and MC3 behaves like a smoothed Borda count, as the one-step result shows.
- Missing items below. A common change is to treat an item that a list misses as ranked below every item it holds. Then that list votes on the pair. On the toy runs this gives , the Borda order, and document 6 no longer climbs on a one-list majority.
- Footrule aggregation. The ranking that minimizes the total Spearman footrule distance to full lists is a minimum weight perfect matching of items to positions, so it can be found in polynomial time, and it is within a factor 2 of the Kemeny optimum by the Diaconis-Graham inequality. The paper uses it as another starting point for local Kemenization.
- Exact stationary vector. For small , solving with by Gaussian elimination gives directly. The test file does this in rational numbers as the reference.
- Other fusion methods. Reciprocal rank fusion and CombMNZ are linear time and need no matrix; they are the common choices when only speed matters.
When to use it
Use MC4 when the lists come from systems whose scores cannot be compared, when you care about pairwise majorities more than about rank positions, and when the number of items to merge is small enough for an matrix, a few hundred to a few thousand. Run local Kemenization on the result, or on the output of any cheaper method, when one bad list must not lift an item above the item that most lists prefer. For large lists of web results, a positional method such as Borda or reciprocal rank fusion is simpler and faster.
Pitfalls
- A majority of one list. The MC4 rule of line L2 counts only the lists that hold both items. An item that appears in one list only beats every item that this list ranks below it, as document 6 does in the toy example. If missing items should count as poor, change line L2 so that a list votes over when it holds and not , as in the variant above.
- No teleport. With , line L3 does nothing, the chain is usually reducible, and line L5 can converge to a vector with many zeros. The order of the items with probability 0 is then only the tie rule of line L6: the toy runs at give , which is document 1 followed by the documents in id order. Keep , or use the zero entries only to find the top item.
- Rounding splits ties. Documents 2 and 8 have the same exact probability, but power iteration gives two floats that can differ in the last bits. Sorting the raw floats in line L6 then orders them by noise. Round the probabilities to well above the tolerance, or compare exact values, before the sort.
- Quadratic memory. The dense matrix of line L2 has entries. Merge only the top of each list, or store MC4 as the majority relation and compute each row when it is needed.
- Local Kemenization keeps the input order. Lines L7 to L9 only repair neighbours. Two items that no majority links stay in the order of the input, so the result still depends on the method that produced it.
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/markov-chain-rank-aggregation/. The authors are listed in prov/DF298Z.jsonl.
from fractions import Fraction
from typing import Any, Hashable, Sequence
Ranking = Sequence[Hashable]
def _union(rankings: Sequence[Ranking]) -> list[Any]:
items = set()
for r in rankings:
items.update(r)
return sorted(items)
def transition_matrix(rankings: Sequence[Ranking], chain: str = "MC4", exact: bool = False) -> tuple[list[Any], list[list[Any]]]:
"""Return (items, M), where M[i][j] is the probability that the chain moves from items[i] to items[j].
Each ranking lists distinct items, best first, and may be partial. The chains are
MC1 to MC4 of Dwork, Kumar, Naor and Sivakumar (2001), with no teleport. With
exact=True the entries are Fractions, else floats.
"""
one = Fraction(1) if exact else 1.0
items = _union(rankings) # @line L1
n = len(items)
idx = {x: i for i, x in enumerate(items)}
pos = [{x: i + 1 for i, x in enumerate(r)} for r in rankings]
m = [[0 * one for _ in range(n)] for _ in range(n)]
for p in items: # @line L2
i = idx[p]
lists_p = [t for t in pos if p in t]
if chain == "MC1":
pool = [q for t in lists_p for q in t if t[q] <= t[p]]
for q in pool:
m[i][idx[q]] += one / len(pool)
elif chain == "MC2":
for t in lists_p:
above = [q for q in t if t[q] <= t[p]]
for q in above:
m[i][idx[q]] += one / len(lists_p) / len(above)
elif chain == "MC3":
for t in lists_p:
for q in t:
target = q if t[q] < t[p] else p
m[i][idx[target]] += one / len(lists_p) / len(t)
elif chain == "MC4":
for q in items:
both = [t for t in pos if p in t and q in t]
wins = sum(1 for t in both if t[q] < t[p])
target = q if q != p and 2 * wins > len(both) else p
m[i][idx[target]] += one / n
else:
raise ValueError("chain must be MC1, MC2, MC3 or MC4")
return items, m
def teleport(m: list[list[Any]], eps: Any) -> list[list[Any]]:
"""Return (1 - eps) M + eps J / n, the chain that jumps to a uniform state with probability eps."""
n = len(m)
return [[(1 - eps) * m[i][j] + eps / n for j in range(n)] for i in range(n)] # @line L3
def stationary(m: list[list[float]], tol: float = 1e-12, max_iter: int = 100000) -> list[float]:
"""Power iteration from the uniform distribution, until the L1 change is below tol."""
n = len(m)
pi = [1.0 / n] * n # @line L4
for _ in range(max_iter):
new = [sum(pi[i] * m[i][j] for i in range(n)) for j in range(n)] # @line L5
if sum(abs(a - b) for a, b in zip(new, pi)) < tol:
return new
pi = new
return pi
def aggregate(rankings: Sequence[Ranking], chain: str = "MC4", eps: float = 0.15) -> list[Any]:
"""Rank the items of the union by the stationary probability of the chain, high first, ties by item.
The probabilities are rounded to 10 decimals before the sort, so that two states with
the same exact probability are not split by rounding noise of the power iteration.
"""
items, m = transition_matrix(rankings, chain)
pi = stationary(teleport(m, eps) if eps > 0 else m)
order = sorted(range(len(items)), key=lambda i: (-round(pi[i], 10), items[i])) # @line L6
return [items[i] for i in order]
def _prefers(pos: Sequence[dict], x: Hashable, y: Hashable) -> bool:
over = sum(1 for t in pos if x in t and y in t and t[x] < t[y])
under = sum(1 for t in pos if x in t and y in t and t[y] < t[x])
return over > under
def prefers(rankings: Sequence[Ranking], x: Hashable, y: Hashable) -> bool:
"""True when strictly more of the rankings that hold both x and y put x above y than y above x."""
return _prefers([{z: i for i, z in enumerate(r)} for r in rankings], x, y)
def local_kemenize(order: Sequence[Hashable], rankings: Sequence[Ranking]) -> list[Any]:
"""Insertion sort of order where an item moves up past its upper neighbour only when a strict majority prefers it."""
pos = [{z: i for i, z in enumerate(r)} for r in rankings]
out: list[Any] = []
for x in order: # @line L7
out.append(x)
j = len(out) - 1
while j > 0 and _prefers(pos, out[j], out[j - 1]): # @line L8
out[j - 1], out[j] = out[j], out[j - 1] # @line L9
j -= 1
return out
test_markov_chain_rank_aggregation.py 228 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/markov-chain-rank-aggregation/. The authors are listed in prov/DF298Z.jsonl.
import itertools
import random
from fractions import Fraction
from markov_chain_rank_aggregation import (
aggregate,
local_kemenize,
prefers,
stationary,
teleport,
transition_matrix,
)
CHAINS = ("MC1", "MC2", "MC3", "MC4")
def exact_stationary(m):
"""Solve pi M = pi with sum(pi) = 1 by Gaussian elimination over Fractions. None if not unique."""
n = len(m)
# Equations: for each j, sum_i pi_i (M[i][j] - [i == j]) = 0; replace the last by sum pi = 1.
a = [[m[i][j] - (1 if i == j else 0) for i in range(n)] + [Fraction(0)] for j in range(n)]
a[n - 1] = [Fraction(1)] * n + [Fraction(1)]
for c in range(n):
p = next((r for r in range(c, n) if a[r][c] != 0), None)
if p is None:
return None
a[c], a[p] = a[p], a[c]
for r in range(n):
if r != c and a[r][c] != 0:
f = a[r][c] / a[c][c]
a[r] = [x - f * y for x, y in zip(a[r], a[c])]
return [a[i][n] / a[i][i] for i in range(n)]
def random_profile(rng, n, k, partial):
items = list(range(1, n + 1))
out = []
for _ in range(k):
r = items[:]
rng.shuffle(r)
if partial:
r = r[: rng.randint(1, n)]
out.append(r)
return out
def kendall(sigma, tau):
"""Pairs ranked by both lists in opposite orders."""
ps = {x: i for i, x in enumerate(sigma)}
pt = {x: i for i, x in enumerate(tau)}
common = [x for x in sigma if x in pt]
return sum(1 for x, y in itertools.combinations(common, 2) if (ps[x] - ps[y]) * (pt[x] - pt[y]) < 0)
def footrule(sigma, tau):
pt = {x: i for i, x in enumerate(tau)}
return sum(abs(i - pt[x]) for i, x in enumerate(sigma))
def total(dist, sigma, profile):
return sum(dist(sigma, t) for t in profile)
def test_rows_are_distributions():
rng = random.Random(1)
for _ in range(200):
prof = random_profile(rng, rng.randint(1, 6), rng.randint(1, 4), partial=True)
for c in CHAINS:
_, m = transition_matrix(prof, c, exact=True)
for row in m:
assert sum(row) == 1 and min(row) >= 0
def test_power_iteration_matches_exact_solve():
rng = random.Random(2)
eps = Fraction(3, 20)
for _ in range(120):
prof = random_profile(rng, rng.randint(2, 5), rng.randint(1, 4), partial=rng.random() < 0.5)
for c in CHAINS:
_, mx = transition_matrix(prof, c, exact=True)
_, mf = transition_matrix(prof, c)
pi_exact = exact_stationary(teleport(mx, eps))
pi_float = stationary(teleport(mf, 0.15))
assert pi_exact is not None
assert sum(pi_exact) == 1
for a, b in zip(pi_exact, pi_float):
assert abs(float(a) - b) < 1e-9
def test_mc4_condorcet_winner_takes_all_mass():
rng = random.Random(3)
seen = 0
for _ in range(300):
n = rng.randint(2, 5)
prof = random_profile(rng, n, rng.choice([1, 3, 5]), partial=False)
items = sorted(prof[0])
winners = [w for w in items if all(prefers(prof, w, y) for y in items if y != w)]
if not winners:
continue
seen += 1
w = winners[0]
its, m = transition_matrix(prof, "MC4", exact=True)
i = its.index(w)
assert m[i][i] == 1
pi = exact_stationary(m)
assert pi == [Fraction(1) if j == i else Fraction(0) for j in range(n)]
assert seen > 100
def test_mc3_one_step_from_uniform_is_borda_order():
rng = random.Random(4)
for _ in range(200):
n, k = rng.randint(2, 6), rng.randint(1, 5)
prof = random_profile(rng, n, k, partial=False)
items, m = transition_matrix(prof, "MC3", exact=True)
step = [sum(Fraction(1, n) * m[i][j] for i in range(n)) for j in range(n)]
for j, x in enumerate(items):
rank_sum = sum(r.index(x) + 1 for r in prof)
assert step[j] == Fraction(1, n) * (1 + Fraction(k * (n + 1) - 2 * rank_sum, k * n))
def kemeny_costs(prof, perms):
"""Total Kendall distance of each permutation to the full lists of prof."""
pos = [{x: i for i, x in enumerate(r)} for r in prof]
items = sorted(prof[0])
w = {(x, y): sum(1 for t in pos if t[x] < t[y]) for x in items for y in items}
n = len(items)
return [sum(w[p[j], p[i]] for i in range(n) for j in range(i + 1, n)) for p in perms]
def footrule_costs(prof, perms):
pos = [{x: i for i, x in enumerate(r)} for r in prof]
return [sum(abs(i - t[x]) for t in pos for i, x in enumerate(p)) for p in perms]
def test_kemeny_costs_agree_with_kendall():
rng = random.Random(8)
for _ in range(20):
prof = random_profile(rng, rng.randint(1, 5), rng.randint(1, 4), partial=False)
perms = list(itertools.permutations(sorted(prof[0])))
assert kemeny_costs(prof, perms) == [total(kendall, p, prof) for p in perms]
assert footrule_costs(prof, perms) == [total(footrule, p, prof) for p in perms]
def test_condorcet_ranking_is_the_unique_kemeny_ranking():
rng = random.Random(5)
seen = 0
for _ in range(150):
n = rng.randint(2, 6)
prof = random_profile(rng, n, rng.choice([1, 3, 5, 7]), partial=False)
items = sorted(prof[0])
beats = {(x, y): prefers(prof, x, y) for x in items for y in items}
perms = list(itertools.permutations(items))
cond = [p for p in perms if all(beats[p[i], p[j]] for i in range(n) for j in range(i + 1, n))]
if not cond:
continue
seen += 1
cost = kemeny_costs(prof, perms)
best = min(cost)
assert [p for p, c in zip(perms, cost) if c == best] == cond
assert seen > 30
def test_footrule_optimum_is_a_two_approximation_of_kemeny():
rng = random.Random(6)
for _ in range(60):
n = rng.randint(2, 6)
prof = random_profile(rng, n, rng.randint(1, 5), partial=False)
perms = list(itertools.permutations(sorted(prof[0])))
kc, fc = kemeny_costs(prof, perms), footrule_costs(prof, perms)
kem, fbest = min(kc), min(fc)
for k_cost, f_cost in zip(kc, fc):
assert k_cost <= f_cost <= 2 * k_cost # Diaconis and Graham, summed over the lists
if f_cost == fbest:
assert k_cost <= 2 * kem
def test_local_kemenization():
rng = random.Random(7)
for _ in range(300):
n = rng.randint(1, 7)
prof = random_profile(rng, n, rng.randint(1, 5), partial=rng.random() < 0.5)
start = sorted({x for r in prof for x in r})
rng.shuffle(start)
out = local_kemenize(start, prof)
assert sorted(out) == sorted(start)
# Locally Kemeny optimal: no adjacent swap lowers the total Kendall distance.
for i in range(len(out) - 1):
assert not prefers(prof, out[i + 1], out[i])
assert total(kendall, out, prof) <= total(kendall, start, prof)
# Extended Condorcet: if every item of a top set beats every other item, the set comes first.
for size in range(1, len(out)):
for top in itertools.combinations(sorted(out), size):
rest = [y for y in out if y not in top]
if all(prefers(prof, x, y) for x in top for y in rest):
assert set(out[:size]) == set(top)
def test_extended_procedure_on_the_page_example():
prof = [list("abc")] * 3 + [list("bca")] * 2
assert aggregate(prof, "MC4", eps=0.0)[0] == "a"
assert aggregate(prof, "MC4", eps=0.15) == list("abc")
assert aggregate([list("bc")] * 3 + [list("bc")] * 2, "MC4", eps=0.0) == list("bc")
assert local_kemenize(list("bac"), prof) == list("abc")
def test_toy_runs():
bm25 = [1, 2, 8, 7, 4]
run = [1, 6, 8, 2, 4]
# Document 6 is in one list only, so it beats 2, 8 and 4 by a "majority" of one list.
assert aggregate([bm25, run], "MC4", eps=0.15) == [1, 6, 2, 8, 7, 4]
items, m = transition_matrix([bm25, run], "MC4", exact=True)
pi = exact_stationary(teleport(m, Fraction(3, 20)))
assert dict(zip(items, pi)) == {1: Fraction(4, 7), 2: Fraction(2580, 30797), 4: Fraction(3, 103), 6: Fraction(39072, 215579), 7: Fraction(120, 2369), 8: Fraction(2580, 30797)}
# With no teleport, document 1 is a Condorcet winner and holds all the mass.
assert aggregate([bm25, run], "MC4", eps=0.0) == [1, 2, 4, 6, 7, 8]
def test_five_voter_profile_mc3_against_mc4():
prof = [list("abc")] * 3 + [list("bca")] * 2
assert aggregate(prof, "MC3", eps=0.0) == list("bac")
_, m = transition_matrix(prof, "MC3", exact=True)
assert exact_stationary(m) == [Fraction(3, 7), Fraction(13, 28), Fraction(3, 28)]
_, m = transition_matrix(prof, "MC4", exact=True)
assert exact_stationary(teleport(m, Fraction(3, 20))) == [Fraction(10, 13), Fraction(90, 559), Fraction(3, 43)]
History
Dwork, Kumar, Naor and Sivakumar presented rank aggregation for the web at the WWW10 conference in Hong Kong in 2001. Their aim was a metasearch engine that resists spam: a page that tricks one search engine should not reach the top of the merged list. The paper proves that the Kemeny ranking is NP-hard to find already for four lists, which motivated the cheap chains. It defines MC1 to MC4 as heuristics, compares them with Borda and footrule aggregation on the results of real search engines, and introduces local Kemenization and the extended Condorcet criterion. The paper builds the chains without a jump; the teleport of line L3 is the standard repair, taken from PageRank, that later uses of these chains add to make the stationary distribution unique.
References
- Cynthia Dwork, Ravi Kumar, Moni Naor and D. Sivakumar, Rank aggregation methods for the Web, Proceedings of the 10th International World Wide Web Conference (WWW10), 613-622, the Markov chain methods MC1 to MC4, the definition of local Kemenization and the extended Condorcet criterion, and the NP-hardness of Kemeny aggregation for four lists
- Cynthia Dwork, Ravi Kumar, Moni Naor and D. Sivakumar, Rank aggregation revisited, manuscript (2001), the longer version of the WWW10 paper, with the proofs on local Kemenization and on the footrule as an approximation of the Kendall distance
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 DF298Z Edit this page History Report an error Markdown