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.
- Solves
- Word segmentation
- 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
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 and a finite dictionary of nonempty strings. The output is a list of strings whose concatenation is . A span is written with fencepost indices: it covers the characters to in 1-based counting. MaxMatch does not optimize a score. Its output is defined by the rule itself: is the longest word of that is a prefix of the rest of the string, or one character if there is no such word.
The algorithm
The trie holds the words of . Each node is a prefix of a word, and a node is marked when it is a full word.
MAX-MATCH(s, T) ▷ |s| = n, T is a trie of D- 1
i ← 0, W ← empty list - 2
while i < n do - 3
v ← root of T, j ← i + 1, k ← i ▷ j is the end of the longest match so far - 4
while k < n and v has a child for s[k] do - 5
v ← that child, k ← k + 1 - 6
if v is marked as a word then j ← k - 7
append s[i..j) to W - 8
i ← j - 9
return W
Line L3 sets the default end , so that a position where no word starts gives a word of one character. Lines L4 to L6 follow the characters of 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 the, table, down, there, theta, bled, own, tab, led, a, here and the string thetabledownthere, with . The intended reading is "the table down there". In the table, "ends" lists every at which line L6 found a word.
| step | characters read in L4 and L5 | why the walk stops | ends | 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 | 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 . The string has exactly three segmentations into dictionary words. Their natural log probabilities are for the table down there, for theta bled own there, and 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 ab, abc, cd and 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 is the trie node of and is the end of the longest dictionary word seen so far, so it ends with the longest match at , or if there is none. Second, the outer loop keeps the invariant that is the list of the first words and that their concatenation is . Since in each pass, the loop stops after at most passes with . The full proof is in proofs/correctness.md.
Proof: Forward maximum matching cuts the string into longest matches and stopsfull
Let be a string and a finite set of nonempty strings, stored in a trie : each node of is a string, the root is the empty string, the child of node for the character is , and a node is marked as a word end exactly when it is in . The trie holds every prefix of every word of and nothing else. For let if this set is not empty, and otherwise. The span covers the characters to in 1-based counting.
The claim is that MAX-MATCH returns the list defined by , and , where is the first index with .
Lemma 1. Each run of lines L3 to L6 with ends with .
Proof. We show this invariant at the test of line L4: is the trie node , and . At line L3, and is the root, the empty string , and the set of is empty, so . If the test succeeds, then has a child for , so is a node, and line L5 moves to it and adds 1 to . Line L6 sets exactly when the new node is in . The new is at least and larger than every older , so the maximum is right again. The loop stops when or when is not a node. In the second case, no word of has the prefix , so no with is in . In both cases the set of in the invariant is the full set . If this set is empty, . If it is not empty, its maximum is at least , so is this maximum, which is .
Lemma 2 (invariant of the outer loop). At each test of line L2, the list is and for some , and the concatenation of is .
Proof. At line L1, , is empty, , and is empty. If the test passes, then , and by Lemma 1, . Line L7 appends , and line L8 sets . The concatenation grows from to .
Termination. , so grows by at least 1 in each pass of the outer loop, and because . The outer loop runs at most times. The inner loop runs at most times, because grows by 1 in each pass and stops at .
Theorem. MAX-MATCH stops and returns . Their concatenation is , each is the longest word of that starts at , and is one character only when has no word that starts at or when the longest such word has one character.
Proof. By termination the loop ends, and then , because keeps the loop going and . By Lemma 2 with , , the output is and its concatenation is . The statement about each is the definition of .
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 and , the algorithm returns , but 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 be the length of the longest word in . The inner loop reads at most characters, because a path in the trie has at most edges. Each read is a child lookup, which costs with a hash table per node or an array over a fixed alphabet. So a pass of the outer loop costs , and the at most passes cost . The bound is reached: for , the string makes each walk read up to characters and then cut off a single a.
- Build. The trie of a dictionary of total length has at most nodes and is built in time.
- Space. for the trie and 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 a, ab, bcd, c, d, the string abcd gives ab, c, d, but a, bcd has two words.
- Direction matters. With 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 and on the set , not on the order of the dictionary.
- Look-ahead. The algorithm reads at most characters past the current position, so it can work on a stream with a buffer of 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 time instead of .
- Compact tries. A double-array trie stores a large dictionary in two integer arrays with 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 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 , a position where no word starts leaves undefined or equal to , 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 only at marked nodes. Taking after the loop is wrong: with 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.
# 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
- 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)
- 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
- 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.
| 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 ZZTPQ8 Edit this page History Report an error Markdown