Algorithm Search⌘K

Algorithmcore

Structured perceptron

Also called Collins perceptron.

Decode each training sentence by Viterbi and add the features of the gold tags minus those of the predicted tags; averaged in practice.

Time
Θ(t n k^2) worst
Space
O(n + d) extra
Where
d = the number of features; k = the number of tags; n = the total number of training tokens; t = the number of epochs
Properties
deterministicnot exactonlineiterative
Origin
Michael Collins, 2002

The structured perceptron learns the weights of a linear scoring function over whole tag sequences. For each training sentence it finds the best tag sequence under the current weights with the Viterbi algorithm. If that sequence is wrong, it adds the feature counts of the gold sequence to the weights and subtracts those of the predicted sequence. It is the perceptron with the argmax over kk classes replaced by an argmax over knk^n tag sequences. Unlike the HMM tagger it does not estimate probabilities, so features can overlap freely, and unlike the conditional random field it needs no forward-backward pass, only decoding.

In plain words

The tagger gives points to each small fact about a tagged sentence, such as "the word dog has tag N" or "tag N follows tag D". The score of a tagging is the sum of its points. To learn the points, go through the training sentences one by one. Find the tagging with the most points. If it is the right one, do nothing. If it is wrong, give one more point to each fact of the right tagging and take one point away from each fact of the wrong one. Facts that both taggings share cancel out. Repeat over the data a few times. In practice, use the average of the points over all steps, which makes the tagger much more stable on new text.

The problem

Input: training pairs (xi,yi)(x_i, y_i), i=1,…,Ni = 1, \ldots, N, of sentences and gold tag sequences over kk tags; a feature map Φ(x,y)∈Rd\Phi(x, y) \in \mathbb{R}^d; a number of epochs TT. Output: a weight vector ww such that the tagger F(x)=arg⁡max⁡y∈GEN(x)w⋅Φ(x,y)F(x) = \arg\max_{y \in \mathrm{GEN}(x)} w \cdot \Phi(x, y) makes few errors. GEN(x)\mathrm{GEN}(x) is the set of all knk^n tag sequences for a sentence of nn words.

To decode by dynamic programming, Φ\Phi must be a sum of local feature vectors, each depending on the words, the position jj and a few neighbouring tags. The code uses first-order features: one count for each transition (yj−1,yj)(y_{j-1}, y_j), with y0=⟨s⟩y_0 = \langle s \rangle and yn+1=⟨/s⟩y_{n+1} = \langle /s \rangle, and one for each pair (tag, word). Collins uses trigram tag features and the word features of Ratnaparkhi's maximum entropy tagger (suffixes, prefixes, capitalization, nearby words), which works the same way with a decoder over pairs of tags.

The algorithm

  1. PERCEPTRON-TRAIN((x_1, y_1) .. (x_N, y_N), T)
  2. 1w ← 0; u ← 0; c ← 0 ▷ u and c keep the average lazily
  3. 2for epoch ← 1 to T do
  4. 3for i ← 1 to N do
  5. 4z ← VITERBI(x_i, w) ▷ argmax over z of w · Φ(x_i, z)
  6. 5if z ≠ y_i then
  7. 6d ← Φ(x_i, y_i) - Φ(x_i, z)
  8. 7w ← w + d; u ← u + c d
  9. 8c ← c + 1
  10. 9return w and the averaged weights w - u / c

The averaged weights are the mean of the weights after each of the TNT N examples (Collins 2002, Section 2.5). Summing ww after every example costs O(d)O(d) per example. The code uses the identity 1J∑j=1Jwj=wJ−1J∑i(i−1)di\frac{1}{J} \sum_{j=1}^{J} w_j = w_J - \frac{1}{J} \sum_{i} (i - 1) d_i, so each update costs only the size of dd. The decoder breaks ties by taking the first tag in a fixed order, which makes the whole run deterministic.

Example

Use the tags D, J, N, V in that order and three training sentences: "the/D runs/N", "dogs/N run/V" and "the/D dog/N runs/V". All weights start at 0.

  1. "the runs": all taggings score 0, and the tie rule picks D D. The update adds 1 to (D,N)(D, N), (N, runs) and (N,⟨/s⟩)(N, \langle /s \rangle), and subtracts 1 from (D,D)(D, D), (D, runs) and (D,⟨/s⟩)(D, \langle /s \rangle). The shared features (⟨s⟩,D)(\langle s \rangle, D) and (D, the) cancel.
  2. "dogs run": the decoder picks D N with score 2, using the weight of (D,N)(D, N) and (N,⟨/s⟩)(N, \langle /s \rangle) from step 1. The gold is N V, so a second update follows. It moves (D,N)(D, N) back to 0 and (N,⟨/s⟩)(N, \langle /s \rangle) back to 0.
  3. "the dog runs": the decoder picks N V N with score 3. A third update adds, among others, 1 to (V, runs) and subtracts 1 from (N, runs).

In epoch 2, "the runs" comes out as D V, since (V, runs) is now 1 and (N, runs) is 0, and the fourth update fixes this. The other two sentences are right. Epoch 3 has no mistakes, so the mistakes per epoch are 3, 1, 0. The averaged weights are means over 9 steps, for example 14/914/9 for the transition (D,N)(D, N) and 8/98/9 for (N, runs); they also tag all three sentences correctly. The test file checks a run like this one on a larger corpus.

Correctness

The proof in proofs/correctness.md has three parts. First, the score is a sum of local terms, so Viterbi returns a sequence of the highest score (a theorem; the test file compares it with a search over all knk^n sequences). Second, Collins's Theorem 1: if some unit vector UU separates the data with margin δ\delta, so that U⋅Φ(xi,yi)−U⋅Φ(xi,z)≥δU \cdot \Phi(x_i, y_i) - U \cdot \Phi(x_i, z) \ge \delta for all wrong zz, and ∥Φ(xi,yi)−Φ(xi,z)∥≤R\lVert \Phi(x_i, y_i) - \Phi(x_i, z) \rVert \le R, then the algorithm makes at most R2/δ2R^2 / \delta^2 mistakes in total, however many epochs it runs. The proof is the one of Novikoff for the binary perceptron: each mistake raises U⋅wU \cdot w by at least δ\delta, while ∥w∥2\lVert w \rVert^2 grows by at most R2R^2, since the predicted zz scored at least as high as yiy_i. Note that the bound does not depend on the number of sequences in GEN(x)\mathrm{GEN}(x), which grows as knk^n. Third, the lazy average is equal to the direct average, which the test file checks in exact rational arithmetic.

Proof: Viterbi decoding is exact, the perceptron makes a bounded number of mistakes on separable data, and lazy averaging is exactfull

Setting. A training set has pairs (xi,yi)(x_i, y_i) for i=1,…,Ni = 1, \ldots, N, where xix_i is a sentence and yiy_i its gold tags. GEN(x)\mathrm{GEN}(x) is the set of all tag sequences of the length of xx over the kk tags. Φ(x,y)\Phi(x, y) is the global feature vector: the counts of the transition features (yj−1,yj)(y_{j-1}, y_j), with y0=⟨s⟩y_0 = \langle s \rangle and yn+1=⟨/s⟩y_{n+1} = \langle /s \rangle, and of the emission features (yj,xj)(y_j, x_j). The score of yy is w⋅Φ(x,y)w \cdot \Phi(x, y).

Claim 1: Viterbi returns a highest-scoring tag sequence

The score splits into local terms: w⋅Φ(x,y)=∑j=1n(wT(yj−1,yj)+wE(yj,xj))+wT(yn,⟨/s⟩)w \cdot \Phi(x, y) = \sum_{j=1}^{n} \bigl(w_{T}(y_{j-1}, y_j) + w_{E}(y_j, x_j)\bigr) + w_{T}(y_n, \langle /s \rangle). Let δj(t)\delta_j(t) be the largest value of the first jj local terms over the prefixes y1…yjy_1 \ldots y_j with yj=ty_j = t. Then δ1(t)=wT(⟨s⟩,t)+wE(t,x1)\delta_1(t) = w_T(\langle s \rangle, t) + w_E(t, x_1) and δj(t)=max⁡g(δj−1(g)+wT(g,t))+wE(t,xj)\delta_j(t) = \max_g (\delta_{j-1}(g) + w_T(g, t)) + w_E(t, x_j), because the terms of a prefix ending in gg at j−1j - 1 do not depend on tt, and any prefix ending in gg can be replaced by a best one without changing the new terms. The best total is max⁡t(δn(t)+wT(t,⟨/s⟩))\max_t (\delta_n(t) + w_T(t, \langle /s \rangle)), and following the stored maximizers back gives a sequence with this score. This is the same argument as for the Viterbi algorithm, with sums of weights in place of log probabilities. The test file checks the score against all knk^n sequences for n≤6n \le 6 and k≤3k \le 3. □\square

Claim 2: the mistake bound (Collins 2002, Theorem 1)

Suppose there is a vector UU with ∥U∥=1\lVert U \rVert = 1 and a δ>0\delta > 0 such that U⋅Φ(xi,yi)−U⋅Φ(xi,z)≥δU \cdot \Phi(x_i, y_i) - U \cdot \Phi(x_i, z) \ge \delta for all ii and all z∈GEN(xi)z \in \mathrm{GEN}(x_i) with z≠yiz \ne y_i. Let RR be a number with ∥Φ(xi,yi)−Φ(xi,z)∥≤R\lVert \Phi(x_i, y_i) - \Phi(x_i, z) \rVert \le R for all such ii and zz. Then the perceptron, run for any number of epochs, makes at most R2/δ2R^2 / \delta^2 mistakes.

Proof. Let wkw^k be the weights before the kk-th mistake, with w1=0w^1 = 0. At the kk-th mistake, on example ii, the decoder returns z≠yiz \ne y_i with wk⋅Φ(xi,z)≥wk⋅Φ(xi,yi)w^k \cdot \Phi(x_i, z) \ge w^k \cdot \Phi(x_i, y_i), since zz has the highest score under wkw^k (Claim 1). The update is wk+1=wk+dw^{k+1} = w^k + d with d=Φ(xi,yi)−Φ(xi,z)d = \Phi(x_i, y_i) - \Phi(x_i, z).

Lower bound. U⋅wk+1=U⋅wk+U⋅d≥U⋅wk+δU \cdot w^{k+1} = U \cdot w^k + U \cdot d \ge U \cdot w^k + \delta, so by induction U⋅wk+1≥kδU \cdot w^{k+1} \ge k \delta. By the Cauchy-Schwarz inequality, ∥wk+1∥≥U⋅wk+1≥kδ\lVert w^{k+1} \rVert \ge U \cdot w^{k+1} \ge k \delta.

Upper bound. ∥wk+1∥2=∥wk∥2+2wk⋅d+∥d∥2≤∥wk∥2+R2\lVert w^{k+1} \rVert^2 = \lVert w^k \rVert^2 + 2 w^k \cdot d + \lVert d \rVert^2 \le \lVert w^k \rVert^2 + R^2, because wk⋅d≤0w^k \cdot d \le 0 by the choice of zz. By induction ∥wk+1∥2≤kR2\lVert w^{k+1} \rVert^2 \le k R^2.

Together, k2δ2≤kR2k^2 \delta^2 \le k R^2, so k≤R2/δ2k \le R^2 / \delta^2. □\square

Consequence. When the bound holds, there is an epoch with no mistakes after at most R2/δ2+1R^2/\delta^2 + 1 epochs, and from then on the weights do not change, so every later epoch is also clean and the final ww tags every training sentence correctly. The test file builds separable data from a random integer vector uu, keeps only sentences whose best tagging under uu is unique, and checks the bound in the integer form mistakes⋅m2≤R2∥u∥2\text{mistakes} \cdot m^2 \le R^2 \lVert u \rVert^2, where mm is the smallest score gap under uu, so that δ=m/∥u∥\delta = m / \lVert u \rVert. It also checks that the last epoch is clean.

Collins also proves a bound for data that is not separable (Theorem 2) and a bound on the generalization error of the voted perceptron (Theorem 3, from Freund and Schapire 1999). These are not checked by the test file.

Claim 3: lazy averaging is exact

Number the examples processed in all epochs 1,…,J1, \ldots, J, with J=TNJ = T N. Let djd_j be the update at step jj (dj=0d_j = 0 if there was no mistake), so the weights after step jj are wj=∑i≤jdiw_j = \sum_{i \le j} d_i. The averaged weights of Collins (2002, Section 2.5) are

wˉ=1J∑j=1Jwj=1J∑i=1J(J−i+1)di=∑i=1Jdi−1J∑i=1J(i−1)di=wJ−uJ,\bar w = \frac{1}{J} \sum_{j=1}^{J} w_j = \frac{1}{J} \sum_{i=1}^{J} (J - i + 1) d_i = \sum_{i=1}^{J} d_i - \frac{1}{J} \sum_{i=1}^{J} (i - 1) d_i = w_J - \frac{u}{J},

where u=∑i(i−1)diu = \sum_i (i - 1) d_i. The code keeps c=i−1c = i - 1, the number of examples seen before step ii, and adds c dic \, d_i to uu at line L7; at the end c=Jc = J and line L9 returns w−u/cw - u / c. This needs work only for the features in each update, while the direct sum needs work for every feature after every example. The test file checks the two in exact rational arithmetic. □\square

Complexity

Each training step decodes one sentence. With first-order features, Viterbi takes Θ(nik2)\Theta(n_i k^2) time for a sentence of nin_i words, so one epoch over nn tokens takes Θ(nk2)\Theta(n k^2) time and TT epochs take Θ(Tnk2)\Theta(T n k^2), plus the cost of computing the features. An update touches at most O(ni)O(n_i) features. With second-order features, as in Collins's experiments, decoding takes Θ(nik3)\Theta(n_i k^3). Space is the dd weights and the second vector uu for the average, plus O(nik)O(n_i k) for the decoder. On separable data, Theorem 1 also bounds the number of updates by R2/δ2R^2/\delta^2, but the bound is often very loose: in the test file the runs make 0 to 18 mistakes against bounds between about 1300 and 20000.

Properties

  • Online and mistake-driven: it looks at one example at a time and changes ww only on a mistake.
  • No learning rate: scaling all weights does not change the argmax, so a step size other than 1 gives the same predictions when ww starts at 0.
  • Exact decoding is required by the proof: with an approximate decoder such as beam search, the predicted zz may score lower than yiy_i, and the upper bound step fails. Collins and Roark (2004) add an early update for this case.
  • Not probabilistic: the scores are not normalized, so the model gives no marginal probabilities or confidence.
  • Measured (Collins 2002, Section 4): on Penn Treebank part-of-speech tagging the averaged perceptron had an error rate of 2.89% against 3.28% for a maximum entropy tagger with the same features, and on NP chunking an F-measure of 93.63 against 93.29.

Variants and improvements

  • Averaged perceptron. The average of all weight vectors, as here. Collins motivates it as an approximation to the voted perceptron of Freund and Schapire (1999), and it gave clear gains over the last weight vector in his experiments.
  • Voted perceptron. Each intermediate weight vector votes with a weight equal to the number of examples it survived; Collins's Theorem 3 bounds its expected error on new data.
  • Inseparable data. Collins's Theorem 2 bounds the number of mistakes in terms of how far the data is from separable.
  • Margin methods. MIRA and the structured support vector machine also learn from decoded outputs, but choose the step to reach a margin; structured prediction covers them.
  • Other structures. The same algorithm works for any output with an exact argmax: parse trees with a CKY decoder, segmentations with a semi-Markov decoder, dependency parsing and so on.
  • Probabilistic training. Replacing the perceptron update by the gradient of the log likelihood gives the conditional random field; the perceptron update is a subgradient step on a loss that uses the max where the CRF uses log-sum-exp.

When to use it

Use the structured perceptron for a fast and simple discriminative tagger or chunker with rich, overlapping features, when you only need the best output and not probabilities. It is easy to implement on top of any exact decoder, needs no tuning of a learning rate, and trains in a few epochs. Use a CRF when you need calibrated probabilities or marginals, and a neural model such as the BiLSTM-CRF when you want learned features.

Pitfalls

  • Use the averaged weights for testing. The last weight vector depends strongly on the order of the last examples.
  • Shuffle the data between epochs, or at least do not sort it by type; the result depends on the order.
  • Ties in the decoder: with all-zero weights every sequence ties. A fixed tie rule keeps runs reproducible; the update is still correct whatever the tie rule is.
  • The bound is for exact decoding. With a beam, a wrong output may score lower than the gold output, and the update can make things worse.
  • The gold and the predicted sequences usually share most of their features, and these cancel in Φ(x,y)−Φ(x,z)\Phi(x, y) - \Phi(x, z). Compute the update as a sparse difference, not with dense vectors.
  • The convergence result says nothing about new text. Run a fixed number of epochs and choose it on held-out data.

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.

structured_perceptron.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/structured-perceptron/. The authors are listed in prov/KYD1XY.jsonl.

"""The structured perceptron of Collins (2002) for tagging, with averaging.

The feature vector Phi(x, y) of a sentence x with tags y counts first-order
features: ("T", y[i-1], y[i]) for each transition, with "<s>" before the
first tag and "</s>" after the last one, and ("E", y[i], x[i]) for each word.
The score of y is the dot product w . Phi(x, y). Decoding is Viterbi over
the tags.

Weights are kept in dicts; a missing key means 0. Updates add +1 or -1 to
weights, so the weights stay integers, and the averaged weights are exact
Fractions.
"""

from fractions import Fraction
from itertools import product
from typing import Dict, Hashable, List, Sequence, Tuple

BOS, EOS = "<s>", "</s>"

Weights = Dict[Hashable, int]


def phi(words: Sequence[str], tags: Sequence[str]) -> Dict[Tuple[str, str, str], int]:
    """The global feature vector: counts of transition and emission features."""
    f: Dict[Tuple[str, str, str], int] = {}
    prev = BOS
    for x, y in zip(words, tags):
        for key in (("T", prev, y), ("E", y, x)):
            f[key] = f.get(key, 0) + 1
        prev = y
    key = ("T", prev, EOS)
    f[key] = f.get(key, 0) + 1
    return f


def score(w, words: Sequence[str], tags: Sequence[str]):
    return sum(w.get(k, 0) * v for k, v in phi(words, tags).items())


def viterbi(words: Sequence[str], tagset: Sequence[str], w):
    """Return (tags, score) of a highest-scoring tag sequence. Ties go to the first tag in tagset order."""
    n = len(words)
    if n == 0:
        raise ValueError("empty sentence")
    delta = {t: w.get(("T", BOS, t), 0) + w.get(("E", t, words[0]), 0) for t in tagset}
    back: List[Dict[str, str]] = []
    for i in range(1, n):
        new, bp = {}, {}
        for t in tagset:
            e = w.get(("E", t, words[i]), 0)
            best_g = None
            for g in tagset:
                v = delta[g] + w.get(("T", g, t), 0)
                if best_g is None or v > new[t]:
                    new[t], best_g = v, g
            new[t] += e
            bp[t] = best_g
        delta = new
        back.append(bp)
    last = None
    for t in tagset:
        v = delta[t] + w.get(("T", t, EOS), 0)
        if last is None or v > best:
            last, best = t, v
    out = [last]
    for bp in reversed(back):
        out.append(bp[out[-1]])
    out.reverse()
    return out, best


def brute_force(words: Sequence[str], tagset: Sequence[str], w):
    """The best score over all k^n tag sequences (for tests)."""
    return max(score(w, words, ys) for ys in product(tagset, repeat=len(words)))


def train(data, tagset: Sequence[str], epochs: int):
    """Run the perceptron. Return (w, averaged w, number of mistakes per epoch).

    The average is over the weights after each of the epochs * len(data)
    examples, as in Collins (2002), Section 2.5. It is kept lazily: u adds
    c * d for each update d made when c examples were seen before, and the
    average is w - u / c at the end.
    """
    w: Weights = {}  # @line L1
    u: Weights = {}
    c = 0
    mistakes = []
    for _ in range(epochs):  # @line L2
        m = 0
        for words, gold in data:  # @line L3
            z, _ = viterbi(words, tagset, w)  # @line L4
            if list(z) != list(gold):  # @line L5
                m += 1
                d = dict(phi(words, gold))  # @line L6
                for k, v in phi(words, z).items():
                    d[k] = d.get(k, 0) - v
                for k, v in d.items():  # @line L7
                    if v:
                        w[k] = w.get(k, 0) + v
                        u[k] = u.get(k, 0) + c * v
            c += 1  # @line L8
        mistakes.append(m)
    avg = {k: Fraction(w.get(k, 0)) - Fraction(u.get(k, 0), c) for k in set(w) | set(u)} if c else {}
    return w, avg, mistakes  # @line L9


def train_naive_average(data, tagset: Sequence[str], epochs: int):
    """The same run, with the average computed by summing the weights after every example (for tests)."""
    w: Weights = {}
    total: Dict[Hashable, int] = {}
    c = 0
    for _ in range(epochs):
        for words, gold in data:
            z, _ = viterbi(words, tagset, w)
            if list(z) != list(gold):
                for k, v in phi(words, gold).items():
                    w[k] = w.get(k, 0) + v
                for k, v in phi(words, z).items():
                    w[k] = w.get(k, 0) - v
            c += 1
            for k, v in w.items():
                total[k] = total.get(k, 0) + v
    return {k: Fraction(v, c) for k, v in total.items()}
test_structured_perceptron.py 131 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/structured-perceptron/. The authors are listed in prov/KYD1XY.jsonl.

import random
from fractions import Fraction
from itertools import product

import pytest

from structured_perceptron import BOS, EOS, brute_force, phi, score, train, train_naive_average, viterbi

TAGS = ["A", "B", "C"]
VOCAB = ["p", "q", "r", "s"]

CORPUS = [
    ("the dog runs".split(), ["D", "N", "V"]),
    ("the old dog runs".split(), ["D", "J", "N", "V"]),
    ("dogs run".split(), ["N", "V"]),
    ("the runs".split(), ["D", "N"]),
    ("old dogs walk".split(), ["J", "N", "V"]),
]


def all_features(tags, vocab):
    feats = [("T", a, b) for a in [BOS] + tags for b in tags + [EOS]]
    return feats + [("E", t, x) for t in tags for x in vocab]


def random_weights(rng, tags, vocab, lo=-5, hi=5):
    return {f: rng.randint(lo, hi) for f in all_features(tags, vocab)}


def sq_norm(d):
    return sum(v * v for v in d.values())


def diff(a, b):
    d = dict(a)
    for k, v in b.items():
        d[k] = d.get(k, 0) - v
    return {k: v for k, v in d.items() if v}


def test_phi_counts():
    f = phi(["p", "q", "p"], ["A", "A", "B"])
    assert f == {("T", BOS, "A"): 1, ("E", "A", "p"): 1, ("T", "A", "A"): 1, ("E", "A", "q"): 1,
                 ("T", "A", "B"): 1, ("E", "B", "p"): 1, ("T", "B", EOS): 1}
    assert sum(f.values()) == 2 * 3 + 1


def test_viterbi_matches_brute_force():
    rng = random.Random(2002)
    for _ in range(300):
        k = rng.randint(1, 3)
        tags = TAGS[:k]
        n = rng.randint(1, 6)
        words = [rng.choice(VOCAB) for _ in range(n)]
        w = random_weights(rng, tags, VOCAB, -3, 3)
        ys, s = viterbi(words, tags, w)
        assert len(ys) == n
        assert s == score(w, words, ys) == brute_force(words, tags, w)


def test_viterbi_ties_and_errors():
    assert viterbi(["p", "q"], TAGS, {}) == (["A", "A"], 0)
    with pytest.raises(ValueError):
        viterbi([], TAGS, {})


def test_lazy_average_equals_naive_average():
    rng = random.Random(5)
    for _ in range(10):
        data = []
        for _ in range(rng.randint(1, 6)):
            n = rng.randint(1, 5)
            data.append(([rng.choice(VOCAB) for _ in range(n)], [rng.choice(TAGS) for _ in range(n)]))
        epochs = rng.randint(1, 4)
        _, avg, _ = train(data, TAGS, epochs)
        naive = train_naive_average(data, TAGS, epochs)
        keys = set(avg) | set(naive)
        assert all(avg.get(k, Fraction(0)) == naive.get(k, Fraction(0)) for k in keys)


def separable_data(rng, tags, count):
    """Label random sentences with a fixed weight vector, keeping only those with a unique best tagging."""
    u = random_weights(rng, tags, VOCAB)
    data, margin, r2 = [], None, 0
    while len(data) < count:
        n = rng.randint(1, 5)
        words = [rng.choice(VOCAB) for _ in range(n)]
        scored = sorted(((score(u, words, ys), ys) for ys in product(tags, repeat=n)), reverse=True)
        if len(scored) > 1 and scored[0][0] == scored[1][0]:
            continue
        gold = list(scored[0][1])
        data.append((words, gold))
        if len(scored) > 1:
            m = scored[0][0] - scored[1][0]
            margin = m if margin is None else min(margin, m)
        fg = phi(words, gold)
        for _, ys in scored[1:]:
            r2 = max(r2, sq_norm(diff(fg, phi(words, ys))))
    return u, data, margin, r2


def test_mistake_bound_on_separable_data():
    """Collins (2002), Theorem 1: mistakes <= R^2 / delta^2 with delta = margin / ||u||."""
    rng = random.Random(17)
    for _ in range(6):
        u, data, margin, r2 = separable_data(rng, TAGS, 12)
        w, _, mistakes = train(data, TAGS, 60)
        total = sum(mistakes)
        assert total * margin * margin <= r2 * sq_norm(u)
        assert mistakes[-1] == 0
        assert all(viterbi(x, TAGS, w)[0] == y for x, y in data)


def test_mistakes_stop_once_an_epoch_is_clean():
    rng = random.Random(3)
    _, data, _, _ = separable_data(rng, TAGS[:2], 10)
    _, _, mistakes = train(data, TAGS[:2], 40)
    first_clean = mistakes.index(0)
    assert all(m == 0 for m in mistakes[first_clean:])


def test_averaged_tagger_on_small_corpus():
    tags = ["D", "J", "N", "V"]
    w, avg, mistakes = train(CORPUS, tags, 10)
    assert mistakes[-1] == 0
    for x, y in CORPUS:
        assert viterbi(x, tags, avg)[0] == y
    assert viterbi("the old dogs walk".split(), tags, avg)[0] == ["D", "J", "N", "V"]

History

Rosenblatt introduced the perceptron in 1958, and Novikoff proved its mistake bound for separable data in 1962. Freund and Schapire (1999) studied the voted perceptron and its averaged form. Collins (2002) brought the algorithm to sequence tasks: he replaced the argmax over classes by Viterbi decoding over tag sequences, proved that the bounds carry over with a margin and a radius defined on whole sequences, and showed that the averaged perceptron beats a maximum entropy tagger with the same features on part-of-speech tagging and NP chunking. The method became a standard way to train taggers and parsers in the following decade.

References

  1. Collins 2002, Figure 1 (the tagging algorithm), Figure 2 (the general algorithm), Section 2.5 (averaged parameters), Section 3 (Definition 1 and Theorem 1 on separable data, Theorem 2 on inseparable data, Theorem 3 on generalization), Section 4 (part-of-speech tagging and NP chunking experiments)

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
  • at least three sources
  • a scene preset for the example