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.
- Solves
- Sequence labeling
- 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
- Model
- Word RAM
- Properties
- deterministicnot exactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 classes replaced by an argmax over 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 , , of sentences and gold tag sequences over tags; a feature map ; a number of epochs . Output: a weight vector such that the tagger makes few errors. is the set of all tag sequences for a sentence of words.
To decode by dynamic programming, must be a sum of local feature vectors, each depending on the words, the position and a few neighbouring tags. The code uses first-order features: one count for each transition , with and , 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
PERCEPTRON-TRAIN((x_1, y_1) .. (x_N, y_N), T)- 1
w ← 0; u ← 0; c ← 0 ▷ u and c keep the average lazily - 2
for epoch ← 1 to T do - 3
for i ← 1 to N do - 4
z ← VITERBI(x_i, w) ▷ argmax over z of w · Φ(x_i, z) - 5
if z ≠ y_i then - 6
d ← Φ(x_i, y_i) - Φ(x_i, z) - 7
w ← w + d; u ← u + c d - 8
c ← c + 1 - 9
return w and the averaged weights w - u / c
The averaged weights are the mean of the weights after each of the examples (Collins 2002, Section 2.5). Summing after every example costs per example. The code uses the identity , so each update costs only the size of . 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.
- "the runs": all taggings score 0, and the tie rule picks D D. The update adds 1 to , (N, runs) and , and subtracts 1 from , (D, runs) and . The shared features and (D, the) cancel.
- "dogs run": the decoder picks D N with score 2, using the weight of and from step 1. The gold is N V, so a second update follows. It moves back to 0 and back to 0.
- "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 for the transition and 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 sequences). Second, Collins's Theorem 1: if some unit vector separates the data with margin , so that for all wrong , and , then the algorithm makes at most mistakes in total, however many epochs it runs. The proof is the one of Novikoff for the binary perceptron: each mistake raises by at least , while grows by at most , since the predicted scored at least as high as . Note that the bound does not depend on the number of sequences in , which grows as . 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 for , where is a sentence and its gold tags. is the set of all tag sequences of the length of over the tags. is the global feature vector: the counts of the transition features , with and , and of the emission features . The score of is .
Claim 1: Viterbi returns a highest-scoring tag sequence
The score splits into local terms: . Let be the largest value of the first local terms over the prefixes with . Then and , because the terms of a prefix ending in at do not depend on , and any prefix ending in can be replaced by a best one without changing the new terms. The best total is , 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 sequences for and .
Claim 2: the mistake bound (Collins 2002, Theorem 1)
Suppose there is a vector with and a such that for all and all with . Let be a number with for all such and . Then the perceptron, run for any number of epochs, makes at most mistakes.
Proof. Let be the weights before the -th mistake, with . At the -th mistake, on example , the decoder returns with , since has the highest score under (Claim 1). The update is with .
Lower bound. , so by induction . By the Cauchy-Schwarz inequality, .
Upper bound. , because by the choice of . By induction .
Together, , so .
Consequence. When the bound holds, there is an epoch with no mistakes after at most epochs, and from then on the weights do not change, so every later epoch is also clean and the final tags every training sentence correctly. The test file builds separable data from a random integer vector , keeps only sentences whose best tagging under is unique, and checks the bound in the integer form , where is the smallest score gap under , so that . 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 , with . Let be the update at step ( if there was no mistake), so the weights after step are . The averaged weights of Collins (2002, Section 2.5) are
where . The code keeps , the number of examples seen before step , and adds to at line L7; at the end and line L9 returns . 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.
Complexity
Each training step decodes one sentence. With first-order features, Viterbi takes time for a sentence of words, so one epoch over tokens takes time and epochs take , plus the cost of computing the features. An update touches at most features. With second-order features, as in Collins's experiments, decoding takes . Space is the weights and the second vector for the average, plus for the decoder. On separable data, Theorem 1 also bounds the number of updates by , 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 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 starts at 0.
- Exact decoding is required by the proof: with an approximate decoder such as beam search, the predicted may score lower than , 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 . 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.
# 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
- 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.
| 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 KYD1XY Edit this page History Report an error Markdown