Algorithm Search⌘K

Algorithmcore

Yarowsky algorithm

Also called one sense per collocation bootstrapping.

Semi-supervised sense disambiguation that grows a decision list from a few seed collocations using one sense per discourse and one sense per collocation.

Time
O(T (n m + F log F + n F)) worst
Space
O(n m + F) extra
Where
F = the number of distinct features; T = the number of rounds; m = the largest number of features of one occurrence; n = the number of occurrences of the target word
Properties
deterministicnot exactofflineiterativenot supervised
Origin
David Yarowsky, 1995

The Yarowsky algorithm solves word sense disambiguation for one ambiguous word from a large unlabeled corpus and a few seed collocations, for example "plant life" for the living sense of "plant" and "manufacturing plant" for the factory sense. The seeds label a small part of the occurrences. A decision list trained on these labels then labels more occurrences, the list is trained again on the larger set, and the loop goes on until the labels stop changing. Two heuristic constraints drive it. One sense per collocation says that a nearby word gives strong and consistent evidence for one sense. One sense per discourse says that an ambiguous word keeps one sense within one document, so a label can spread to the other occurrences in the same document. The Lesk algorithm uses a dictionary instead of a corpus.

In plain words

Suppose you want to tell the living "plant" from the factory "plant" in a big pile of text. You know two clues for sure: "plant life" is the living kind and "manufacturing plant" is the factory kind. Those two clues mark a few sentences.

Now look at the marked sentences and notice which other words appear near "plant" in each group. Words such as "water" go with the living kind, and words such as "workers" go with the factory kind. Use these new clues to mark more sentences, and learn more clues from them. If one document already uses "plant" in one sense, give that sense to the other unmarked uses of "plant" in the same document. Stop when a round marks nothing new.

The problem

The input is a list of nn occurrences of one target word, each with its tokens and, if known, the discourse (document) it is in, a list of senses, and a map from seed features to senses. The features of an occurrence are its collocations: the word just before the target (−1:w-1{:}w), the word just after it (+1:w+1{:}w), and each word that is not a stop word within kk tokens (win:w\text{win}{:}w). The output is a sense or ⊥\bot (no decision) for each occurrence, and a decision list that can label new occurrences.

A decision list is a list of rules (f,s,λ)(f, s, \lambda) sorted by decreasing score λ\lambda. It labels an occurrence with the sense of the first rule whose feature the occurrence has. For labels yy, let c(f,σ)c(f, \sigma) count the occurrences labeled σ\sigma that have the feature ff. The rule for ff takes the sense sfs_f with the largest count and the smoothed log ratio

λf=ln⁡c(f,sf)+α∑σ≠sfc(f,σ)+α(ln⁡, nats),\lambda_f = \ln \frac{c(f, s_f) + \alpha}{\sum_{\sigma \ne s_f} c(f, \sigma) + \alpha} \quad (\ln,\ \text{nats}),

with a constant α>0\alpha > 0. With two senses this is the log of the ratio of the two smoothed counts, as in Yarowsky 1994.

The algorithm

  1. YAROWSKY(occurrences, seeds, senses, alpha, theta, T)
  2. 1y ← the seed labels: the sense of the seed features of each occurrence, else ⊥
  3. 2for t ← 1 to T do
  4. 3D ← the decision list trained on the occurrences with y_i ≠ ⊥
  5. 4y' ← for each occurrence: its seed label if it has one, else the sense of the first rule of D that matches it if the score of that rule is at least theta, else ⊥
  6. 5optional: for each occurrence without a seed label in a discourse where one sense has strictly the most labels in y', set y'_i to that sense
  7. 6if y' = y then return D, y
  8. 7y ← y'
  9. 8return D, y

The rules are sorted by decreasing score and, on equal scores, by the feature string, and the largest count goes to the first sense on ties. This makes the loop deterministic. An occurrence with two seed features of different senses gets no seed label in line L1. Seed labels never change: line L4 keeps them and line L5 skips them.

Example

The target is "plant", with A the living sense and B the factory sense. The seeds are +1:life→A+1{:}\text{life} \to A and −1:manufacturing→B-1{:}\text{manufacturing} \to B, with α=0.1\alpha = 0.1, θ=2\theta = 2, k=4k = 4 and one sense per discourse on. The nine occurrences, written for this page, are in six documents:

i occurrence document seed
1 plant life needs water and light d1 A
2 a green plant grows toward the light d1
3 the plant needs water d1
4 the manufacturing plant hired workers d2 B
5 workers at the plant went on strike d2
6 the car plant closed d3
7 water the plant every day d4
8 the plant workers were paid d5
9 the car plant employs workers d6

The rounds:

round rules that decide labels 1 to 9 after the round
seeds (L1) none A, ⊥, ⊥, B, ⊥, ⊥, ⊥, ⊥, ⊥
1 win:needs A, win:water A, win:workers B, each ln⁡11≈2.398\ln 11 \approx 2.398 A, A, A, B, B, ⊥, A, B, B
2 win:workers B ln⁡41≈3.714\ln 41 \approx 3.714, win:water A ln⁡31≈3.434\ln 31 \approx 3.434, win:needs A ln⁡21≈3.045\ln 21 \approx 3.045, -1:car B ln⁡11\ln 11 A, A, A, B, B, B, A, B, B
3 the same list as round 2, with -1:car B now ln⁡21\ln 21 no change, so line L6 returns

In round 1 only occurrences 1 and 4 are labeled, so every feature has one count and the score ln⁡(1.1/0.1)=ln⁡11\ln(1.1/0.1) = \ln 11. Occurrence 3 gets A from "needs" and "water", occurrence 7 from "water", and occurrences 5, 8 and 9 get B from "workers". Occurrence 2 has no feature in the list, but its document d1 has only A labels, so line L5 gives it A. Occurrence 6 has no match and is alone in d3, so it stays ⊥. In round 2 occurrence 9 is labeled B, so the rule -1:car B appears with score ln⁡11≥θ\ln 11 \ge \theta and labels occurrence 6. The feature -1:the occurs in two A and two B occurrences and gets the score ln⁡(2.1/2.1)=0\ln(2.1/2.1) = 0, last in the list. Without line L5, occurrence 2 stays ⊥, since none of its features occurs in another occurrence: the "light" of occurrence 1 is 5 tokens from "plant", outside the window.

Correctness

The sense labels are a heuristic and their quality is a measurement. What can be proved is what the loop computes. The decision list labels an occurrence with the sense of its matching rule of largest score, the smallest feature on ties, if that score reaches θ\theta. The seed labels never change, since line L4 keeps them and line L5 skips them. The loop stops after at most TT rounds, and if line L6 returns early, the labels are a fixed point of one round: training on them and labeling again gives the same labels. The loop is not guaranteed to reach a fixed point. An occurrence labeled in one round can lose its label in the next, when new labels lower the score of its rule below θ\theta, so the bound TT is needed. Yarowsky 1995 gives no convergence proof. Abney 2004 analyzes variants that optimize an objective. The full proof is below.

Proof: The Yarowsky loop keeps its seeds, stops, and stops early only at a fixed pointfull

We use the pseudocode of the page. There are nn examples with feature sets F1,…,FnF_1, \ldots, F_n, a list of senses σ1,…,σm\sigma_1, \ldots, \sigma_m in a fixed order, a smoothing constant α>0\alpha > 0, a threshold θ\theta and a bound T≥1T \ge 1 on the rounds. Let ziz_i be the seed label of example ii: the one sense of the seed collocations in FiF_i, or ⊥\bot if there is none or there are two different ones. A labeling is a vector y=(y1,…,yn)y = (y_1, \ldots, y_n) with each yiy_i a sense or ⊥\bot.

The algorithm makes no claim that the labels are the right senses. That part is a heuristic, measured on test data. What can be proved is what the loop computes.

Lemma 1 (the decision list). For a labeling yy, let cy(f,σ)c_y(f, \sigma) be the number of examples ii with f∈Fif \in F_i and yi=σy_i = \sigma. Line L3 gives one rule (f,sf,λf)(f, s_f, \lambda_f) for each feature ff with ∑σcy(f,σ)>0\sum_\sigma c_y(f, \sigma) > 0, where sfs_f is the first sense in the list with the largest count and

λf=ln⁡cy(f,sf)+α∑σ≠sfcy(f,σ)+α,\lambda_f = \ln \frac{c_y(f, s_f) + \alpha}{\sum_{\sigma \ne s_f} c_y(f, \sigma) + \alpha},

and it sorts the rules by decreasing λf\lambda_f, ties by the smaller feature string. Then the classification of line L4 for a set FF returns sf∗s_{f^*} if λf∗≥θ\lambda_{f^*} \ge \theta and ⊥\bot otherwise, where f∗f^* is the feature of FF with a rule that has the largest λ\lambda, the smallest string on ties; it returns ⊥\bot if no feature of FF has a rule.

Proof. Since α>0\alpha > 0, both parts of the ratio are positive and λf\lambda_f is a real number. The classification scans the sorted list and stops at the first rule whose feature is in FF. In the sorted order, rule ff comes before rule gg exactly when (−λf,f)<(−λg,g)(-\lambda_f, f) < (-\lambda_g, g), so the first rule with a feature in FF is the rule of the feature f∗f^* that is smallest in this order, which is the description above. The test of the threshold is made on that rule only. If no rule has a feature in FF, the scan ends without a match and returns ⊥\bot. □\square

Write U(y)U(y) for the labeling that one round makes from yy: lines L3 and L4, and line L5 when one sense per discourse is on. In line L4, example ii gets ziz_i if zi≠⊥z_i \ne \bot and the classification of Lemma 1 otherwise. In line L5, each example ii with zi=⊥z_i = \bot and a known discourse dd gets the sense that has strictly the most votes among the line L4 labels of discourse dd, if there is such a sense; otherwise it keeps its line L4 label.

Lemma 2 (the seeds stay). For every labeling yy and every ii with zi≠⊥z_i \ne \bot, U(y)i=ziU(y)_i = z_i.

Proof. Line L4 gives ziz_i to example ii. Line L5 changes only examples with zi=⊥z_i = \bot. □\square

Claim. The loop stops after at most TT rounds and returns a labeling yy with yi=ziy_i = z_i for every seeded example. If it returns at line L6 in round tt, then U(y)=yU(y) = y, the returned list DD is the decision list of yy, and classifying every unseeded example with DD by Lemma 1, followed by line L5, gives yy again.

Proof. Let y(0)y^{(0)} be the labeling of line L1 and y(t)=U(y(t−1))y^{(t)} = U(y^{(t-1)}). We show by induction on tt that, at the start of round t+1t + 1, the variable yy holds y(t)y^{(t)} and yi(t)=ziy^{(t)}_i = z_i for every seeded example.

Base. Line L1 sets y=y(0)y = y^{(0)}, and yi(0)=ziy^{(0)}_i = z_i for every ii by definition.

Step. In round t+1t + 1, lines L3 to L5 compute y′=U(y(t))=y(t+1)y' = U(y^{(t)}) = y^{(t+1)} from the current yy. Lemma 2 gives yi′=ziy'_i = z_i on the seeded examples. If line L7 runs, it sets y=y(t+1)y = y^{(t+1)}.

Termination. The rounds are the values t=1,…,Tt = 1, \ldots, T of line L2. Each round is finite: line L3 counts over nn finite sets and sorts a finite list, line L4 scans that list once per example, and line L5 counts votes once. So the loop stops at line L6 or after round TT, and line L8 returns. In both cases the returned labeling is some y(t)y^{(t)}, which keeps the seeds by the induction.

The early stop. Line L6 returns in round tt only when y′=yy' = y, that is U(y(t−1))=y(t−1)U(y^{(t-1)}) = y^{(t-1)}, and it returns y=y(t−1)y = y^{(t-1)} with the list DD that line L3 built from it in the same round. By the definition of UU and Lemma 1, applying DD to the unseeded examples and then line L5 gives y′y', which equals yy. □\square

What is not proved. The claim does not say that the loop reaches a fixed point within TT rounds, and Yarowsky 1995 gives no proof that it converges. The update UU is not monotone: an example labeled in one round can lose its label in the next. Take α=0.1\alpha = 0.1, θ=2\theta = 2, one sense per discourse off, and five examples: example 1 has {a,f}\{a, f\} and the seed a→σ1a \to \sigma_1; example 2 has {f}\{f\}; example 3 has {f,g}\{f, g\}; examples 4 and 5 have {g,b}\{g, b\} and the seed b→σ2b \to \sigma_2. In round 1, λf=ln⁡11≈2.40\lambda_f = \ln 11 \approx 2.40 and λg=ln⁡21≈3.04\lambda_g = \ln 21 \approx 3.04, so example 2 gets σ1\sigma_1 by ff and example 3 gets σ2\sigma_2 by gg. In round 2, ff occurs in two examples labeled σ1\sigma_1 and one labeled σ2\sigma_2, so λf=ln⁡(2.1/1.1)≈0.65<θ\lambda_f = \ln(2.1/1.1) \approx 0.65 < \theta, and example 2 goes back to ⊥\bot. So the labeled set need not grow, and the bound TT of line L2 is what makes the loop stop in all cases. Abney 2004 studies variants of the algorithm that do have a decreasing objective. ■\blacksquare

Complexity

The model is the word-RAM with hash maps keyed by feature strings.

  • Features. Building the feature sets costs O(nm)O(n m) once, for mm at most 2k+22k + 2 features per occurrence.
  • One round. Counting costs O(nm)O(n m), scoring O(F)O(F), and sorting the rules O(Flog⁡F)O(F \log F). Line L4 scans the list for each occurrence, which is O(nF)O(n F) in the worst case. With a map from each feature to its rank, line L4 takes the best rule of an occurrence in O(m)O(m), which makes the round O(nm+Flog⁡F)O(n m + F \log F). Line L5 counts the votes per document in O(n)O(n).
  • All rounds. TT times the cost of a round. The space is O(nm)O(n m) for the features and O(F)O(F) for the list and the counts.

In Yarowsky's experiments the rounds run over all the occurrences of the word in a corpus of 460 million words, so the cost of a round, and not the number of rounds, decides the run time.

Properties

  • Semi-supervised. The only labeled input is the seeds. Yarowsky called it unsupervised, since the seeds can come from a dictionary definition or a few hand-picked words.
  • Self-training. The classifier is trained on its own output. An occurrence that gets a label in round tt is training data in round t+1t + 1, and it also counts for the rules that labeled it.
  • Readable model. The decision list is a ranked list of collocations, so each decision has one rule as its reason.
  • One sense per collocation. A heuristic. It is what makes a single best rule a good decision, and the list keeps only that rule per occurrence.
  • One sense per discourse. A heuristic, with a measurement: Yarowsky 1995 reports 99.8% accuracy for it on 37,232 examples, with an applicability of 50.1%, which means that about half of the examples have another occurrence of the word in the same discourse.

Variants and improvements

  • Two senses with absolute scores. Yarowsky 1994 and 1995 use two senses and rank the rules by the absolute value of the log ratio. The rule above is the same for two senses and gives one rule per feature for more senses.
  • Seeds. Yarowsky 1995 compares seeds of two hand-picked words, the words of the dictionary definitions, and the top collocations from a few labeled examples.
  • Line L5 as a filter. The original uses one sense per discourse both to add labels and to remove labels that disagree with the majority of a discourse. Line L5 replaces a minority label with the majority sense, which does both.
  • A final pass. After the loop, the original applies the final decision list to new text, so the list is a classifier and not only a labeling of the training corpus.
  • Analyzed variants. Abney 2004 defines variants with a stated objective that each round does not increase. Like expectation maximization, they alternate between labeling the data and fitting the model to the labels.

When to use it

Use it when one ambiguous word has many unlabeled occurrences, long documents, and a few reliable collocations per sense. The decision list is cheap to apply and easy to inspect. When a sense-tagged corpus exists, a supervised classifier such as naive Bayes or a neural model is usually simpler. When the senses come from a dictionary and there is no corpus, use Lesk.

Pitfalls

  • A wrong label spreads. Line L4 trusts the rules learned from earlier labels, so one error can produce more errors. Replace occurrence 9 above by "a car plant needs workers". In round 1, win:needs A and win:workers B have the same score, and the tie rule picks win:needs, so occurrence 9 gets A. In round 2, -1:car becomes an A rule, and occurrence 6, "the car plant closed", also gets A. Use a high threshold in line L4 and check the rules near the top of the list.
  • No smoothing. With α=0\alpha = 0 in line L3, a feature seen with only one sense has an infinite score, and every such rule is at the top of the list, whatever the number of occurrences behind it. Yarowsky 1995 reports that smoothing is crucial. Keep α>0\alpha > 0.
  • Changing seed labels. If line L4 lets the decision list relabel the seeded occurrences, the loop can drift away from the seeds. Keep the seed label in line L4 and skip seeded occurrences in line L5.
  • Stop test on the size only. If line L6 stops when the number of labeled occurrences stops growing, it can stop while labels still change between senses. Compare the labels themselves.
  • No bound on the rounds. Without the bound TT in line L2, nothing guarantees that the loop stops, since the update is not monotone.
  • Discourse boundaries. Line L5 needs the document of each occurrence. If the whole corpus is one discourse, line L5 gives every unseeded occurrence the majority sense.

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.

yarowsky_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/yarowsky-algorithm/. The authors are listed in prov/89R7KS.jsonl.
"""The Yarowsky algorithm: grow a decision list for word senses from seed
collocations, with the one sense per discourse constraint as an option.

Features of an occurrence are the word just before the target ("-1:w"), the
word just after it ("+1:w") and each non-stop word within k tokens
("win:w"). The score of a rule f -> s is the smoothed log ratio
log((c(f, s) + alpha) / (c(f, other senses) + alpha)), with natural logs.
"""

from collections import Counter, defaultdict
from dataclasses import dataclass
from math import log

STOP_WORDS = frozenset("a an the of in on at to for and or is are was were be it its this that with by as".split())


@dataclass(frozen=True)
class Occurrence:
    """One occurrence of the target word: the tokens, its position, and its discourse (None if unknown)."""

    tokens: tuple[str, ...]
    position: int
    discourse: str | None = None


@dataclass(frozen=True)
class Rule:
    score: float
    feature: str
    sense: str


@dataclass(frozen=True)
class Result:
    rules: list[Rule]
    labels: list[str | None]
    iterations: int
    converged: bool


def features(occ: Occurrence, k: int = 4, stop_words: frozenset[str] = STOP_WORDS) -> frozenset[str]:
    """The collocation features of one occurrence."""
    t, i = occ.tokens, occ.position
    f = set()
    if i > 0:
        f.add("-1:" + t[i - 1])
    if i + 1 < len(t):
        f.add("+1:" + t[i + 1])
    for j in range(max(0, i - k), min(len(t), i + k + 1)):
        if j != i and t[j] not in stop_words:
            f.add("win:" + t[j])
    return frozenset(f)


def train_decision_list(
    feats: list[frozenset[str]], labels: list[str | None], senses: list[str], alpha: float
) -> list[Rule]:
    """One rule per feature seen in a labeled example, sorted by score, then by feature."""
    count: dict[str, Counter[str]] = defaultdict(Counter)
    for f, y in zip(feats, labels):
        if y is not None:
            for x in f:
                count[x][y] += 1
    rules = []
    for x, c in count.items():
        s = max(senses, key=lambda z: (c[z], -senses.index(z)))
        other = sum(c.values()) - c[s]
        rules.append(Rule(log((c[s] + alpha) / (other + alpha)), x, s))
    rules.sort(key=lambda r: (-r.score, r.feature))
    return rules


def classify(f: frozenset[str], rules: list[Rule], threshold: float) -> str | None:
    """The sense of the first rule that matches f, if its score reaches the threshold."""
    for r in rules:
        if r.feature in f:
            return r.sense if r.score >= threshold else None
    return None


def seed_labels(feats: list[frozenset[str]], seeds: dict[str, str]) -> list[str | None]:
    """The sense of the seed collocations of each example, or None for none or a conflict."""
    out: list[str | None] = []
    for f in feats:
        found = {seeds[x] for x in f if x in seeds}
        out.append(found.pop() if len(found) == 1 else None)
    return out


def yarowsky(
    occurrences: list[Occurrence],
    seeds: dict[str, str],
    senses: list[str],
    k: int = 4,
    alpha: float = 0.1,
    threshold: float = 2.0,
    max_iter: int = 50,
    one_sense_per_discourse: bool = True,
) -> Result:
    """Bootstrap a decision list from the seed collocations.

    Precondition: alpha > 0, and every seed sense is in senses (in order of
    preference for ties). Examples labeled by a seed keep that label. The
    loop stops when the labels repeat or after max_iter rounds. Cost per
    round, for F distinct features, n examples and at most m features per
    example: O(n m) to count, O(F log F) to sort, and O(n F) to scan the
    list once per example.
    """
    if alpha <= 0:
        raise ValueError("alpha must be positive")
    feats = [features(o, k) for o in occurrences]
    fixed = seed_labels(feats, seeds)
    labels = list(fixed)  # @line L1
    rules: list[Rule] = []
    for t in range(1, max_iter + 1):  # @line L2
        rules = train_decision_list(feats, labels, senses, alpha)  # @line L3
        new = [fixed[i] or classify(feats[i], rules, threshold) for i in range(len(feats))]  # @line L4
        if one_sense_per_discourse:  # @line L5
            votes: dict[str, Counter[str]] = defaultdict(Counter)
            for o, y in zip(occurrences, new):
                if o.discourse is not None and y is not None:
                    votes[o.discourse][y] += 1
            for i, o in enumerate(occurrences):
                c = votes.get(o.discourse) if o.discourse is not None else None
                if c and fixed[i] is None:
                    top = c.most_common(2)
                    if len(top) == 1 or top[0][1] > top[1][1]:
                        new[i] = top[0][0]
        if new == labels:  # @line L6
            return Result(rules, labels, t, True)
        labels = new  # @line L7
    return Result(rules, labels, max_iter, False)  # @line L8
test_yarowsky_algorithm.py 176 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/yarowsky-algorithm/. The authors are listed in prov/89R7KS.jsonl.

import math
import random

from yarowsky_algorithm import (
    Occurrence,
    Rule,
    classify,
    features,
    seed_labels,
    train_decision_list,
    yarowsky,
)

DATA = [
    ("plant life needs water and light", "d1"),
    ("a green plant grows toward the light", "d1"),
    ("the plant needs water", "d1"),
    ("the manufacturing plant hired workers", "d2"),
    ("workers at the plant went on strike", "d2"),
    ("the car plant closed", "d3"),
    ("water the plant every day", "d4"),
    ("the plant workers were paid", "d5"),
    ("the car plant employs workers", "d6"),
]
SEEDS = {"+1:life": "A", "-1:manufacturing": "B"}


def occurrences(data: list[tuple[str, str]]) -> list[Occurrence]:
    out = []
    for s, d in data:
        t = tuple(s.split())
        out.append(Occurrence(t, t.index("plant"), d))
    return out


def test_worked_example() -> None:
    occ = occurrences(DATA)
    assert sorted(features(occ[2])) == ["+1:needs", "-1:the", "win:needs", "win:water"]
    r1 = yarowsky(occ, SEEDS, ["A", "B"], max_iter=1)
    assert r1.labels == ["A", "A", "A", "B", "B", None, "A", "B", "B"]
    assert all(abs(r.score - math.log(11)) < 1e-12 for r in r1.rules)
    result = yarowsky(occ, SEEDS, ["A", "B"])
    assert result.converged and result.iterations == 3
    assert result.labels == ["A", "A", "A", "B", "B", "B", "A", "B", "B"]
    top = [(r.feature, r.sense, round(r.score, 3)) for r in result.rules[:5]]
    assert top == [
        ("win:workers", "B", 3.714), ("win:water", "A", 3.434), ("-1:car", "B", 3.045),
        ("win:car", "B", 3.045), ("win:needs", "A", 3.045),
    ]
    assert result.rules[-1] == Rule(0.0, "-1:the", "A")
    plain = yarowsky(occ, SEEDS, ["A", "B"], one_sense_per_discourse=False)
    assert plain.converged and plain.labels == ["A", None, "A", "B", "B", "B", "A", "B", "B"]


def test_error_propagation() -> None:
    data = DATA[:-1] + [("a car plant needs workers", "d6")]
    result = yarowsky(occurrences(data), SEEDS, ["A", "B"])
    assert result.labels[5] == "A" and result.labels[8] == "A"


def test_label_can_be_lost() -> None:
    occ = [
        Occurrence(("a", "x", "f"), 1),
        Occurrence(("x", "f"), 0),
        Occurrence(("g", "x", "f"), 1),
        Occurrence(("g", "x", "b"), 1),
        Occurrence(("g", "x", "b"), 1),
    ]
    seeds = {"-1:a": "A", "+1:b": "B"}
    run = [yarowsky(occ, seeds, ["A", "B"], k=0, max_iter=t, one_sense_per_discourse=False) for t in (1, 2, 3)]
    assert run[0].labels == ["A", "A", "B", "B", "B"]
    assert run[1].labels == ["A", None, "B", "B", "B"]
    assert run[2].converged and run[2].labels == run[1].labels


def test_edges() -> None:
    occ = occurrences(DATA)
    none = yarowsky(occ, {}, ["A", "B"])
    assert none.converged and none.iterations == 1 and none.labels == [None] * 9 and none.rules == []
    both = seed_labels([frozenset({"x", "y"}), frozenset({"x"})], {"x": "A", "y": "B"})
    assert both == [None, "A"]
    assert features(Occurrence(("plant",), 0)) == frozenset()
    assert classify(frozenset({"f"}), [Rule(1.0, "f", "A")], 2.0) is None
    assert classify(frozenset({"g"}), [Rule(1.0, "f", "A")], 0.0) is None
    capped = yarowsky(occ, SEEDS, ["A", "B"], max_iter=2)
    assert not capped.converged and capped.iterations == 2
    try:
        yarowsky(occ, SEEDS, ["A", "B"], alpha=0.0)
    except ValueError:
        pass
    else:
        raise AssertionError("alpha = 0 must fail")


def reference(occ, seeds, senses, k, alpha, threshold, max_iter, ospd):
    """A direct second version: counts by scanning, the best rule by max."""
    feats = [features(o, k) for o in occ]
    fixed = []
    for f in feats:
        s = sorted({seeds[x] for x in f if x in seeds})
        fixed.append(s[0] if len(s) == 1 else None)
    y = list(fixed)
    for t in range(1, max_iter + 1):
        allf = sorted({x for f, lab in zip(feats, y) if lab is not None for x in f})
        table = {}
        for x in allf:
            c = {s: sum(1 for f, lab in zip(feats, y) if lab == s and x in f) for s in senses}
            best = senses[0]
            for s in senses:
                if c[s] > c[best]:
                    best = s
            other = sum(c.values()) - c[best]
            table[x] = (math.log((c[best] + alpha) / (other + alpha)), best)
        new = []
        for i, f in enumerate(feats):
            if fixed[i] is not None:
                new.append(fixed[i])
                continue
            match = [x for x in f if x in table]
            if not match:
                new.append(None)
                continue
            x = min(match, key=lambda z: (-table[z][0], z))
            new.append(table[x][1] if table[x][0] >= threshold else None)
        if ospd:
            out = list(new)
            for i, o in enumerate(occ):
                if fixed[i] is not None or o.discourse is None:
                    continue
                c = {}
                for j, p in enumerate(occ):
                    if p.discourse == o.discourse and new[j] is not None:
                        c[new[j]] = c.get(new[j], 0) + 1
                if c:
                    m = max(c.values())
                    winners = [s for s in c if c[s] == m]
                    if len(winners) == 1:
                        out[i] = winners[0]
            new = out
        if new == y:
            return y, t, True
        y = new
    return y, max_iter, False


def test_against_reference() -> None:
    rng = random.Random(5)
    words = ["w%d" % i for i in range(8)]
    for _ in range(500):
        senses = ["A", "B", "C"][: rng.randrange(2, 4)]
        occ = []
        for _ in range(rng.randrange(1, 9)):
            n = rng.randrange(1, 7)
            t = tuple(rng.choice(words) for _ in range(n))
            occ.append(Occurrence(t, rng.randrange(n), rng.choice(["d1", "d2", "d3", None])))
        seeds = {}
        for _ in range(rng.randrange(0, 4)):
            seeds[rng.choice(["-1:", "+1:", "win:"]) + rng.choice(words)] = rng.choice(senses)
        k = rng.randrange(1, 4)
        alpha = rng.choice([0.1, 0.5, 1.0])
        threshold = rng.choice([0.0, 0.5, 1.5])
        ospd = rng.random() < 0.5
        got = yarowsky(occ, seeds, senses, k=k, alpha=alpha, threshold=threshold, max_iter=6, one_sense_per_discourse=ospd)
        want = reference(occ, seeds, senses, k, alpha, threshold, 6, ospd)
        assert (got.labels, got.iterations, got.converged) == want
        if got.converged:
            again = yarowsky(occ, seeds, senses, k=k, alpha=alpha, threshold=threshold, max_iter=got.iterations + 1,
                             one_sense_per_discourse=ospd)
            assert again.labels == got.labels
        fixed = seed_labels([features(o, k) for o in occ], seeds)
        assert all(f is None or f == y for f, y in zip(fixed, got.labels))
        rules = train_decision_list([features(o, k) for o in occ], got.labels, senses, alpha)
        assert all(a.score >= b.score for a, b in zip(rules, rules[1:]))

History

Gale, Church and Yarowsky 1992 measured that an ambiguous word tends to keep one sense in one discourse. Yarowsky 1994 used decision lists ranked by log likelihood ratios for accent restoration, a task with the same structure as sense disambiguation. Yarowsky 1995 joined the two into the bootstrapping algorithm, tested it on 12 words over a corpus of 460 million words, and reported 96.5% average accuracy for the best setting with one sense per discourse, against 96.1% for a supervised decision list and 90.6% for seeds of two words without it. These are measurements on his test data. Abney 2004 gave the first analysis of what the algorithm optimizes.

References

  1. Yarowsky 1995, the two constraints with the measurement of one sense per discourse, Steps 1 to 5 of the algorithm with the plant example, and the table of results for 12 words
  2. Gale, Church and Yarowsky 1992, the observation that an ambiguous word keeps one sense within a discourse
  3. Yarowsky 1994, the decision list ranked by the log likelihood ratio of each collocation
  4. Abney 2004, the analysis of variants of the algorithm as the optimization of an objective
  5. Roberto Navigli, Word sense disambiguation, a survey, ACM Computing Surveys 41(2), 2009, article 10, the section on semi-supervised disambiguation and bootstrapping

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.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example