Algorithmadvanced
Morfessor
Also called Morfessor baseline.
Unsupervised morphological segmentation of Creutz and Lagus that splits words into morphs by minimizing a two-part MDL code length of lexicon and corpus.
- Solves
- Morphological analysis
- Time
- O(W n^3) epochO(n^3) resplit
- Space
- O(L) model
- Where
- L = the total length of the word types; W = the number of word types; n = the length of the longest word
- Model
- Word RAM
- Properties
- randomizednot exactofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Mathias Creutz, Krista Lagus, 2002
Morfessor is a family of methods that learn to split words into morph-like units without any labeled data. Its first member, now called the Baseline, comes from Creutz and Lagus (2002). It searches for a lexicon of morphs and a segmentation of the corpus that make the total description short: the cost of writing down the lexicon plus the cost of the corpus coded with it. The search splits words recursively in two and keeps a split only when it lowers the total cost.
In plain words
A word list can be stored in two parts: a dictionary of pieces, and each word written as a row of pieces from the dictionary. Long pieces make the rows short but the dictionary big. Single letters make the dictionary tiny but the rows long. Pieces such as "walk", "talk", "ed" and "ing" are a good middle: few pieces, used again and again.
Morfessor looks for this middle. It takes one word, tries it whole and cut in two at every place, and keeps the choice that makes the total smallest. If it cut the word, it does the same to each half. It goes over all the words many times, in random order, until nothing improves. It is a greedy search, so it can get stuck at a choice that a cleverer search would beat.
The problem
The input is a corpus of word types with counts . The output is an analysis: for each word , a list of morphs whose concatenation is . Let be the number of times the morph is used in the corpus, weighted by the counts, and . Following the minimum description length principle, the Baseline minimizes the two-part cost of Creutz and Lagus (2002, Section 2.1), here in nats (natural logs):
The first part is the code length of the corpus under the maximum likelihood unigram model of morphs; the second is the code length of the lexicon, with per character. Creutz and Lagus use 5 bits per character, enough for 32 lower-case letters, which is nats.
The algorithm
The search reprocesses one word at a time. The split of a string with count tries whole and every cut into two parts:
RESPLIT(s, f)R1 best ← the cost with s added f times; cut ← noneR2 for i ← 1 to len(s) - 1R3 c ← the cost with s[:i] and s[i:] added f times eachR4 if c < best then best ← c; cut ← iR5 if cut is none then add s f times and return [s]R6 left ← RESPLIT(s[:cut], f)R7 return left followed by RESPLIT(s[cut:], f)
The main loop goes over the word types in a random order and repeats until an epoch lowers the cost by less than a tolerance:
MORFESSOR(corpus, rng)M1 give each word the analysis [w] and count its morphsM2 repeatM3 for each word w, in an order shuffled by rngM4 remove the morphs of the analysis of w (f_w times each)M5 new ← RESPLIT(w, f_w)M6 if the cost went up then put the old analysis back, else keep newM7 until the cost of an epoch drops by less than the toleranceM8 return the analysis
The 2002 search reads word tokens online and reprocesses a word each time it appears, and a "dreaming" stage goes over the words seen so far in random order. The code here runs only the dreaming form, in epochs over the word types. Creutz and Lagus keep the splits in a shared tree, so a chunk split once is split the same way in every word; the code here keeps one list of morphs per word type, which is simpler. Line M6 is a choice of this page: it makes the cost never rise.
A new word is segmented with the learned lexicon by a Viterbi pass over its positions, in the TROPICAL semiring (costs , plus = min, times = +). A word with no split into known morphs stays whole.
Example
Take the corpus walk 4, walked 3, walking 3, talk 3, talked 2, talking 2, jump 3, jumped 2 and jumping 2. At the start every word is one morph: tokens, a data cost of 52.000 nats, and a lexicon of 51 characters, which costs , so the total is 228.752.
With the seed 0 the first word is walked. Removing it and putting it back whole gives 228.752. The cut walk + ed gives 219.527, because walk is already in the lexicon and only "ed" is new. Every other cut, such as w + alked, adds two new morphs and gives 238.171. So walked becomes walk + ed. The two parts are not split further.
After one epoch the analysis is walk, walk + ed, walk + ing, talk, talk + ed, talk + ing, jump, jump + ed and jump + ing. The lexicon is walk 10, ed 7, ing 7, talk 7 and jump 7: tokens, a data cost of 60.717 nats, and 17 characters, which cost 58.918, for a total of 119.634. The second epoch changes nothing, and the search stops. A new word "walkjump" is segmented as walk + jump. The word "jumps" stays whole, because "s" is not a morph.
Correctness
RESPLIT always returns morphs that join back to the word, since it only cuts a string in two and recurses on the halves. The model keeps , and the lexicon length up to date under each change of a count, so each cost it compares is the exact cost. Each pass over a word either lowers the cost or restores the old analysis, so the cost never rises from epoch to epoch. These are theorems, proved in proofs/correctness.md.
The search is greedy and finds a local optimum, not the global one. With the corpus bb 11 and bbbb 9, the search keeps the morph bb in both words, at a cost of . Writing both words as single b's costs only , but the search never gets there: splitting bb alone adds b and keeps bb in the lexicon for bbbb, which costs more. That the morphs found are close to linguistic morphemes is a measurement, which Creutz and Lagus report for Finnish and English.
Proof: The Morfessor search returns segmentations of the words, keeps the cost up to date, and never raises the cost, but it can stop at a local optimumfull
Notation. The corpus gives each word type a count . An analysis gives each word a list of morphs whose concatenation is . The morph counts are , the total is , and the lexicon is the set of morphs with . All logs are natural logs. With the maximum likelihood estimate of Creutz and Lagus, the two-part cost is
since the morph is used times and . Here is the cost of one character of the lexicon, in nats ( for 5 bits).
Lemma 1 (the counts). After any sequence of calls ADD(, ) that keeps every count nonnegative, the model holds , and the total length of the lexicon, so COST returns the formula above for the current counts.
Proof. Each call changes one count from to . It adds to , replaces the term of by (with ), and adds or removes from the lexicon length exactly when the count leaves or reaches . By induction on the number of calls, the three values match the counts. COST-WITH adds and then removes the same amounts, so it leaves the model as it found it.
Theorem 1 (RESPLIT). For a string and a count , RESPLIT stops, returns a list of nonempty strings whose concatenation is , and adds to the count of each returned morph, once per use.
Proof. By induction on . If line R5 keeps whole, it adds to and returns . Otherwise there is a cut , and lines R6 and R7 call RESPLIT on and , which are shorter, nonempty, and join to . By the induction hypothesis each call stops, returns a list that joins to its part and adds for each morph it returns, so the joined list has the claimed properties.
Theorem 2 (the cost never rises). Each pass of lines M4 to M6 over one word keeps an analysis of the corpus whose model counts are the counts of the analysis, and the cost after the pass is at most the cost before it. So the costs of the trace never increase, and MORFESSOR stops after at most the given number of epochs.
Proof. Before the pass, the model counts are those of (at the start by line M1, and later by induction). Line M4 removes from each morph of , and line M5 adds for each morph of the new list (Theorem 1), so the counts are those of with replaced by the new list, which joins to . If the new cost is larger than the cost before, line M6 removes the new morphs and adds back the old ones, which restores the counts and the cost of . In both cases the cost does not rise, by Lemma 1. Each epoch is a sequence of such passes, so its cost is at most the cost at its start. The loop runs at most max-epochs times.
Theorem 3 (only a local optimum). The result need not have the least cost over all analyses.
Proof. Take the corpus bb 11 times and bbbb 9 times. Start from the words whole. With and either order of the two words (the test file runs both), RESPLIT compares each word whole with its splits while the other word is still in the lexicon, and the search ends with bb as bb and bbbb as bb + bb: one morph type of 2 characters, a data cost of (one morph has probability 1), and a cost of . The analysis with every word as single b's has one morph type of 1 character and a cost of . The test file runs this case and checks the global optimum by brute force over all analyses.
The cost is a sum over the corpus, and the search changes one word at a time with a greedy recursive split, so the result depends on the order of the words and on the start. Theorem 2 makes the search a descent method; whether its result is a good segmentation is a matter of measurement.
Complexity
Let be the length of a word. In the word-RAM model, with the morph counts in a hash table, one cost evaluation changes counts and costs time to hash the strings. RESPLIT tries cuts at each node of its recursion, and the recursion has at most levels, each over parts of total length at most , so one word costs evaluations and time. An epoch over word types costs time. The model takes space for word types of total length . The number of epochs is not bounded by a formula; in the examples it is small.
Properties
- No labels. Only word counts are needed.
- Two-part code. A longer lexicon must pay for itself by shortening the coded corpus, which stops the search from keeping whole words.
- Order-dependent. The result depends on the order of the words and on the random seed, as for any greedy local search.
- Flat morphs. The Baseline does not label morphs as stems or affixes.
Variants and improvements
- Shared split tree. The 2002 search keeps every split in one tree of chunks with counts, so the split of a chunk is shared by every word that contains it.
- Later models. Creutz and Lagus (2007) describe the Baseline together with the later models of the Morfessor family.
- Subword vocabularies. The unigram language model tokenization of Kudo uses a similar unigram model of pieces, trained by EM with pruning instead of an MDL cost.
When to use it
Use it to find morph-like units in a language with rich morphology, such as Finnish or Turkish, when no analyzer or labeled data exists, for example to build a vocabulary for speech recognition. When a rule-based analyzer exists, two-level morphology or another finite-state analyzer gives linguistic analyses with features, which Morfessor does not.
Pitfalls
- Local optima. The greedy split can keep a long morph that a global search would replace, as the bb example shows. Several random orders and more epochs help but do not guarantee the optimum.
- The value of K. The cost per lexicon character sets the balance: a large gives few short morphs and long analyses, and a small keeps whole words.
- Not morphemes. Morphs are strings that compress well, not morphemes with meaning; they can cut across morpheme boundaries.
- Underflow. The probability of the corpus is a product of thousands of morph probabilities; compute the cost as a sum of logs, never as a product.
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/morfessor/. The authors are listed in prov/TM8W3C.jsonl.
"""Morfessor Baseline search of Creutz and Lagus, with the two-part cost of 2002.
The corpus is a dict from word types to counts. An analysis gives each word
type a list of morphs whose concatenation is the word. The morph counts c(m)
are the sums of the word counts over the uses of m, and C is their total.
cost = sum over morph tokens of -ln(c(m) / C) + K * (sum over morph types of len(m))
= C ln C - sum_m c(m) ln c(m) + K * (total length of the lexicon)
All logs are natural logs, so the cost is in nats. K is the cost of one
character of the lexicon: 5 bits, that is 5 ln 2 nats, by default.
The search reprocesses the word types in a random order. For each word it
removes the word's morphs, tries the word whole and every split into two
parts, takes the cheapest, and recurses on the two parts. If the new analysis
of the word costs more than the old one, the old one is put back, so the cost
never rises. The search is greedy and finds a local optimum.
"""
import math
import random
from typing import Dict, List, Optional, Tuple
from nlslog import safe_log
K_DEFAULT = 5 * math.log(2)
def _xlogx(c: int) -> float:
return c * safe_log(c) if c > 0 else 0.0
def cost_of(corpus: Dict[str, int], analysis: Dict[str, List[str]], k: float = K_DEFAULT) -> float:
"""The two-part cost of an analysis, computed from scratch."""
counts: Dict[str, int] = {}
for w, f in corpus.items():
for m in analysis[w]:
counts[m] = counts.get(m, 0) + f
total = sum(counts.values())
data = _xlogx(total) - math.fsum(_xlogx(c) for c in counts.values())
return data + k * sum(len(m) for m in counts)
class Model:
"""Morph counts with the cost kept up to date."""
def __init__(self, k: float = K_DEFAULT):
self.k = k
self.counts: Dict[str, int] = {}
self.total = 0
self.sum_xlogx = 0.0
self.lexicon_chars = 0
def add(self, m: str, d: int) -> None:
"""Add d (which may be negative) to the count of the morph m."""
old = self.counts.get(m, 0)
new = old + d
if new < 0:
raise ValueError("negative morph count")
self.sum_xlogx += _xlogx(new) - _xlogx(old)
self.total += d
if old == 0 and new > 0:
self.lexicon_chars += len(m)
if old > 0 and new == 0:
self.lexicon_chars -= len(m)
if new == 0:
self.counts.pop(m, None)
else:
self.counts[m] = new
def cost(self) -> float:
return _xlogx(self.total) - self.sum_xlogx + self.k * self.lexicon_chars
def cost_with(self, morphs: List[str], f: int) -> float:
"""The cost if each morph of the list were added f times."""
for m in morphs:
self.add(m, f)
c = self.cost()
for m in morphs:
self.add(m, -f)
return c
def resplit(model: Model, s: str, f: int) -> List[str]:
"""Analyze s (with count f) by recursive binary splitting; add its morphs to the model."""
best, cut = model.cost_with([s], f), None # @line R1
for i in range(1, len(s)): # @line R2
c = model.cost_with([s[:i], s[i:]], f) # @line R3
if c < best - 1e-12: # @line R4
best, cut = c, i
if cut is None: # @line R5
model.add(s, f)
return [s]
left = resplit(model, s[:cut], f) # @line R6
return left + resplit(model, s[cut:], f) # @line R7
def morfessor(corpus: Dict[str, int], rng: random.Random, k: float = K_DEFAULT,
tol: float = 1e-9, max_epochs: int = 50,
start: Optional[Dict[str, List[str]]] = None) -> Tuple[Dict[str, List[str]], List[float]]:
"""Return the analysis and the cost after each epoch (the first value is the start)."""
model = Model(k)
analysis = {w: list(start[w]) if start else [w] for w in corpus} # @line M1
for w, f in corpus.items():
for m in analysis[w]:
model.add(m, f)
trace = [cost_of(corpus, analysis, k)]
for _ in range(max_epochs): # @line M2
order = sorted(corpus)
rng.shuffle(order)
for w in order: # @line M3
f = corpus[w]
before = model.cost()
for m in analysis[w]: # @line M4
model.add(m, -f)
new = resplit(model, w, f) # @line M5
if model.cost() > before + 1e-12: # @line M6
for m in new:
model.add(m, -f)
for m in analysis[w]:
model.add(m, f)
else:
analysis[w] = new
trace.append(cost_of(corpus, analysis, k)) # @line M7
if trace[-2] - trace[-1] < tol:
break
return analysis, trace # @line M8
def segment(word: str, lexicon: Dict[str, int]) -> List[str]:
"""Segment a new word with a learned lexicon (morph counts): the most probable
split into known morphs by a Viterbi pass in the TROPICAL semiring over
costs -ln(c(m) / C); a word with no such split is returned whole."""
total = sum(lexicon.values())
n = len(word)
best = [math.inf] * (n + 1)
back = [0] * (n + 1)
best[0] = 0.0
for j in range(1, n + 1):
for i in range(j):
m = word[i:j]
if m in lexicon and best[i] < math.inf:
c = best[i] - safe_log(lexicon[m] / total)
if c < best[j]:
best[j], back[j] = c, i
if best[n] == math.inf:
return [word]
out, j = [], n
while j > 0:
out.append(word[back[j]:j])
j = back[j]
return out[::-1]
def lexicon_of(corpus: Dict[str, int], analysis: Dict[str, List[str]]) -> Dict[str, int]:
counts: Dict[str, int] = {}
for w, f in corpus.items():
for m in analysis[w]:
counts[m] = counts.get(m, 0) + f
return counts
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_morfessor.py 127 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/morfessor/. The authors are listed in prov/TM8W3C.jsonl.
import itertools
import math
import random
from morfessor import K_DEFAULT, Model, cost_of, lexicon_of, morfessor, resplit, segment
PAGE = {"walk": 4, "walked": 3, "walking": 3, "talk": 3, "talked": 2, "talking": 2,
"jump": 3, "jumped": 2, "jumping": 2}
def splits(w):
for mask in range(1 << (len(w) - 1)):
out, last = [], 0
for i in range(1, len(w)):
if mask >> (i - 1) & 1:
out.append(w[last:i])
last = i
out.append(w[last:])
yield out
def brute_force(corpus, k):
words = sorted(corpus)
return min(cost_of(corpus, dict(zip(words, combo)), k)
for combo in itertools.product(*[list(splits(w)) for w in words]))
def random_corpus(rng):
return {"".join(rng.choice("ab") for _ in range(rng.randint(2, 5))): rng.randint(1, 30)
for _ in range(rng.randint(2, 4))}
def test_cost_formula():
# 2 tokens of "ab" and 1 of "c": data cost 3 ln 3 - 2 ln 2, lexicon 3 characters.
corpus = {"ab": 2, "c": 1}
want = 3 * math.log(3) - 2 * math.log(2) + 3 * K_DEFAULT
assert abs(cost_of(corpus, {"ab": ["ab"], "c": ["c"]}) - want) < 1e-12
assert abs(K_DEFAULT - 5 * math.log(2)) < 1e-15
def test_page_example():
analysis, trace = morfessor(PAGE, random.Random(0))
assert {w: "+".join(a) for w, a in analysis.items()} == {
"walk": "walk", "walked": "walk+ed", "walking": "walk+ing", "talk": "talk", "talked": "talk+ed",
"talking": "talk+ing", "jump": "jump", "jumped": "jump+ed", "jumping": "jump+ing"}
assert [round(c, 3) for c in trace] == [228.752, 119.634, 119.634]
assert lexicon_of(PAGE, analysis) == {"walk": 10, "ed": 7, "ing": 7, "talk": 7, "jump": 7}
lex = lexicon_of(PAGE, analysis)
assert segment("talked", lex) == ["talk", "ed"]
assert segment("walkjump", lex) == ["walk", "jump"]
assert segment("jumps", lex) == ["jumps"]
def test_first_split_of_walked():
model = Model()
for w, f in PAGE.items():
model.add(w, f)
model.add("walked", -3)
whole = model.cost_with(["walked"], 3)
cuts = {i: model.cost_with(["walked"[:i], "walked"[i:]], 3) for i in range(1, 6)}
assert round(whole, 3) == 228.752 and round(cuts[4], 3) == 219.527
assert min(cuts, key=cuts.get) == 4 and all(round(c, 3) == 238.171 for i, c in cuts.items() if i != 4)
def test_analyses_concatenate_and_counts_stay_consistent():
rng = random.Random(3)
for _ in range(40):
corpus = random_corpus(rng)
analysis, trace = morfessor(corpus, random.Random(rng.randint(0, 99)), k=rng.choice([1.0, K_DEFAULT]))
assert all("".join(a) == w for w, a in analysis.items())
assert all(b <= a + 1e-9 for a, b in zip(trace, trace[1:]))
def test_the_cost_never_rises_on_any_reprocessing():
rng = random.Random(4)
for _ in range(40):
corpus = random_corpus(rng)
start = {w: rng.choice(list(splits(w))) for w in corpus}
before = cost_of(corpus, start)
analysis, trace = morfessor(corpus, random.Random(1), start=start)
assert abs(trace[0] - before) < 1e-9 and trace[-1] <= before + 1e-9
def test_resplit_keeps_the_model_counts_right():
rng = random.Random(5)
for _ in range(30):
corpus = random_corpus(rng)
model = Model(1.0)
analysis = {}
for w, f in corpus.items():
analysis[w] = resplit(model, w, f)
assert model.counts == lexicon_of(corpus, analysis)
assert abs(model.cost() - cost_of(corpus, analysis, 1.0)) < 1e-9
def test_local_optimum_against_brute_force():
corpus = {"bb": 11, "bbbb": 9}
analysis, trace = morfessor(corpus, random.Random(0))
assert analysis == {"bb": ["bb"], "bbbb": ["bb", "bb"]}
assert abs(trace[-1] - 2 * K_DEFAULT) < 1e-9
assert abs(brute_force(corpus, K_DEFAULT) - K_DEFAULT) < 1e-9 # every word as single b's
firsts = set()
for seed in range(10):
order = sorted(corpus)
random.Random(seed).shuffle(order)
firsts.add(order[0])
assert morfessor(corpus, random.Random(seed))[0] == analysis
assert firsts == {"bb", "bbbb"} # both orders were tried
rng = random.Random(6)
for _ in range(25):
corpus = random_corpus(rng)
_, trace = morfessor(corpus, random.Random(0), k=1.0)
assert trace[-1] >= brute_force(corpus, 1.0) - 1e-9
def test_log_space_avoids_underflow():
# 2000 tokens of a morph of probability 1/2: the product underflows, the cost does not.
corpus = {"ab": 1000, "cd": 1000}
product = 1.0
for _ in range(2000):
product *= 0.5
assert product == 0.0
c = cost_of(corpus, {"ab": ["ab"], "cd": ["cd"]})
assert abs(c - (2000 * math.log(2) + 4 * K_DEFAULT)) < 1e-9
History
Creutz and Lagus (2002) presented two methods for unsupervised segmentation of words into morphs, tested on Finnish and English. The first, recursive splitting under an MDL cost, became the Morfessor Baseline. Their 2007 article in ACM Transactions on Speech and Language Processing describes the Morfessor family, with the Baseline in Section 4.1.
References
- Mathias Creutz and Krista Lagus, Unsupervised discovery of morphemes, Proceedings of the ACL-02 Workshop on Morphological and Phonological Learning, 2002, pages 21 to 30, Section 2, Method 1, Recursive segmentation and MDL cost; Section 2.1 (the cost, with k = 5 bits per character, page 23) and Section 2.2 (the recursive search, the reprocessing of seen words and the dreaming stage, pages 23 and 24)
- Mathias Creutz and Krista Lagus, Unsupervised models for morpheme segmentation and morphology learning, ACM Transactions on Speech and Language Processing 4(1), article 3, 2007, Section 4.1, the Baseline model
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 TM8W3C Edit this page History Report an error Markdown