Algorithm Search⌘K

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
Properties
deterministicexactofflineiterativenot supervised
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 w1,…,wmw_1, \ldots, w_m (after the stop words and the words without a vector are removed) with the counts cic_i. Its normalized bag of words (nBOW) is di=ci/∑kckd_i = c_i / \sum_k c_k. The second document has the nBOW d1′,…,dn′d'_1, \ldots, d'_n over its words wj′w'_j. With the word vectors xix_i and xj′x'_j, the travel cost is c(i,j)=∥xi−xj′∥2c(i, j) = \|x_i - x'_j\|_2. Then

WMD(d,d′)=min⁡T≥0∑i=1m∑j=1nTij c(i,j)subject to∑jTij=di for all i,∑iTij=dj′ for all j.\mathrm{WMD}(d, d') = \min_{T \ge 0} \sum_{i=1}^{m} \sum_{j=1}^{n} T_{ij}\, c(i, j) \quad \text{subject to} \quad \sum_j T_{ij} = d_i \ \text{for all } i, \quad \sum_i T_{ij} = d'_j \ \text{for all } j.

TijT_{ij} is the amount of word ii that travels to word jj. 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.

  1. WMD(doc1, doc2)
  2. 1d ← nBOW(doc1); d' ← nBOW(doc2)
  3. 2c(i, j) ← ‖x_i - x'_j‖ for every word i of doc1 and j of doc2
  4. 3L ← lcm of the denominators of all d_i and d'_j; a_i ← d_i L; b_j ← d'_j L
  5. 4F ← 0
  6. 5while some supply a_i is not yet sent do
  7. 6P ← a cheapest path s → t in the residual network, by Bellman-Ford
  8. 7δ ← the bottleneck of P: the remaining supply, the remaining demand, or a reverse arc
  9. 8push δ along P
  10. 9return Σ_ij F_ij c(i, j) / L

The network has a source ss with an arc of capacity aia_i to each word ii of the first document, an arc of cost c(i,j)c(i, j) and no capacity limit from each ii to each word jj of the second document, and an arc of capacity bjb_j from jj to the sink tt. The residual network also has the reverse arc j→ij \to i with cost −c(i,j)-c(i, j) wherever flow is on i→ji \to j, 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). ∥∑idixi−∑jdj′xj′∥2\|\sum_i d_i x_i - \sum_j d'_j x'_j\|_2, the distance between the weighted means of the two documents. It costs O(dp)O(d p) 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 ℓ1=∑idimin⁡jc(i,j)\ell_1 = \sum_i d_i \min_j c(i, j). Dropping the row constraints instead gives ℓ2\ell_2. RWMD is max⁡(ℓ1,ℓ2)\max(\ell_1, \ell_2), at O(dp2)O(d p^2) time.

Prefetch and prune. For the kk nearest documents of a query, sort the candidates by WCD, compute the exact WMD of the first kk, and for each further candidate compute RWMD first. If RWMD is at least the current kk-th distance, skip the exact computation.

Example

Take the example of the paper with two dimensional vectors written for this page: Obama (1,0)(1, 0), President (1.2,0.1)(1.2, 0.1), speaks (0,1)(0, 1), greets (0.2,1.1)(0.2, 1.1), media (−1,0)(-1, 0), press (−1.1,−0.2)(-1.1, -0.2), Illinois (0,−1)(0, -1) and Chicago (0.1,−1.3)(0.1, -1.3). The stop words "the", "to" and "in" are removed, so each document has four words with the share 1/41/4. 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 WMD=(0.2236+0.2236+0.2236+0.3162)/4=0.2468\mathrm{WMD} = (0.2236 + 0.2236 + 0.2236 + 0.3162)/4 = 0.2468. Here every word's nearest word is its partner, so RWMD is also 0.24680.2468. The two centroids are (0,0)(0, 0) and (0.1,−0.075)(0.1, -0.075), so WCD =0.125= 0.125, a weaker bound. With word2vec vectors trained on Google News, the paper gives 1.071.07 for this pair of sentences.

With unequal lengths the weight splits. For "The President speaks", each of the two words gets 1/21/2. The optimum sends Obama and Illinois to President, and speaks and media to speaks: (0.2236+1.6279+0+1.4142)/4=0.8164(0.2236 + 1.6279 + 0 + 1.4142)/4 = 0.8164. Each word of the second document receives two quarters, as its share of 1/21/2 requires.

Correctness

The proof below shows that the algorithm returns the exact optimum. Scaling by LL turns the program into one with integer supplies and demands and does not change which TT 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 LL rounds.

WCD is a lower bound by the triangle inequality: ∑idixi−∑jdj′xj′=∑i,jTij(xi−xj′)\sum_i d_i x_i - \sum_j d'_j x'_j = \sum_{i,j} T_{ij}(x_i - x'_j) for any feasible TT. 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 nn distinct words with share 1/n1/n, the feasible set is the set of doubly stochastic matrices divided by nn. By the Birkhoff-von Neumann theorem its vertices are the permutation matrices, so WMD is 1/n1/n times the optimum of an assignment problem, which the Hungarian algorithm solves in O(n3)O(n^3) 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 1,…,m1, \ldots, m with the shares di>0d_i > 0, and the second has the words 1,…,n1, \ldots, n with the shares dj′>0d'_j > 0. Both lists of shares are rationals that sum to 1. The cost is c(i,j)=∥xi−xj′∥2≥0c(i, j) = \|x_i - x'_j\|_2 \ge 0. WMD is the optimum of the linear program

min⁡T≥0∑i,jTijc(i,j)subject to∑jTij=di, ∑iTij=dj′.\min_{T \ge 0} \sum_{i,j} T_{ij} c(i, j) \quad \text{subject to} \quad \sum_j T_{ij} = d_i, \ \sum_i T_{ij} = d'_j.

Scaling. Let LL be the least common multiple of the denominators of all the shares (line L3), and ai=diLa_i = d_i L, bj=dj′Lb_j = d'_j L. These are positive integers with ∑ai=∑bj=L\sum a_i = \sum b_j = L. A matrix TT is feasible for the program above if and only if F=LTF = L T is feasible for the same program with aa and bb, and the costs differ by the factor LL. So it is enough to solve the integer program and divide by LL (line L9).

The network. Build a source ss, a sink tt, an arc s→is \to i of capacity aia_i and cost 0, an arc i→ji \to j of infinite capacity and cost c(i,j)c(i, j), and an arc j→tj \to t of capacity bjb_j and cost 0. A flow of value LL from ss to tt is the same as a feasible FF. The residual network of a flow FF has the arcs s→is \to i while ii still has supply, every arc i→ji \to j, an arc j→ij \to i of cost −c(i,j)-c(i, j) while Fij>0F_{ij} > 0, and j→tj \to t while jj 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 F=0F = 0 and the only arcs with a cost are the arcs i→ji \to j, 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 π(v)\pi(v) from ss to every node vv that ss reaches, and a shortest path PP to tt. Let RR be the set of nodes that ss reaches. For every residual arc u→vu \to v with u∈Ru \in R, v∈Rv \in R and π(v)≤π(u)+cost(u,v)\pi(v) \le \pi(u) + \text{cost}(u, v), so the reduced cost cost(u,v)+π(u)−π(v)\text{cost}(u, v) + \pi(u) - \pi(v) is at least 0. On PP the reduced costs are 0, since PP is a shortest path. Line L8 pushes δ\delta along PP. This can remove arcs of PP and can add the reversal of an arc of PP, whose reduced cost is −0=0-0 = 0. All other arcs stay. After the push, no arc leaves RR: no arc left RR before, and the new arcs join two nodes of P⊆RP \subseteq R. So every cycle lies inside RR or inside its complement. A cycle inside RR has a cost equal to the sum of its reduced costs, because the terms π(u)−π(v)\pi(u) - \pi(v) 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. □\square

Lemma 3 (a path exists). While some aia_i is not yet sent, line L6 finds a path from ss to tt.

Proof. The totals of the remaining supply and the remaining demand are equal, since each round reduces both by δ\delta. So some supply word ii and some demand word jj still have something left, and s→i→j→ts \to i \to j \to t is a residual path, because the arc i→ji \to j has infinite capacity. □\square

Theorem 1. Line L9 returns WMD, and the loop of line L5 ends after at most LL rounds.

Proof. Every capacity and every flow value is an integer, so the bottleneck δ\delta of line L7 is a positive integer, and each round sends at least one more unit. The total to send is LL, so there are at most LL rounds (Lemma 3 shows that the loop does not stop early). At the end, the flow has value LL, so FF 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 LL. By the scaling argument, ∑Fijc(i,j)/L\sum F_{ij} c(i, j) / L is the optimum of the original program. □\square

Theorem 2 (WCD is a lower bound). ∥∑idixi−∑jdj′xj′∥2≤WMD\|\sum_i d_i x_i - \sum_j d'_j x'_j\|_2 \le \mathrm{WMD}.

Proof. Let TT be optimal. Then ∑idixi=∑i,jTijxi\sum_i d_i x_i = \sum_{i,j} T_{ij} x_i and ∑jdj′xj′=∑i,jTijxj′\sum_j d'_j x'_j = \sum_{i,j} T_{ij} x'_j, by the two sets of constraints. So the left side is ∥∑i,jTij(xi−xj′)∥≤∑i,jTij∥xi−xj′∥=WMD\|\sum_{i,j} T_{ij}(x_i - x'_j)\| \le \sum_{i,j} T_{ij} \|x_i - x'_j\| = \mathrm{WMD}, by the triangle inequality and T≥0T \ge 0. □\square

Theorem 3 (RWMD is a lower bound). Let ℓ1=∑idimin⁡jc(i,j)\ell_1 = \sum_i d_i \min_j c(i, j) and ℓ2=∑jdj′min⁡ic(i,j)\ell_2 = \sum_j d'_j \min_i c(i, j). Then ℓ1\ell_1 is the optimum of the program without the column constraints, ℓ2\ell_2 is the optimum without the row constraints, and max⁡(ℓ1,ℓ2)≤WMD\max(\ell_1, \ell_2) \le \mathrm{WMD}.

Proof. For any T≥0T \ge 0 with row sums did_i, ∑i,jTijc(i,j)≥∑i∑jTijmin⁡kc(i,k)=∑idimin⁡kc(i,k)=ℓ1\sum_{i,j} T_{ij} c(i, j) \ge \sum_i \sum_j T_{ij} \min_k c(i, k) = \sum_i d_i \min_k c(i, k) = \ell_1, and moving all of did_i to a nearest word attains it. The case of ℓ2\ell_2 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. □\square

Theorem 4 (the assignment case). If both documents have nn distinct words with the share 1/n1/n each, then WMD=1nmin⁡σ∑ic(i,σ(i))\mathrm{WMD} = \frac{1}{n} \min_{\sigma} \sum_i c(i, \sigma(i)) over the permutations σ\sigma of {1,…,n}\{1, \ldots, n\}.

Proof. The feasible set is {T/n:T doubly stochastic}\{T / n : T \text{ doubly stochastic}\}. 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 σ\sigma has the cost 1n∑ic(i,σ(i))\frac{1}{n} \sum_i c(i, \sigma(i)). □\square

Theorem 5 (pruned search is exact). In the k-nearest search of the code, a skipped document has RWMD at least the current kk-th smallest WMD, so by Theorem 3 its WMD is at least that value too. The kk-th smallest value never increases during the search, so a skipped document cannot be closer than the final kk-th neighbor. Only a document with exactly the same distance as the kk-th neighbor can be left out, which changes the result only on ties. ■\blacksquare

Complexity

The model is the real-RAM, with pp the number of distinct words in the two documents and dd the dimension of the vectors.

  • Costs. Line L2 computes up to p2p^2 distances: O(dp2)O(d p^2) time and O(p2)O(p^2) space.
  • Exact WMD. Kusner et al. quote O(p3log⁡p)O(p^3 \log p) 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 O(p3)O(p^3) on the bipartite network, and there are at most LL rounds, where LL is at most the product of the two document lengths.
  • Bounds. WCD costs O(dp)O(d p), or O(d)O(d) per pair when the centroids are stored. RWMD costs O(dp2)O(d p^2).
  • Search. A nearest-neighbor search over NN documents computes NN 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 m+n−1m + n - 1 nonzero entries, so most word pairs carry no flow.
  • Interpretable. The flow TT 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 O(p2)O(p^2) 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 kk-th distance" can drop a document whose WMD equals the kk-th distance. Use a strict test if ties matter.
  • Long documents. The cost grows about as p3p^3, 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.

word_movers_distance.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. Pele and Werman 2009, the fast solver whose running time Kusner et al. quote for WMD
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.exact
  • a full proof of time.rwmd
  • a full proof of time.wcd
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example