Algorithm Search⌘K

Algorithmintro

Maximum matching segmentation

Also called MaxMatch, greedy longest-match segmentation.

Segment a string into words by repeatedly taking the longest dictionary word that starts at the current position, from left to right.

Time
O(n m) worstO(L) trie_build
Space
O(n) outputO(L) trie
Where
L = the total length of the dictionary words; m = the length of the longest dictionary word; n = the length of the string in characters
Properties
deterministicnot exactofflineiterative
Origin
Keh Jiann Chen, Shing Huan Liu, Pak kwong Wong, Chorkin Chan, 1992

Maximum matching segmentation, or MaxMatch, cuts a string with no spaces into words with a dictionary: at the current position it takes the longest dictionary word that starts there, and it continues after that word. It is one greedy algorithm for the word segmentation problem, which asks for the right cut, so it can return a wrong cut where a model-based method returns the right one. The longest match is found with a trie of the dictionary: the trie is the data structure, and MaxMatch is the rule that walks it. The backward variant works from the right end, and the bidirectional variant runs both directions and keeps one result.

In plain words

You have a line of text with no spaces and a list of known words. Start at the first letter. Look for the longest known word that starts there, cut it off, and start again after it. If no known word starts at a letter, cut off that single letter. Repeat until the line is used up.

The method never looks back. When the longest word at a place is the wrong choice, the error stays and can push the next words out of place. A word list stored as a tree of letters makes each search fast: you follow the letters of the text down the tree and remember the last place where a word ended.

The problem

The input is a string s=s[0…n)s = s[0 \ldots n) and a finite dictionary DD of nonempty strings. The output is a list of strings w1,…,wrw_1, \ldots, w_r whose concatenation is ss. A span s[i…j)s[i \ldots j) is written with fencepost indices: it covers the characters i+1i + 1 to jj in 1-based counting. MaxMatch does not optimize a score. Its output is defined by the rule itself: wtw_t is the longest word of DD that is a prefix of the rest of the string, or one character if there is no such word.

The algorithm

The trie TT holds the words of DD. Each node is a prefix of a word, and a node is marked when it is a full word.

  1. MAX-MATCH(s, T) ▷ |s| = n, T is a trie of D
  2. 1i ← 0, W ← empty list
  3. 2while i < n do
  4. 3v ← root of T, j ← i + 1, k ← i ▷ j is the end of the longest match so far
  5. 4while k < n and v has a child for s[k] do
  6. 5v ← that child, k ← k + 1
  7. 6if v is marked as a word then j ← k
  8. 7append s[i..j) to W
  9. 8i ← j
  10. 9return W

Line L3 sets the default end j=i+1j = i + 1, so that a position where no word starts gives a word of one character. Lines L4 to L6 follow the characters of ss down the trie and record the last position where a word ends. The walk stops when the trie has no edge for the next character, because then no longer word can match. Lines L7 and L8 cut off the longest match and move on.

The backward variant is MAX-MATCH on the reversed string with a trie of the reversed words, and it reverses the result. The bidirectional variant runs both and keeps the result with fewer words, then the one with fewer characters outside the dictionary, then the one with fewer one-character words, and the backward result on a full tie. This rule is a heuristic: it optimizes no model.

Example

Take the dictionary D={D = \{the, table, down, there, theta, bled, own, tab, led, a, here}\} and the string s=s = thetabledownthere, with n=17n = 17. The intended reading is "the table down there". In the table, "ends" lists every kk at which line L6 found a word.

step ii characters read in L4 and L5 why the walk stops ends jj word
1 0 t h e t a no edge for b after "theta" 3, 5 5 theta
2 5 b l e d no edge for o after "bled" 9 9 bled
3 9 o w n no edge for t after "own" 12 12 own
4 12 t h e r e k=nk = n 15, 17 17 there

Forward MaxMatch returns theta, bled, own, there. The first greedy choice "theta" takes the "ta" of "table", and the next two words are wrong as a result. Backward MaxMatch takes there, then the longest word that ends at position 12 (down, not own), then table, then the, so it returns the right reading. Both results have 4 words, no unknown characters and no one-character words, so the bidirectional rule falls to its last tie break and keeps the backward result.

Now give the words counts: the 30, a 6, there 5, down 4, table 3, own 2, here 2, and 1 for each of theta, bled, tab and led, 56 in all, with P(w)=c(w)/56P(w) = c(w)/56. The string has exactly three segmentations into dictionary words. Their natural log probabilities are −8.605865-8.605865 for the table down there, −13.798822-13.798822 for theta bled own there, and −14.422976-14.422976 for the tab led own there. The unigram dynamic program on the word segmentation page picks the first. MaxMatch has no access to the counts, so it cannot make this choice.

A second case shows a dead end. With D={D = \{ab, abc, cd}\} and s=s = abcd, forward MaxMatch takes abc and then has to cut off d as an unknown character, although ab, cd uses only dictionary words.

Correctness

MaxMatch is correct with respect to its own rule, not with respect to the intended words. The proof shows two facts. First, the inner loop keeps the invariant that vv is the trie node of s[i…k)s[i \ldots k) and jj is the end of the longest dictionary word seen so far, so it ends with the longest match at ii, or i+1i + 1 if there is none. Second, the outer loop keeps the invariant that WW is the list of the first tt words and that their concatenation is s[0…i)s[0 \ldots i). Since j>ij > i in each pass, the loop stops after at most nn passes with i=ni = n. The full proof is in proofs/correctness.md.

Proof: Forward maximum matching cuts the string into longest matches and stopsfull

Let s=s[0…n)s = s[0 \ldots n) be a string and DD a finite set of nonempty strings, stored in a trie TT: each node of TT is a string, the root is the empty string, the child of node uu for the character cc is ucuc, and a node is marked as a word end exactly when it is in DD. The trie holds every prefix of every word of DD and nothing else. For 0≤i<n0 \le i < n let M(i)=max⁡{j:i<j≤n, s[i…j)∈D}M(i) = \max\{ j : i < j \le n,\ s[i \ldots j) \in D \} if this set is not empty, and M(i)=i+1M(i) = i + 1 otherwise. The span s[i…j)s[i \ldots j) covers the characters i+1i+1 to jj in 1-based counting.

The claim is that MAX-MATCH returns the list w1,…,wrw_1, \ldots, w_r defined by p0=0p_0 = 0, pt=M(pt−1)p_t = M(p_{t-1}) and wt=s[pt−1…pt)w_t = s[p_{t-1} \ldots p_t), where rr is the first index with pr=np_r = n.

Lemma 1. Each run of lines L3 to L6 with 0≤i<n0 \le i < n ends with j=M(i)j = M(i).

Proof. We show this invariant at the test of line L4: vv is the trie node s[i…k)s[i \ldots k), and j=max⁡({i+1}∪{k′:i<k′≤k, s[i…k′)∈D})j = \max(\{ i + 1 \} \cup \{ k' : i < k' \le k,\ s[i \ldots k') \in D \}). At line L3, k=ik = i and vv is the root, the empty string s[i…i)s[i \ldots i), and the set of k′k' is empty, so j=i+1j = i + 1. If the test succeeds, then vv has a child for s[k]s[k], so s[i…k+1)s[i \ldots k+1) is a node, and line L5 moves vv to it and adds 1 to kk. Line L6 sets j←kj \leftarrow k exactly when the new node is in DD. The new kk is at least i+1i + 1 and larger than every older k′k', so the maximum is right again. The loop stops when k=nk = n or when s[i…k+1)s[i \ldots k+1) is not a node. In the second case, no word of DD has the prefix s[i…k+1)s[i \ldots k+1), so no s[i…k′)s[i \ldots k') with k′>kk' > k is in DD. In both cases the set of k′k' in the invariant is the full set {k′:i<k′≤n, s[i…k′)∈D}\{ k' : i < k' \le n,\ s[i \ldots k') \in D \}. If this set is empty, j=i+1=M(i)j = i + 1 = M(i). If it is not empty, its maximum is at least i+1i + 1, so jj is this maximum, which is M(i)M(i). □\square

Lemma 2 (invariant of the outer loop). At each test of line L2, the list WW is w1,…,wtw_1, \ldots, w_t and i=pti = p_t for some t≥0t \ge 0, and the concatenation of WW is s[0…i)s[0 \ldots i).

Proof. At line L1, t=0t = 0, WW is empty, i=0=p0i = 0 = p_0, and s[0…0)s[0 \ldots 0) is empty. If the test passes, then i=pt<ni = p_t < n, and by Lemma 1, j=M(pt)=pt+1j = M(p_t) = p_{t+1}. Line L7 appends s[pt…pt+1)=wt+1s[p_t \ldots p_{t+1}) = w_{t+1}, and line L8 sets i=pt+1i = p_{t+1}. The concatenation grows from s[0…pt)s[0 \ldots p_t) to s[0…pt+1)s[0 \ldots p_{t+1}). □\square

Termination. M(i)≥i+1M(i) \ge i + 1, so ii grows by at least 1 in each pass of the outer loop, and i≤ni \le n because M(i)≤nM(i) \le n. The outer loop runs at most nn times. The inner loop runs at most n−in - i times, because kk grows by 1 in each pass and stops at nn.

Theorem. MAX-MATCH(s,T)(s, T) stops and returns w1,…,wrw_1, \ldots, w_r. Their concatenation is ss, each wtw_t is the longest word of DD that starts at pt−1p_{t-1}, and wtw_t is one character only when DD has no word that starts at pt−1p_{t-1} or when the longest such word has one character.

Proof. By termination the loop ends, and then i=ni = n, because i<ni < n keeps the loop going and i≤ni \le n. By Lemma 2 with i=pt=ni = p_t = n, t=rt = r, the output is w1,…,wrw_1, \ldots, w_r and its concatenation is s[0…n)=ss[0 \ldots n) = s. The statement about each wtw_t is the definition of MM. ■\blacksquare

Remark. The theorem says that each word is a longest match at its own start, not that the list has the fewest words or the highest probability. For D={a,ab,bcd,c,d}D = \{a, ab, bcd, c, d\} and s=abcds = abcd, the algorithm returns ab,c,dab, c, d, but a,bcda, bcd has two words. The dynamic program over positions on the word-segmentation page finds a segmentation with the fewest words, or with the highest unigram probability.

Complexity

  • Time. Let mm be the length of the longest word in DD. The inner loop reads at most mm characters, because a path in the trie has at most mm edges. Each read is a child lookup, which costs O(1)O(1) with a hash table per node or an array over a fixed alphabet. So a pass of the outer loop costs O(m)O(m), and the at most nn passes cost O(nm)O(n m). The bound is reached: for D={a,am−1b}D = \{a, a^{m-1}b\}, the string ana^n makes each walk read up to m−1m - 1 characters and then cut off a single a.
  • Build. The trie of a dictionary of total length LL has at most L+1L + 1 nodes and is built in O(L)O(L) time.
  • Space. O(L)O(L) for the trie and O(n)O(n) for the output. The backward variant needs a second trie of the reversed words, and the bidirectional variant runs the algorithm twice.

Properties

  • Total. It always returns a segmentation, because of the one-character default. A model-based method can fail where no cut into dictionary words exists.
  • Greedy. Each word is fixed when it is chosen. The output is not the cut with the fewest words: with D={D = \{a, ab, bcd, c, d}\}, the string abcd gives ab, c, d, but a, bcd has two words.
  • Direction matters. With D={D = \{a, ab, bc, c, d}\}, forward MaxMatch cuts abcd as ab, c, d and backward MaxMatch cuts it as a, bc, d.
  • Deterministic. The output depends only on ss and on the set DD, not on the order of the dictionary.
  • Look-ahead. The algorithm reads at most mm characters past the current position, so it can work on a stream with a buffer of mm characters.

Variants and improvements

  • Backward maximum matching. Run from the right end, as in the example. Neither direction is better on all inputs: the Properties section has a string where the two differ, and the example has one where only backward is right.
  • Bidirectional maximum matching. Run both directions and choose by a rule such as the one above. The rules differ between systems.
  • Chunk matching. Chen and Liu (1992) look at all chunks of three words that start at the current position. Their heuristic rule 1 picks the chunk with the largest total length, and rule 2 breaks ties by the smallest variance of the word lengths. The paper adds more rules for the remaining ties.
  • Linear-time longest match. WordPiece tokenizers use the same greedy longest-match-first rule on subwords. Fast WordPiece tokenization adds failure links in the style of Aho-Corasick, so the whole text takes O(n)O(n) time instead of O(nm)O(n m).
  • Compact tries. A double-array trie stores a large dictionary in two integer arrays with O(1)O(1) child lookups.
  • Statistical segmentation. With word frequencies, the best cut under a unigram model is a shortest path in a DAG of positions. This is the usual replacement for MaxMatch.

When to use it

Use MaxMatch as a fast baseline when you have a good dictionary and no word frequencies, or to split identifiers and compound strings when errors are cheap. It is also the rule of the WordPiece tokenizer at inference time. When you have counts, use the unigram dynamic program, which costs the same O(nm)O(n m) and finds the most probable cut. For Chinese and Japanese text with many unknown words, use a trained sequence labeler, because no dictionary method can find a word that is not in its dictionary.

Pitfalls

  • No default for an unknown character. If line L3 does not set j←i+1j \leftarrow i + 1, a position where no word starts leaves jj undefined or equal to ii, and the loop never ends. The default must be set before the walk.
  • The last trie node is not the last word. The walk can pass the end of the longest word and go on along a path that ends nowhere. Line L6 must record jj only at marked nodes. Taking j←kj \leftarrow k after the loop is wrong: with D={D = \{the, theta}\} and the string thetb, the walk reaches "thet", which is not a word.
  • Greedy is not optimal. Do not claim that MaxMatch gives the fewest words or the most probable cut. The Properties section gives a counterexample to each.
  • Characters and bytes. Index the string by code points, and normalize it first (see Unicode text segmentation). A walk over UTF-8 bytes can cut a character in two.
  • Errors spread. One wrong long word can shift the next cuts, as in the example, so word error counts can be larger than the number of wrong greedy choices.

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.

maximum_matching_segmentation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maximum-matching-segmentation/. The authors are listed in prov/ZZTPQ8.jsonl.

"""Maximum matching word segmentation with a trie.

forward_max_match is the algorithm of the page: from left to right, take the
longest dictionary word that starts at the current position, or one character
when no word starts there. backward_max_match does the same from right to
left, and bidirectional_max_match picks one of the two results by a fixed rule.
unigram_segment is the dynamic program over positions that the page compares
with the greedy method. Indices are 0-based and s[i:j] is the span (i, j).
"""

from typing import Dict, Iterable, List, Mapping, Optional, Tuple

from nlslog import NEG_INF, VITERBI, safe_log

END = ""  # key of the end-of-word mark in a trie node; no edge has an empty label


def build_trie(words: Iterable[str]) -> Dict[str, dict]:
    """Return a trie of the nonempty words, as nested dicts keyed by character.

    A node that ends a word has the key END. Cost: O(L) time and space for
    words of total length L.
    """
    root: Dict[str, dict] = {}
    for w in words:
        if not w:
            raise ValueError("the dictionary holds the empty word")
        node = root
        for ch in w:
            node = node.setdefault(ch, {})
        node[END] = {}
    return root


def longest_match_end(s: str, i: int, trie: Mapping[str, dict]) -> int:
    """Return the largest j > i with s[i:j] in the dictionary, or i + 1 if there is none.

    Precondition: 0 <= i < len(s). Cost: O(min(len(s) - i, m)) steps for
    dictionary words of length at most m.
    """
    n = len(s)
    v, j, k = trie, i + 1, i  # @line L3
    while k < n and s[k] in v:  # @line L4
        v, k = v[s[k]], k + 1  # @line L5
        if END in v:  # @line L6
            j = k
    return j


def forward_max_match(s: str, trie: Mapping[str, dict]) -> List[str]:
    """Segment s by forward maximum matching.

    Each word is the longest dictionary word that starts where the previous
    word ends. Where no dictionary word starts, the word is one character.
    Cost: O(n m) time for len(s) = n and dictionary words of length at most m.
    """
    i, out = 0, []  # @line L1
    n = len(s)
    while i < n:  # @line L2
        j = longest_match_end(s, i, trie)
        out.append(s[i:j])  # @line L7
        i = j  # @line L8
    return out  # @line L9


def backward_max_match(s: str, words: Iterable[str]) -> List[str]:
    """Segment s by backward maximum matching, from the right end to the left.

    It is forward matching on the reversed string with the reversed words.
    Cost: O(n m) time after an O(L) trie build.
    """
    rtrie = build_trie(w[::-1] for w in words)
    return [w[::-1] for w in reversed(forward_max_match(s[::-1], rtrie))]


def _bidirectional_key(seg: List[str], known: set) -> Tuple[int, int, int]:
    unknown = sum(1 for w in seg if w not in known)
    single = sum(1 for w in seg if len(w) == 1)
    return (len(seg), unknown, single)


def bidirectional_max_match(s: str, words: Iterable[str]) -> List[str]:
    """Run both directions and keep one result.

    The rule: fewer words, then fewer characters left outside the dictionary,
    then fewer one-character words, and the backward result on a full tie.
    This rule is a heuristic, not an optimum of any model.
    """
    words = list(words)
    known = set(words)
    fw = forward_max_match(s, build_trie(words))
    bw = backward_max_match(s, words)
    if _bidirectional_key(fw, known) < _bidirectional_key(bw, known):
        return fw
    return bw


def unigram_segment(s: str, prob: Mapping[str, float]) -> Optional[Tuple[List[str], float]]:
    """Return a most probable segmentation of s under a unigram model, and its log probability.

    Every word must be a key of prob with a positive value. The score of a
    segmentation is the sum of the log probabilities of its words. This is a
    Viterbi recursion over the positions 0 to n: best[j] is the best score of
    a segmentation of s[0:j]. Ties go to the smallest last start i. Return
    None if s has no segmentation into dictionary words. Cost: O(n m) trie
    steps and O(n) space for the table and the back pointers.
    """
    n = len(s)
    trie = build_trie(prob)
    best = [NEG_INF] * (n + 1)
    best[0] = VITERBI.one
    back = [-1] * (n + 1)
    for i in range(n):
        if best[i] == NEG_INF:
            continue
        v, k = trie, i
        while k < n and s[k] in v:
            v, k = v[s[k]], k + 1
            if END in v:
                cand = VITERBI.times(best[i], safe_log(prob[s[i:k]]))
                if cand > best[k]:
                    best[k], back[k] = cand, i
    if best[n] == NEG_INF and n > 0:
        return None
    out: List[str] = []
    j = n
    while j > 0:
        out.append(s[back[j] : j])
        j = back[j]
    out.reverse()
    return out, best[n]
nlslog.py 152 lines
# SPDX-License-Identifier: MIT
# Shared helper of the natural-language-and-speech pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Log-space arithmetic and semirings for the natural-language-and-speech pages.

Every log is the natural log. A probability of 0 is NEG_INF (float("-inf")),
never a large negative number. A cost is -log p, so a probability of 0 is a
cost of POS_INF.

The semirings are (K, plus, times, zero, one) as on the weighted-automaton page:

    PROB      probabilities         plus = +        times = *   zero = 0       one = 1
    LOG       log probabilities     plus = log_add  times = +   zero = -inf    one = 0
    VITERBI   log probabilities     plus = max      times = +   zero = -inf    one = 0
    TROPICAL  costs -log p          plus = min      times = +   zero = +inf    one = 0
    LOG_COST  costs -log p          plus = -log_add(-a, -b), times = +, zero = +inf, one = 0
    BOOLEAN   truth values          plus = or       times = and zero = False   one = True
    COUNTING  path counts           plus = +        times = *   zero = 0       one = 1

This module holds no algorithm of any page: no forward, Viterbi, CKY, Eisner,
CTC or DTW recursion. The pages build their dynamic programs on top of it.
"""

import math
from dataclasses import dataclass
from typing import Any, Callable, Iterable, List, Sequence

NEG_INF = float("-inf")
POS_INF = float("inf")


def safe_log(p) -> float:
    """Return log p, and NEG_INF for p = 0. Raise ValueError for p < 0."""
    if p < 0:
        raise ValueError("log of a negative number")
    if p == 0:
        return NEG_INF
    return math.log(p)


def log_add(a: float, b: float) -> float:
    """Return log(exp(a) + exp(b)) = max(a, b) + log(1 + exp(-|a - b|)).

    log_add(NEG_INF, NEG_INF) is NEG_INF. No exp of a large number is taken.
    """
    if a < b:
        a, b = b, a
    if b == NEG_INF or a == POS_INF:
        return a
    return a + math.log1p(math.exp(b - a))


def log_sum(xs: Iterable[float]) -> float:
    """Return log(sum of exp(x)) over xs. An empty input gives NEG_INF."""
    xs = list(xs)
    if not xs:
        return NEG_INF
    m = max(xs)
    if m == NEG_INF or m == POS_INF:
        return m
    return m + math.log(math.fsum(math.exp(x - m) for x in xs))


def log_normalize(xs: Sequence[float]) -> List[float]:
    """Return the list x - log_sum(xs): log values whose exps sum to 1.

    Raise ValueError if every value is NEG_INF (nothing to normalize).
    """
    z = log_sum(xs)
    if z == NEG_INF:
        raise ValueError("every weight is zero")
    return [x - z for x in xs]


def log_softmax(xs: Sequence[float]) -> List[float]:
    """Return log softmax(xs): the logits xs turned into log probabilities."""
    return log_normalize(xs)


def softmax(xs: Sequence[float], temperature: float = 1.0) -> List[float]:
    """Return the probabilities exp(x / temperature) / sum, computed stably.

    The temperature must be positive. Logits of NEG_INF get probability 0.
    """
    if not temperature > 0:
        raise ValueError("the temperature must be positive")
    m = max(xs)
    if m == NEG_INF:
        raise ValueError("every logit is -inf")
    es = [math.exp((x - m) / temperature) for x in xs]
    s = math.fsum(es)
    return [e / s for e in es]


def argmax(xs: Sequence[Any]) -> int:
    """Return the first index of a largest value. Raise ValueError if xs is empty."""
    if len(xs) == 0:
        raise ValueError("argmax of an empty sequence")
    best = 0
    for i in range(1, len(xs)):
        if xs[i] > xs[best]:
            best = i
    return best


@dataclass(frozen=True)
class Semiring:
    """A semiring (K, plus, times, zero, one). idempotent is True when a plus a = a."""

    name: str
    plus: Callable[[Any, Any], Any]
    times: Callable[[Any, Any], Any]
    zero: Any
    one: Any
    idempotent: bool


def _add(a, b):
    return a + b


def _mul(a, b):
    return a * b


def _log_add_cost(a: float, b: float) -> float:
    return -log_add(-a, -b)


PROB = Semiring("probability", _add, _mul, 0, 1, False)
LOG = Semiring("log", log_add, _add, NEG_INF, 0.0, False)
VITERBI = Semiring("viterbi", max, _add, NEG_INF, 0.0, True)
TROPICAL = Semiring("tropical", min, _add, POS_INF, 0.0, True)
LOG_COST = Semiring("log-cost", _log_add_cost, _add, POS_INF, 0.0, False)
BOOLEAN = Semiring("boolean", lambda a, b: a or b, lambda a, b: a and b, False, True, True)
COUNTING = Semiring("counting", _add, _mul, 0, 1, False)


def sr_sum(sr: Semiring, xs: Iterable[Any]) -> Any:
    """Return the semiring sum of xs, and sr.zero for an empty input."""
    acc = sr.zero
    for x in xs:
        acc = sr.plus(acc, x)
    return acc


def sr_prod(sr: Semiring, xs: Iterable[Any]) -> Any:
    """Return the semiring product of xs, and sr.one for an empty input."""
    acc = sr.one
    for x in xs:
        acc = sr.times(acc, x)
    return acc
test_maximum_matching_segmentation.py 142 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maximum-matching-segmentation/. The authors are listed in prov/ZZTPQ8.jsonl.

import math
import random

import pytest

from maximum_matching_segmentation import (
    backward_max_match,
    bidirectional_max_match,
    build_trie,
    forward_max_match,
    longest_match_end,
    unigram_segment,
)
from nlslog import NEG_INF, log_add, log_sum

COUNTS = {
    "the": 30, "table": 3, "down": 4, "there": 5, "theta": 1, "bled": 1,
    "own": 2, "tab": 1, "led": 1, "a": 6, "here": 2,
}
TOTAL = sum(COUNTS.values())
PROB = {w: c / TOTAL for w, c in COUNTS.items()}
TEXT = "thetabledownthere"


def greedy_by_set(s, words):
    """Forward maximum matching with set lookups of every length, longest first."""
    words = set(words)
    m = max((len(w) for w in words), default=0)
    i, out = 0, []
    while i < len(s):
        j = i + 1
        for k in range(min(len(s), i + m), i, -1):
            if s[i:k] in words:
                j = k
                break
        out.append(s[i:j])
        i = j
    return out


def all_segmentations(s, words):
    """Every way to cut s into dictionary words, listed one by one."""
    if not s:
        return [[]]
    out = []
    for j in range(1, len(s) + 1):
        if s[:j] in words:
            out.extend([s[:j]] + rest for rest in all_segmentations(s[j:], words))
    return out


def test_page_example_forward_fails():
    trie = build_trie(COUNTS)
    assert forward_max_match(TEXT, trie) == ["theta", "bled", "own", "there"]
    assert [longest_match_end(TEXT, i, trie) for i in (0, 5, 9, 12)] == [5, 9, 12, 17]


def test_page_example_backward_and_bidirectional():
    assert backward_max_match(TEXT, COUNTS) == ["the", "table", "down", "there"]
    assert bidirectional_max_match(TEXT, COUNTS) == ["the", "table", "down", "there"]


def test_page_example_unigram_dp():
    seg, score = unigram_segment(TEXT, PROB)
    assert seg == ["the", "table", "down", "there"]
    assert score == pytest.approx(math.log(30 * 3 * 4 * 5) - 4 * math.log(56), abs=1e-12)
    assert score == pytest.approx(-8.605865, abs=1e-6)
    greedy = sum(math.log(PROB[w]) for w in ["theta", "bled", "own", "there"])
    assert greedy == pytest.approx(-13.798822, abs=1e-6)
    assert len(all_segmentations(TEXT, COUNTS)) == 3


def test_dead_end_and_fewest_words():
    words = ["ab", "abc", "cd"]
    assert forward_max_match("abcd", build_trie(words)) == ["abc", "d"]
    assert unigram_segment("abcd", {w: 1 / 3 for w in words})[0] == ["ab", "cd"]
    words = ["a", "ab", "bcd", "c", "d"]
    assert forward_max_match("abcd", build_trie(words)) == ["ab", "c", "d"]
    assert min(len(x) for x in all_segmentations("abcd", set(words))) == 2


def test_directions_differ():
    words = ["ab", "a", "bc", "d", "c"]
    assert forward_max_match("abcd", build_trie(words)) == ["ab", "c", "d"]
    assert backward_max_match("abcd", words) == ["a", "bc", "d"]


def test_edge_cases():
    assert forward_max_match("", build_trie(["a"])) == []
    assert forward_max_match("xyz", build_trie([])) == ["x", "y", "z"]
    assert backward_max_match("xyz", []) == ["x", "y", "z"]
    assert unigram_segment("", {"a": 1.0}) == ([], 0.0)
    assert unigram_segment("ab", {"a": 1.0}) is None
    with pytest.raises(ValueError):
        build_trie(["a", ""])


def test_no_underflow_in_log_space():
    s = "a" * 400
    seg, score = unigram_segment(s, {"a": 0.1, "aa": 0.001})
    assert 0.1 ** 400 == 0.0
    assert score == pytest.approx(400 * math.log(0.1), rel=1e-12)
    assert seg == ["a"] * 400


def test_random_against_oracles():
    rng = random.Random(20261118)
    for _ in range(500):
        alphabet = "abc"[: rng.randint(1, 3)]
        size = rng.randint(0, 8)
        words = sorted({"".join(rng.choice(alphabet) for _ in range(rng.randint(1, 4))) for _ in range(size)})
        s = "".join(rng.choice(alphabet) for _ in range(rng.randint(0, 10)))
        fw = forward_max_match(s, build_trie(words))
        assert "".join(fw) == s
        assert fw == greedy_by_set(s, words)
        bw = backward_max_match(s, words)
        assert "".join(bw) == s
        rev = [w[::-1] for w in words]
        assert bw == [w[::-1] for w in reversed(greedy_by_set(s[::-1], rev))]
        assert bidirectional_max_match(s, words) in (fw, bw)
        if not words:
            continue
        weights = [rng.randint(1, 9) for _ in words]
        prob = {w: c / sum(weights) for w, c in zip(words, weights)}
        cands = all_segmentations(s, set(words))
        res = unigram_segment(s, prob)
        if not cands:
            assert res is None
            continue
        seg, score = res
        assert "".join(seg) == s and all(w in prob for w in seg)
        best = max(sum(math.log(prob[w]) for w in c) for c in cands)
        assert score == pytest.approx(best, abs=1e-9)
        assert sum(math.log(prob[w]) for w in seg) == pytest.approx(best, abs=1e-9)


def test_helper_copy_basics():
    assert log_add(math.log(0.5), math.log(0.25)) == pytest.approx(-0.287682, abs=1e-6)
    assert log_sum([]) == NEG_INF

History

Dictionary matching was the usual method for Chinese segmentation before statistical models. Chen and Liu (1992) reported that maximal matching was the most effective of their heuristic rules, and they used it on chunks of three words. Wong and Chan (1996) used forward maximum matching with a lexicon of about 80,000 words and word binding forces, and they describe the method as greedy and suboptimal. Sproat, Shih, Gale and Chang (1996) replaced the greedy choice with a weighted finite-state model that scores whole segmentations. The same greedy longest-match rule appears in lexers as the maximal munch rule and in WordPiece subword tokenizers.

References

  1. Keh-Jiann Chen and Shing-Huan Liu, Word identification for Mandarin Chinese sentences, COLING 1992 Volume 1, Nantes, Section 3.1, Matching algorithm and disambiguation rules (the three-word chunks and heuristic rules 1 and 2)
  2. Pak-kwong Wong and Chorkin Chan, Chinese word segmentation based on maximum matching and word binding force, COLING 1996 Volume 1, Copenhagen, pages 200 to 203, Section 2 (the forward maximum matching method) and the description of the lexicon tables
  3. Richard Sproat, Chilin Shih, William Gale and Nancy Chang, A stochastic finite-state word-segmentation algorithm for Chinese, Computational Linguistics 22(3), 1996, pages 377 to 404 (the weighted finite-state model that scores whole segmentations)

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.trie_build
  • a full proof of time.worst
  • a full proof of space.output
  • a full proof of space.trie
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