Algorithm Search⌘K

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.

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
Properties
randomizednot exactofflinerecursive
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 fwf_w. The output is an analysis: for each word ww, a list of morphs whose concatenation is ww. Let c(m)c(m) be the number of times the morph mm is used in the corpus, weighted by the counts, and C=∑mc(m)C = \sum_m c(m). 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):

cost=∑morph tokens−ln⁡c(m)C+K∑morph typeslen(m)=Cln⁡C−∑mc(m)ln⁡c(m)+K∑morph typeslen(m).\mathrm{cost} = \sum_{\text{morph tokens}} -\ln \frac{c(m)}{C} + K \sum_{\text{morph types}} \mathrm{len}(m) = C \ln C - \sum_m c(m) \ln c(m) + K \sum_{\text{morph types}} \mathrm{len}(m).

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 KK per character. Creutz and Lagus use 5 bits per character, enough for 32 lower-case letters, which is K=5ln⁡2=3.4657K = 5 \ln 2 = 3.4657 nats.

The algorithm

The search reprocesses one word at a time. The split of a string ss with count ff tries ss whole and every cut into two parts:

  1. RESPLIT(s, f)
  2. R1 best ← the cost with s added f times; cut ← none
  3. R2 for i ← 1 to len(s) - 1
  4. R3 c ← the cost with s[:i] and s[i:] added f times each
  5. R4 if c < best then best ← c; cut ← i
  6. R5 if cut is none then add s f times and return [s]
  7. R6 left ← RESPLIT(s[:cut], f)
  8. 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:

  1. MORFESSOR(corpus, rng)
  2. M1 give each word the analysis [w] and count its morphs
  3. M2 repeat
  4. M3 for each word w, in an order shuffled by rng
  5. M4 remove the morphs of the analysis of w (f_w times each)
  6. M5 new ← RESPLIT(w, f_w)
  7. M6 if the cost went up then put the old analysis back, else keep new
  8. M7 until the cost of an epoch drops by less than the tolerance
  9. M8 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 −ln⁡(c(m)/C)-\ln (c(m)/C), 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: C=24C = 24 tokens, a data cost of 52.000 nats, and a lexicon of 51 characters, which costs 51K=176.75351 K = 176.753, 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: C=38C = 38 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 CC, ∑mc(m)ln⁡c(m)\sum_m c(m) \ln c(m) 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 2K2K. Writing both words as single b's costs only KK, 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 ww a count fw≥1f_w \ge 1. An analysis AA gives each word ww a list of morphs A(w)A(w) whose concatenation is ww. The morph counts are c(m)=∑wfw⋅(the number of times m is in A(w))c(m) = \sum_w f_w \cdot (\text{the number of times } m \text{ is in } A(w)), the total is C=∑mc(m)C = \sum_m c(m), and the lexicon is the set of morphs with c(m)>0c(m) > 0. All logs are natural logs. With the maximum likelihood estimate p(m)=c(m)/Cp(m) = c(m) / C of Creutz and Lagus, the two-part cost is

cost(A)=∑tokens−ln⁡p(m)+K∑m∈lexicon∣m∣=Cln⁡C−∑mc(m)ln⁡c(m)+K∑m∈lexicon∣m∣,\mathrm{cost}(A) = \sum_{\text{tokens}} -\ln p(m) + K \sum_{m \in \text{lexicon}} |m| = C \ln C - \sum_m c(m) \ln c(m) + K \sum_{m \in \text{lexicon}} |m|,

since the morph mm is used c(m)c(m) times and ∑mc(m)ln⁡(c(m)/C)=∑mc(m)ln⁡c(m)−Cln⁡C\sum_m c(m) \ln (c(m) / C) = \sum_m c(m) \ln c(m) - C \ln C. Here K>0K > 0 is the cost of one character of the lexicon, in nats (5ln⁡25 \ln 2 for 5 bits).

Lemma 1 (the counts). After any sequence of calls ADD(mm, dd) that keeps every count nonnegative, the model holds CC, S=∑mc(m)ln⁡c(m)S = \sum_m c(m) \ln c(m) and the total length of the lexicon, so COST returns the formula above for the current counts.

Proof. Each call changes one count from cc to c+dc + d. It adds dd to CC, replaces the term cln⁡cc \ln c of SS by (c+d)ln⁡(c+d)(c + d) \ln (c + d) (with 0ln⁡0=00 \ln 0 = 0), and adds or removes ∣m∣|m| from the lexicon length exactly when the count leaves or reaches 00. 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. □\square

Theorem 1 (RESPLIT). For a string ss and a count ff, RESPLIT stops, returns a list of nonempty strings whose concatenation is ss, and adds ff to the count of each returned morph, once per use.

Proof. By induction on ∣s∣|s|. If line R5 keeps ss whole, it adds ff to c(s)c(s) and returns [s][s]. Otherwise there is a cut 0<i<∣s∣0 < i < |s|, and lines R6 and R7 call RESPLIT on s[:i]s[{:}i] and s[i:]s[i{:}], which are shorter, nonempty, and join to ss. By the induction hypothesis each call stops, returns a list that joins to its part and adds ff for each morph it returns, so the joined list has the claimed properties. □\square

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 AA (at the start by line M1, and later by induction). Line M4 removes fwf_w from each morph of A(w)A(w), and line M5 adds fwf_w for each morph of the new list (Theorem 1), so the counts are those of AA with A(w)A(w) replaced by the new list, which joins to ww. 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 AA. 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. □\square

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 K=5ln⁡2K = 5 \ln 2 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 00 (one morph has probability 1), and a cost of 2K2K. The analysis with every word as single b's has one morph type of 1 character and a cost of K<2KK < 2K. The test file runs this case and checks the global optimum by brute force over all analyses. □\square

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 nn be the length of a word. In the word-RAM model, with the morph counts in a hash table, one cost evaluation changes O(1)O(1) counts and costs O(n)O(n) time to hash the strings. RESPLIT tries O(n)O(n) cuts at each node of its recursion, and the recursion has at most nn levels, each over parts of total length at most nn, so one word costs O(n2)O(n^2) evaluations and O(n3)O(n^3) time. An epoch over WW word types costs O(Wn3)O(W n^3) time. The model takes O(L)O(L) space for word types of total length LL. 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 KK gives few short morphs and long analyses, and a small KK 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.

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

  1. 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)
  2. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.epoch
  • a full proof of time.resplit
  • a full proof of space.model
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
  • at least three sources
  • a scene preset for the example