Algorithmadvanced
Word mover's distance
Also called WMD.
The distance between two documents as the minimum cost to move the word embeddings of one to those of the other, an earth mover's distance.
- Time
- O(p^3 log p) exactO(d p^2) rwmdO(d p) wcd
- Space
- O(p^2) extra
- Where
- d = the dimension of the word vectors; p = the number of distinct words in the two documents
- Model
- Real RAM
- Properties
- deterministicexactofflineiterativenot supervised
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Matt J. Kusner, Yu Sun, Nicholas I. Kolkin, Kilian Q. Weinberger, 2015
The word mover's distance (WMD) measures how far apart two documents are as the least total distance that the words of one document must travel in a word embedding to become the words of the other. Each document is a normalized bag of words, a probability distribution over its distinct words, and the cost of moving a unit of weight from one word to another is the Euclidean distance of their vectors. WMD is the earth mover's distance between the two distributions, so it is the optimum of a transportation problem, a special case of the minimum cost flow problem. The distance itself is exact; how well it predicts what people judge as similar documents is a measurement.
In plain words
Think of each document as a set of piles of sand, one pile for each word, with more sand for words that occur more often. Every word has a place in space, given by its vector, and words with similar meanings are close. To turn the first document into the second, move all the sand from the piles of the first to the piles of the second. Moving sand far costs more than moving it near. WMD is the cheapest way to move it all.
"Obama speaks to the media in Illinois" and "The President greets the press in Chicago" share no word except "the" and "in", which are removed. But Obama is close to President, speaks to greets, media to press and Illinois to Chicago, so the sand moves only short distances and the two sentences come out close.
The problem
Let a document have the distinct words (after the stop words and the words without a vector are removed) with the counts . Its normalized bag of words (nBOW) is . The second document has the nBOW over its words . With the word vectors and , the travel cost is . Then
is the amount of word that travels to word . This linear program is the transportation problem: a minimum cost flow from the words of the first document to the words of the second on a complete bipartite network. The earth mover's distance has no page of its own here; WMD is its special case with word vectors as the ground space.
The algorithm
The code solves the program exactly with successive shortest paths. The shares are rationals, so it scales them to integers first.
WMD(doc1, doc2)- 1
d ← nBOW(doc1); d' ← nBOW(doc2) - 2
c(i, j) ← ‖x_i - x'_j‖ for every word i of doc1 and j of doc2 - 3
L ← lcm of the denominators of all d_i and d'_j; a_i ← d_i L; b_j ← d'_j L - 4
F ← 0 - 5
while some supply a_i is not yet sent do - 6
P ← a cheapest path s → t in the residual network, by Bellman-Ford - 7
δ ← the bottleneck of P: the remaining supply, the remaining demand, or a reverse arc - 8
push δ along P - 9
return Σ_ij F_ij c(i, j) / L
The network has a source with an arc of capacity to each word of the first document, an arc of cost and no capacity limit from each to each word of the second document, and an arc of capacity from to the sink . The residual network also has the reverse arc with cost wherever flow is on , which lets a later path undo an earlier choice. Negative arc costs are the reason for Bellman-Ford in line L6; with node potentials, Dijkstra's algorithm works too.
Lower bounds. Two cheap bounds come with the method.
- Word centroid distance (WCD). , the distance between the weighted means of the two documents. It costs time.
- Relaxed WMD (RWMD). Drop the column constraints: then each word moves all its weight to its nearest word in the other document, which gives . Dropping the row constraints instead gives . RWMD is , at time.
Prefetch and prune. For the nearest documents of a query, sort the candidates by WCD, compute the exact WMD of the first , and for each further candidate compute RWMD first. If RWMD is at least the current -th distance, skip the exact computation.
Example
Take the example of the paper with two dimensional vectors written for this page: Obama , President , speaks , greets , media , press , Illinois and Chicago . The stop words "the", "to" and "in" are removed, so each document has four words with the share . The travel costs are:
| President | greets | press | Chicago | |
|---|---|---|---|---|
| Obama | 0.2236 | 1.3601 | 2.1095 | 1.5811 |
| speaks | 1.5000 | 0.2236 | 1.6279 | 2.3022 |
| media | 2.2023 | 1.6279 | 0.2236 | 1.7029 |
| Illinois | 1.6279 | 2.1095 | 1.3601 | 0.3162 |
The optimal flow sends each word to its partner on the diagonal, so . Here every word's nearest word is its partner, so RWMD is also . The two centroids are and , so WCD , a weaker bound. With word2vec vectors trained on Google News, the paper gives for this pair of sentences.
With unequal lengths the weight splits. For "The President speaks", each of the two words gets . The optimum sends Obama and Illinois to President, and speaks and media to speaks: . Each word of the second document receives two quarters, as its share of requires.
Correctness
The proof below shows that the algorithm returns the exact optimum. Scaling by turns the program into one with integer supplies and demands and does not change which is optimal. Successive shortest paths keep the invariant that the residual network has no negative cycle. The invariant holds at the start, since all costs are then at least 0. Augmenting along a shortest path keeps it, because every arc of the path has reduced cost 0 with the shortest path distances as potentials. A flow of full value with no negative residual cycle is a minimum cost flow (Ahuja, Magnanti and Orlin 1993, chapter 9). Every bottleneck is a positive integer, so the loop ends after at most rounds.
WCD is a lower bound by the triangle inequality: for any feasible . RWMD is a lower bound because each of its two programs drops constraints. These bounds make the prefetch and prune search exact up to ties.
When both documents have distinct words with share , the feasible set is the set of doubly stochastic matrices divided by . By the Birkhoff-von Neumann theorem its vertices are the permutation matrices, so WMD is times the optimum of an assignment problem, which the Hungarian algorithm solves in time. The tests check this against a brute force over all permutations.
WMD is a metric on nBOW distributions, because the earth mover's distance is a metric when the ground distance is one (Rubner, Tomasi and Guibas 1998). Two documents with the same nBOW are at distance 0, even when their word order differs.
Proof: Successive shortest paths compute WMD exactly, and WCD and RWMD are lower boundsfull
We use the pseudocode of the page. The first document has the distinct words with the shares , and the second has the words with the shares . Both lists of shares are rationals that sum to 1. The cost is . WMD is the optimum of the linear program
Scaling. Let be the least common multiple of the denominators of all the shares (line L3), and , . These are positive integers with . A matrix is feasible for the program above if and only if is feasible for the same program with and , and the costs differ by the factor . So it is enough to solve the integer program and divide by (line L9).
The network. Build a source , a sink , an arc of capacity and cost 0, an arc of infinite capacity and cost , and an arc of capacity and cost 0. A flow of value from to is the same as a feasible . The residual network of a flow has the arcs while still has supply, every arc , an arc of cost while , and while still has demand. This is the network that line L6 searches.
Lemma 1 (optimality condition). A flow of a given value has the least cost among the flows of that value if and only if its residual network has no cycle of negative cost. This is the negative cycle optimality condition of minimum cost flow (Ahuja, Magnanti and Orlin 1993, chapter 9).
Lemma 2 (invariant). Before each round of line L5, the residual network has no negative cycle.
Proof. At the start and the only arcs with a cost are the arcs , whose costs are at least 0, so no cycle is negative.
Assume the invariant before a round. Then Bellman-Ford finds exact shortest path distances from to every node that reaches, and a shortest path to . Let be the set of nodes that reaches. For every residual arc with , and , so the reduced cost is at least 0. On the reduced costs are 0, since is a shortest path. Line L8 pushes along . This can remove arcs of and can add the reversal of an arc of , whose reduced cost is . All other arcs stay. After the push, no arc leaves : no arc left before, and the new arcs join two nodes of . So every cycle lies inside or inside its complement. A cycle inside has a cost equal to the sum of its reduced costs, because the terms cancel around a cycle, and that sum is at least 0. A cycle inside the complement uses only arcs that did not change, so it was not negative before and is not negative now.
Lemma 3 (a path exists). While some is not yet sent, line L6 finds a path from to .
Proof. The totals of the remaining supply and the remaining demand are equal, since each round reduces both by . So some supply word and some demand word still have something left, and is a residual path, because the arc has infinite capacity.
Theorem 1. Line L9 returns WMD, and the loop of line L5 ends after at most rounds.
Proof. Every capacity and every flow value is an integer, so the bottleneck of line L7 is a positive integer, and each round sends at least one more unit. The total to send is , so there are at most rounds (Lemma 3 shows that the loop does not stop early). At the end, the flow has value , so is feasible. By Lemma 2 its residual network has no negative cycle, so by Lemma 1 it has the least cost of all the flows of value . By the scaling argument, is the optimum of the original program.
Theorem 2 (WCD is a lower bound). .
Proof. Let be optimal. Then and , by the two sets of constraints. So the left side is , by the triangle inequality and .
Theorem 3 (RWMD is a lower bound). Let and . Then is the optimum of the program without the column constraints, is the optimum without the row constraints, and .
Proof. For any with row sums , , and moving all of to a nearest word attains it. The case of is the same with the roles swapped. Each relaxed program has a larger feasible set than the full one, so its optimum is at most WMD, and so is the larger of the two.
Theorem 4 (the assignment case). If both documents have distinct words with the share each, then over the permutations of .
Proof. The feasible set is . By the Birkhoff-von Neumann theorem, the doubly stochastic matrices are the convex hull of the permutation matrices. A linear function on a polytope attains its minimum at a vertex, and the vertex of the permutation has the cost .
Theorem 5 (pruned search is exact). In the k-nearest search of the code, a skipped document has RWMD at least the current -th smallest WMD, so by Theorem 3 its WMD is at least that value too. The -th smallest value never increases during the search, so a skipped document cannot be closer than the final -th neighbor. Only a document with exactly the same distance as the -th neighbor can be left out, which changes the result only on ties.
Complexity
The model is the real-RAM, with the number of distinct words in the two documents and the dimension of the vectors.
- Costs. Line L2 computes up to distances: time and space.
- Exact WMD. Kusner et al. quote as the best average time of the known solvers (Pele and Werman 2009). The code on this page is simpler: each round of Bellman-Ford costs on the bipartite network, and there are at most rounds, where is at most the product of the two document lengths.
- Bounds. WCD costs , or per pair when the centroids are stored. RWMD costs .
- Search. A nearest-neighbor search over documents computes WCDs, and RWMD and the exact WMD only for the documents that the bounds do not prune.
Properties
- No training. WMD has no parameters beyond the word vectors and the stop list.
- Metric. It is symmetric, zero for equal nBOWs and satisfies the triangle inequality.
- Bag of words. Word order does not count. "Dog bites man" and "man bites dog" are at distance 0.
- Sparse flow. A vertex solution of the transportation problem has at most nonzero entries, so most word pairs carry no flow.
- Interpretable. The flow shows which words match which.
Variants and improvements
- Supervised WMD. Huang et al. 2016 learn a linear map of the word vectors and weights of the words from labeled documents, so that the distance fits the labels.
- Entropic regularization. Cuturi 2013 adds an entropy term to the transportation problem. Sinkhorn iterations then solve it with matrix scaling in roughly per iteration, at the price of an approximate value.
- Greedy matching. Matching each word to its nearest word, which is one side of RWMD, is what BERTScore does with contextual token vectors and cosine similarity.
- Centroid only. WCD alone is the distance between averaged word vectors, the simple sentence embedding baseline.
When to use it
Use WMD to compare short texts that use different words for the same things, when good word vectors exist and the number of comparisons is small enough to afford a transportation problem for each. In the k-nearest-neighbor classification experiments of Kusner et al. on eight document data sets, WMD gave the lowest average error among the document distances they compared, such as bag of words, tf-idf, BM25, LSI and LDA. That is a measurement on those data sets. For a large collection, compare sentence vectors with nearest neighbor search first and use WMD, or RWMD, to rerank.
Pitfalls
- Stop words. Without a stop list, "the", "of" and "in" take a large share of the weight and pull every pair of documents together. Remove them before line L1, as the paper does.
- Words without vectors. Removing them changes the nBOW. Report how many words were dropped, and handle a document with no remaining word as an error.
- Vector length. word2vec vectors are not unit length, and frequent words tend to have longer vectors. The Euclidean cost then mixes length and direction. Some implementations normalize the vectors first; say which form you use.
- Floating point in the solver. The residual network has negative arc costs, and rounding can make a zero-cost cycle look slightly negative. The code compares distances with a small tolerance, so Bellman-Ford does not loop on such cycles.
- Ties in the pruned search. The rule "skip when RWMD is at least the -th distance" can drop a document whose WMD equals the -th distance. Use a strict test if ties matter.
- Long documents. The cost grows about as , so WMD is slow for long documents. Prune with the bounds, or use the entropic form.
Implementations
The code takes the word vectors as given and implements the nBOW, an exact transportation solver by successive shortest paths on integer amounts, WCD, RWMD and the pruned nearest-neighbor search.
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/word-movers-distance/. The authors are listed in prov/ZXZK9R.jsonl.
"""Word Mover's Distance (Kusner, Sun, Kolkin and Weinberger 2015) and its lower bounds.
A document is a list of tokens. The word vectors are given as a dict from a
word to a list of floats; the code does not train them. The normalized bag of
words (nBOW) of a document gives each distinct word the share c_i / sum c_j of
its count, after the stop words and the words without a vector are removed.
WMD is the least total cost of moving the nBOW of one document onto the nBOW
of the other, where moving one unit from word i to word j costs |x_i - x_j|.
The transportation problem is solved exactly by successive shortest paths
with Bellman-Ford on integer amounts: the shares are rationals, so they are
scaled by the least common multiple of their denominators.
"""
import math
from fractions import Fraction
from typing import Dict, Iterable, List, Sequence, Tuple
Vector = Sequence[float]
Vectors = Dict[str, Vector]
def euclidean(a: Vector, b: Vector) -> float:
return math.sqrt(math.fsum((x - y) ** 2 for x, y in zip(a, b)))
def nbow(tokens: Iterable[str], vectors: Vectors, stop_words: Iterable[str] = ()) -> Tuple[List[str], List[Fraction]]:
"""Return the distinct words of the document, in order of first use, and their shares as Fractions."""
stop = set(stop_words)
counts: Dict[str, int] = {}
for t in tokens:
if t in stop or t not in vectors:
continue
counts[t] = counts.get(t, 0) + 1
total = sum(counts.values())
if total == 0:
raise ValueError("the document has no word with a vector")
words = list(counts)
return words, [Fraction(counts[w], total) for w in words]
def transport(supply: Sequence[int], demand: Sequence[int], cost: Sequence[Sequence[float]]) -> Tuple[float, List[List[int]]]:
"""Solve min sum F_ij cost_ij subject to row sums supply and column sums demand, F >= 0.
The amounts are integers with equal totals. Successive shortest paths:
each round finds a cheapest path from the source to the sink in the
residual network with Bellman-Ford and pushes the bottleneck amount along
it. Returns (the least cost, the integer flow matrix).
"""
m, n = len(supply), len(demand)
if sum(supply) != sum(demand):
raise ValueError("the supplies and the demands must have the same total")
if any(a < 0 for a in supply) or any(b < 0 for b in demand):
raise ValueError("the amounts must not be negative")
flow = [[0] * n for _ in range(m)] # @line L4
left = list(supply)
need = list(demand)
# Nodes: 0 .. m-1 supply words, m .. m+n-1 demand words, s = m+n, t = m+n+1.
s, t = m + n, m + n + 1
eps = 1e-12
while any(left): # @line L5
dist = [math.inf] * (m + n + 2)
prev: List[Tuple[int, int]] = [(-1, -1)] * (m + n + 2)
dist[s] = 0.0
for _ in range(m + n + 1): # @line L6
changed = False
for i in range(m):
if left[i] > 0 and dist[s] + eps < dist[i]:
dist[i], prev[i] = dist[s], (s, 0)
changed = True
for i in range(m):
if dist[i] == math.inf:
continue
for j in range(n):
if dist[i] + cost[i][j] + eps < dist[m + j]:
dist[m + j], prev[m + j] = dist[i] + cost[i][j], (i, 1)
changed = True
for j in range(n):
if dist[m + j] == math.inf:
continue
for i in range(m):
if flow[i][j] > 0 and dist[m + j] - cost[i][j] + eps < dist[i]:
dist[i], prev[i] = dist[m + j] - cost[i][j], (m + j, -1)
changed = True
if need[j] > 0 and dist[m + j] + eps < dist[t]:
dist[t], prev[t] = dist[m + j], (m + j, 0)
changed = True
if not changed:
break
path = []
v = t
while v != s:
u, kind = prev[v]
path.append((u, v, kind))
v = u
path.reverse()
delta = min(left[path[0][1]], need[path[-1][0] - m]) # @line L7
for u, v, kind in path:
if kind == -1:
delta = min(delta, flow[v][u - m])
for u, v, kind in path: # @line L8
if kind == 1:
flow[u][v - m] += delta
elif kind == -1:
flow[v][u - m] -= delta
left[path[0][1]] -= delta
need[path[-1][0] - m] -= delta
total = math.fsum(flow[i][j] * cost[i][j] for i in range(m) for j in range(n))
return total, flow
def wmd_with_flow(
doc1: Iterable[str], doc2: Iterable[str], vectors: Vectors, stop_words: Iterable[str] = ()
) -> Tuple[float, List[str], List[str], List[List[Fraction]]]:
"""Return (WMD, words of doc1, words of doc2, the optimal flow T as Fractions)."""
w1, d1 = nbow(doc1, vectors, stop_words) # @line L1
w2, d2 = nbow(doc2, vectors, stop_words)
cost = [[euclidean(vectors[a], vectors[b]) for b in w2] for a in w1] # @line L2
scale = math.lcm(*(f.denominator for f in d1 + d2)) # @line L3
supply = [int(f * scale) for f in d1]
demand = [int(f * scale) for f in d2]
total, flow = transport(supply, demand, cost)
T = [[Fraction(x, scale) for x in row] for row in flow]
return total / scale, w1, w2, T # @line L9
def wmd(doc1: Iterable[str], doc2: Iterable[str], vectors: Vectors, stop_words: Iterable[str] = ()) -> float:
"""The Word Mover's Distance between two documents."""
return wmd_with_flow(doc1, doc2, vectors, stop_words)[0]
def wcd(doc1: Iterable[str], doc2: Iterable[str], vectors: Vectors, stop_words: Iterable[str] = ()) -> float:
"""The word centroid distance |X d - X' d'|, a lower bound of WMD. O(d p) time."""
w1, d1 = nbow(doc1, vectors, stop_words)
w2, d2 = nbow(doc2, vectors, stop_words)
dim = len(vectors[w1[0]])
c1 = [math.fsum(float(f) * vectors[w][k] for w, f in zip(w1, d1)) for k in range(dim)]
c2 = [math.fsum(float(f) * vectors[w][k] for w, f in zip(w2, d2)) for k in range(dim)]
return euclidean(c1, c2)
def rwmd(doc1: Iterable[str], doc2: Iterable[str], vectors: Vectors, stop_words: Iterable[str] = ()) -> float:
"""The relaxed WMD max(l1, l2), a lower bound of WMD. O(d p^2) time.
l1 drops the column constraints, so each word of doc1 moves all its share
to its nearest word of doc2; l2 drops the row constraints.
"""
w1, d1 = nbow(doc1, vectors, stop_words)
w2, d2 = nbow(doc2, vectors, stop_words)
cost = [[euclidean(vectors[a], vectors[b]) for b in w2] for a in w1]
l1 = math.fsum(float(d1[i]) * min(cost[i]) for i in range(len(w1)))
l2 = math.fsum(float(d2[j]) * min(cost[i][j] for i in range(len(w1))) for j in range(len(w2)))
return max(l1, l2)
def knn(
query: Sequence[str], docs: Sequence[Sequence[str]], vectors: Vectors, k: int, stop_words: Iterable[str] = ()
) -> Tuple[List[Tuple[float, int]], int]:
"""Exact k nearest documents by WMD, with prefetch by WCD and pruning by RWMD.
Returns (the k pairs (distance, index) in order, the number of exact WMD
computations). A document whose RWMD is at least the current k-th
distance cannot enter the k nearest, so its WMD is skipped.
"""
stop = list(stop_words)
order = sorted(range(len(docs)), key=lambda i: wcd(query, docs[i], vectors, stop))
best: List[Tuple[float, int]] = []
exact = 0
for i in order:
if len(best) == k and rwmd(query, docs[i], vectors, stop) >= best[-1][0]:
continue
dist = wmd(query, docs[i], vectors, stop)
exact += 1
best.append((dist, i))
best.sort()
del best[k:]
return best, exact
test_word_movers_distance.py 155 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/word-movers-distance/. The authors are listed in prov/ZXZK9R.jsonl.
import math
import random
from fractions import Fraction
from itertools import permutations
import pytest
from word_movers_distance import euclidean, knn, nbow, rwmd, transport, wcd, wmd, wmd_with_flow
V = {
"obama": [1.0, 0.0],
"president": [1.2, 0.1],
"speaks": [0.0, 1.0],
"greets": [0.2, 1.1],
"media": [-1.0, 0.0],
"press": [-1.1, -0.2],
"illinois": [0.0, -1.0],
"chicago": [0.1, -1.3],
}
STOP = {"the", "to", "in"}
D1 = "obama speaks to the media in illinois".split()
D2 = "the president greets the press in chicago".split()
D3 = "the president speaks".split()
def random_vocab(rng, size, dim):
return {f"w{i}": [rng.gauss(0.0, 1.0) for _ in range(dim)] for i in range(size)}
def random_doc(rng, vocab, length):
words = list(vocab)
return [rng.choice(words) for _ in range(length)]
def check_flow(T, d1, d2):
for i, row in enumerate(T):
assert sum(row) == d1[i]
assert all(x >= 0 for x in row)
for j in range(len(d2)):
assert sum(T[i][j] for i in range(len(T))) == d2[j]
def test_nbow():
words, d = nbow(["a", "b", "a", "the", "zzz"], {"a": [1.0], "b": [2.0], "the": [0.0]}, {"the"})
assert words == ["a", "b"]
assert d == [Fraction(2, 3), Fraction(1, 3)]
with pytest.raises(ValueError):
nbow(["the"], {"the": [0.0]}, {"the"})
def test_page_example():
dist, w1, w2, T = wmd_with_flow(D1, D2, V, STOP)
assert w1 == ["obama", "speaks", "media", "illinois"]
assert dist == pytest.approx((3 * math.sqrt(0.05) + math.sqrt(0.1)) / 4)
assert dist == pytest.approx(0.2468, abs=1e-4)
assert T == [[Fraction(1, 4) if i == j else 0 for j in range(4)] for i in range(4)]
assert wcd(D1, D2, V, STOP) == pytest.approx(0.125)
dist3, _, w3, T3 = wmd_with_flow(D1, D3, V, STOP)
assert w3 == ["president", "speaks"]
assert dist3 == pytest.approx(0.8164, abs=1e-4)
assert T3 == [[Fraction(1, 4), 0], [0, Fraction(1, 4)], [0, Fraction(1, 4)], [Fraction(1, 4), 0]]
def test_assignment_case_matches_brute_force_over_permutations():
rng = random.Random(1)
for n in range(1, 7):
vocab = random_vocab(rng, 2 * n, 3)
words = list(vocab)
a, b = words[:n], words[n:]
best = min(math.fsum(euclidean(vocab[a[i]], vocab[b[p[i]]]) for i in range(n)) for p in permutations(range(n)))
assert wmd(a, b, vocab) == pytest.approx(best / n, abs=1e-12)
def test_transport_matches_brute_force_on_integer_vertices():
# With supplies (2, 1) and demands (1, 1, 1), every vertex of the polytope is listed below.
rng = random.Random(2)
for _ in range(30):
cost = [[rng.uniform(0, 5) for _ in range(3)] for _ in range(2)]
candidates = []
for j in range(3):
row1 = [1 if k == j else 0 for k in range(3)]
row0 = [1 - x for x in row1]
candidates.append(math.fsum(row0[k] * cost[0][k] + row1[k] * cost[1][k] for k in range(3)))
total, flow = transport([2, 1], [1, 1, 1], cost)
assert total == pytest.approx(min(candidates), abs=1e-12)
assert [sum(r) for r in flow] == [2, 1]
assert [flow[0][j] + flow[1][j] for j in range(3)] == [1, 1, 1]
def test_one_dimensional_closed_form():
# On the line, the earth mover's distance is the integral of |F1 - F2|.
rng = random.Random(3)
for _ in range(20):
vocab = {f"w{i}": [rng.uniform(-3, 3)] for i in range(8)}
a = random_doc(rng, vocab, rng.randint(1, 6))
b = random_doc(rng, vocab, rng.randint(1, 6))
wa, da = nbow(a, vocab)
wb, db = nbow(b, vocab)
pts = sorted({vocab[w][0] for w in wa + wb})
integral = 0.0
for left, right in zip(pts, pts[1:]):
f1 = sum(float(f) for w, f in zip(wa, da) if vocab[w][0] <= left)
f2 = sum(float(f) for w, f in zip(wb, db) if vocab[w][0] <= left)
integral += abs(f1 - f2) * (right - left)
assert wmd(a, b, vocab) == pytest.approx(integral, abs=1e-9)
def test_flow_is_feasible_and_bounds_hold():
rng = random.Random(4)
vocab = random_vocab(rng, 12, 4)
for _ in range(40):
a = random_doc(rng, vocab, rng.randint(1, 7))
b = random_doc(rng, vocab, rng.randint(1, 7))
dist, w1, w2, T = wmd_with_flow(a, b, vocab)
check_flow(T, nbow(a, vocab)[1], nbow(b, vocab)[1])
assert wcd(a, b, vocab) <= dist + 1e-12
assert rwmd(a, b, vocab) <= dist + 1e-12
assert wmd(b, a, vocab) == pytest.approx(dist, abs=1e-12)
def test_metric_axioms():
rng = random.Random(5)
vocab = random_vocab(rng, 10, 3)
docs = [random_doc(rng, vocab, rng.randint(1, 5)) for _ in range(8)]
for a in docs:
assert wmd(a, a, vocab) == pytest.approx(0.0, abs=1e-12)
assert wmd(a, list(reversed(a)) + a, vocab) == pytest.approx(0.0, abs=1e-12)
for a in docs:
for b in docs:
for c in docs:
assert wmd(a, c, vocab) <= wmd(a, b, vocab) + wmd(b, c, vocab) + 1e-9
def test_knn_with_pruning_equals_brute_force():
rng = random.Random(6)
vocab = random_vocab(rng, 15, 3)
docs = [random_doc(rng, vocab, rng.randint(2, 6)) for _ in range(25)]
query = random_doc(rng, vocab, 4)
brute = sorted((wmd(query, d, vocab), i) for i, d in enumerate(docs))
for k in (1, 3, 5):
got, exact = knn(query, docs, vocab, k)
assert [i for _, i in got] == [i for _, i in brute[:k]]
assert exact <= len(docs)
_, exact = knn(query, docs, vocab, 1)
assert exact < len(docs)
def test_bad_input():
with pytest.raises(ValueError):
transport([1, 1], [3], [[0.0], [0.0]])
with pytest.raises(ValueError):
transport([-1, 2], [1], [[0.0], [0.0]])
History
The transportation problem goes back to Monge in 1781 and to Kantorovich and Hitchcock around 1940. Rubner, Tomasi and Guibas 1998 named the earth mover's distance and used it to compare color histograms for image retrieval. Kusner, Sun, Kolkin and Weinberger 2015 applied it to documents, with word2vec vectors as the ground space, and added the WCD and RWMD bounds for fast search. Later work learned the ground costs (Huang et al. 2016), replaced the exact solver with Sinkhorn iterations, and used contextual token vectors in place of word vectors.
References
- Kusner et al. 2015, the definitions of the nBOW, the travel cost and the linear program, the word centroid distance and the relaxed WMD, the prefetch and prune search, and the Obama example
- Rubner, Tomasi and Guibas 1998, the earth mover's distance, and the proof that it is a metric when the ground distance is a metric
- Pele and Werman 2009, the fast solver whose running time Kusner et al. quote for WMD
- Ravindra K. Ahuja, Thomas L. Magnanti and James B. Orlin, Network Flows, theory, algorithms and applications, Prentice Hall, 1993, chapter 9, the negative cycle optimality condition and the successive shortest path algorithm
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 ZXZK9R Edit this page History Report an error Markdown