Algorithmcore
Brill tagger
Also called transformation-based tagging, transformation-based learning.
Start from the most frequent tag of each word, then apply learned rewrite rules in order, each chosen greedily to fix the most errors.
- Solves
- Part-of-speech tagging
- Time
- O(r n k) worst
- Space
- O(n k) extra
- Where
- k = the number of tags; n = the number of training tokens; r = the number of learned rules
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Eric Brill, 1995
The Brill tagger tags a sentence in two stages. First it gives each word its most frequent tag in the training corpus. Then it runs an ordered list of rewrite rules over the tags, such as "change NN to VB when the previous tag is TO". The rules are learned by transformation-based error-driven learning: at each step the learner picks the rule that removes the most errors on the training corpus, applies it, and repeats. Unlike the HMM tagger, it has no probabilities and no search over tag sequences; the model is a short list of rules that a person can read.
In plain words
Start with a simple guess: every word gets the tag it had most often in a corpus that people have already tagged. This guess is right most of the time, but it is wrong whenever a word changes its role with the context, as "race" does in "to race" and "the race". The learner now looks at every rule of a few fixed shapes, such as "change tag A to tag B when the previous tag is C". For each rule it counts how many wrong tags the rule would fix and how many right tags it would break. It keeps the rule with the best balance, applies it to the whole corpus, and does the same again on the corrected tags. It stops when no rule helps. To tag new text, it makes the same first guess and applies the rules in the order they were learned.
The problem
Input: a training corpus of sentences with gold tags from a tag set of tags, a set of rule templates, and a threshold . Output: an initial annotator and an ordered list of rules . A rule changes tag to tag at each position where the environment is true. The templates are the eleven nonlexicalized templates of Brill (1995, Section 4.1), where and are tags: the previous (next) tag is ; the tag two before (after) is ; one of the two previous (next) tags is ; one of the three previous (next) tags is ; the previous tag is and the next tag is ; the previous (next) two tags are and . The code adds the lexicalized template "the current word is " from Section 4.2. Positions before the sentence read the tag <s> and positions after it read </s>.
The learner is greedy. Each step chooses the rule with the largest score , where is the number of training errors of the current tags . It stops when the best score is below . The rule list is not optimal in any sense: the template set is a heuristic, and so is the greedy choice. Only the single step is exact.
Brill fixes two details that change the result (Section 2). Rules are applied with delayed effect: all positions where the rule fires are found first, and then all of them are changed. And under the lexicon rule of Section 4.1, a word seen in training may only change to a tag it had at least once in training. An unknown word may change to any tag.
The algorithm
For a rule , counts the positions with current tag , gold tag , environment true and allowed for the word, and counts the positions with current tag , gold tag , environment true and allowed. Under delayed effect the score of is exactly . The search is data-driven, as Brill notes: only rules with can have a positive score, and each such rule is found from a wrong position where it would fix the tag.
BRILL-TRAIN(corpus, θ)- 1
c ← the most frequent training tag of each word (the most frequent tag overall for an unknown word) - 2
rules ← empty list - 3
repeat - 4
for each wrong position p and each environment e true at p: good(e, c_p → gold_p) += 1, if the lexicon allows gold_p for the word - 5
for each right position p, each environment e true at p and each b with good(e, c_p → b) > 0: bad(e, c_p → b) += 1, if the lexicon allows b - 6
r ← a rule with the largest good(r) - bad(r), ties to the smallest rule in a fixed order - 7
if there is no r or good(r) - bad(r) < θ then return rules - 8
c ← apply r to every sentence with delayed effect - 9
append r to rules
To tag a sentence, give each word its initial tag and apply in order, each with delayed effect and the lexicon rule. The tie order of the code compares the template index first, then the arguments, then , then . Brill does not state a tie rule.
Example
Take six tagged sentences: "we/PRP want/VBP to/TO race/VB", "the/DT race/NN ended/VBD", "the/DT race/NN", "a/DT race/NN is/VBZ fun/JJ", "they/PRP like/VBP to/TO race/VB" and "we/PRP went/VBD to/TO the/DT race/NN". The word "race" is NN four times and VB twice, so the initial annotator tags it NN everywhere. Every other word has one tag. The initial tagging has 2 errors, both on "race" after "to".
The learner scores the candidates. Seven rules change NN to VB with and , for score 2:
| rule | good | bad | score |
|---|---|---|---|
| previous tag is TO | 2 | 0 | 2 |
| tag two before is VBP | 2 | 0 | 2 |
| one of the two previous tags is VBP | 2 | 0 | 2 |
| one of the three previous tags is PRP | 2 | 0 | 2 |
| one of the three previous tags is VBP | 2 | 0 | 2 |
previous tag is TO and next tag is </s> |
2 | 0 | 2 |
| previous two tags are VBP and TO | 2 | 0 | 2 |
| one of the two previous tags is TO | 2 | 1 | 1 |
| the current word is race | 2 | 4 | -2 |
"One of the two previous tags is TO" also fires on "went to the race", where NN is right, so it loses one. The tie rule picks "previous tag is TO", the first template. This is also the first rule Brill learned from the Penn Treebank (Figure 4). After it, the training error is 0 and learning stops. The table shows why the templates are a heuristic: "one of the three previous tags is PRP" fits this corpus as well as the linguistically sensible rule. On "they want to race" the learned tagger gives PRP VBP TO VB, and on "the race" it gives DT NN.
Correctness
The proof in proofs/correctness.md shows three things. Under delayed effect, whether a rule fires at a position depends only on the old tags, so the change in the error count is a sum over positions: where a wrong becomes the gold , where a right becomes , and 0 elsewhere. So the score is exactly . Lines L4 and L5 compute good and bad exactly for every rule with , and every rule with a positive score is among them, so L6 returns the best rule with the stated tie rule (a theorem about one step). Each learned rule removes at least errors, so training ends after at most rules, where is the initial error count. The test file checks one step against a brute force that applies every instantiated rule, for several steps on random corpora.
Proof: The learning step of the Brill tagger picks the rule with the largest error reduction, and learning stopsfull
Setting. The training corpus has sentences with gold tags and current tags . A position is a pair . A rule is with , where is a template with its arguments (an environment). Let say that is true at on the current tags, and let be the lexicon rule: is unknown, or was seen with tag in training. The rule fires at when , and . Application has delayed effect: all firing positions are found on the current tags first, and then each of them gets tag . Let be the number of positions with .
This claim is about the learner as an optimizer of the training error, one step at a time. It does not claim that the list of rules is optimal, or that the rules improve accuracy on new text. Those are heuristic and measured questions.
Lemma 1: the score of a rule is its exact error reduction
Define as the number of firing positions with , and as the number of firing positions with . Then .
Proof. Under delayed effect, whether a position fires depends only on the current tags , not on the changes made at other positions, so each position can be looked at alone. A position that does not fire keeps its tag and its error status. A firing position changes from to . If , a wrong tag becomes right: the error count drops by 1. If , a right tag becomes wrong: it rises by 1. If is a third tag, the tag is wrong before and after. Summing over positions gives the claim.
With immediate effect the lemma fails: a change at position can make a rule fire or not fire at , so the effect is not a sum over independent positions. Brill's A A A A A A example (and the first test in the test file) shows this.
Lemma 2: the code computes good and bad exactly for every rule with good at least 1
Line L4 visits each wrong position whose word allows its gold tag. For each environment in instances, which is the set of all environments true at (the test file checks this set against holds for every template and argument), it adds 1 to . A position adds to exactly when , holds, and the lexicon allows , which is the definition. So the dictionary good holds exactly the rules with , with their values.
Line L5 visits each right position, with . For each environment true there and each such that is in good, it adds 1 to when the lexicon allows . These are exactly the firing positions of with . So is exact for every rule in good.
Theorem 1: one learning step
Let over all rules built from the templates, the tags and the training words. If , then L6 returns the rule with score that is smallest in the order of rule_key among all rules with score .
Proof. A rule with has score , so every rule with score is in the dictionary good. By Lemmas 1 and 2, L6 computes the true score of each rule in good. It scans them in rule_key order and replaces the current best only on a strict improvement, so it returns the first maximizer in that order. That is also the first maximizer among all rules.
If , L6 returns a rule with score at most 0, or none, and L7 stops, since the threshold is at least 1. The test file checks Theorem 1 against a brute force that applies every one of the instantiated rules to the corpus, on random corpora with 3 tags and 4 words, for several steps in a row.
Theorem 2: training ends, and the scores add up
Each rule appended at L9 has score (the threshold), and L8 applies it, so by Lemma 1 the training error after rules is . Errors are nonnegative integers, so at most rules are learned, and the loop ends after at most calls of best_rule. The final training error is minus the sum of the scores.
Tagging new text with the function tag applies the initial annotator and then the same rules, in the same order, with the same application function. So on the training sentences it reproduces the tags that training ended with; the test file checks this.
Complexity
Let be the number of training tokens. Each environment set has a constant size (at most 18 environments per position with the twelve templates), so L4 takes time and L5 takes time with hash tables, and L6 and L8 take time linear in the number of candidates and in . With learned rules, training takes time and space for the counts. Since each rule removes at least one error, is at most the initial number of errors. Tagging a sentence of words with rules takes time, since each rule is one pass with a constant-time test per word. Brill points to an indexed training method of Ramshaw and Marcus (1994) that is much faster in practice (Section 4.1).
Properties
- Greedy: each step is an exact maximization of the training error reduction (a theorem), but the list as a whole is not optimal (the greedy choice and the templates are heuristics).
- Deterministic: with a fixed tie rule, the same corpus always gives the same list.
- Readable: the model is a short list of rules such as "change NN to VB if the previous tag is TO".
- Not probabilistic: it gives one tag per word, with no score, so it cannot give a k-best list or a confidence.
- Measured accuracy (Brill 1995, Table 1, with no unknown words in the test set): 97.2% with 447 contextual rules learned from 600,000 words of the Penn Treebank Wall Street Journal corpus, 97.0% without the lexicalized templates (378 rules), and 96.7% with 215 rules from 64,000 words. The first 200 rules alone give 97.0%.
- Measured open-vocabulary accuracy (Section 4.3): 96.6% overall and 82.2% on unknown words, with 243 rules for unknown words and 447 contextual rules. The initial annotator alone gives 92.4%.
Variants and improvements
- Immediate effect. Applying each change at once, left to right, lets one change trigger the next. On A A A A A A with "change A to B if the previous tag is A", delayed effect gives A B B B B B, while immediate left-to-right effect gives A B A B A B (Brill 1995, Section 2). The score is then no longer a sum over independent positions.
- Lexicalized templates. Brill adds templates that refer to words, such as "the word two after is "; they reduce the error rate by 6.7% in his test (Section 4.2).
- Unknown words. A second learner starts unknown words as proper nouns if capitalized and common nouns otherwise, and learns rules from prefixes, suffixes, characters and neighbouring words, such as "change NN to NNS if the word has suffix -s" (Section 4.3).
- Other initial annotators. The initial state can be the output of an HMM tagger or any other tagger; the learner then fixes its typical errors.
- Other tasks. The same learner works for any labeling task with a gold standard, for example text chunking with BIO tags, and Brill also applied it to parsing.
- Relation to decision trees. Brill proves that for a fixed set of questions, every binary decision tree can be converted into a transformation list (Section 3.1). A transformation list can also use the result of earlier rules at nearby positions, which a tree trained on fixed features cannot.
When to use it
Use a Brill tagger when you want a model that people can read and edit, when you need to fix the errors of another tagger with a few rules, or when you work with a small tagged corpus and want a simple baseline. For the best accuracy, a discriminative sequence model such as the structured perceptron, a conditional random field or a neural tagger is a better choice, and training them is much faster than the plain Brill learner on a large corpus.
Pitfalls
- Delayed and immediate effect give different results. Train and tag with the same choice; the score formula is exact only for delayed effect.
- Rule order matters. A later rule was learned on the output of the earlier rules, so the list must be applied in order and cannot be sorted or pruned in the middle without a loss.
- Spurious rules. When many rules tie, the tie rule decides which one is learned, and a rule may fit the training corpus by accident. The example above has a tie between "previous tag is TO" and "one of the three previous tags is PRP".
- Training cost. A plain implementation scans the whole corpus for every rule, which is slow on a million words. Use an index of where each rule fires.
- Low thresholds overfit. Rules learned at the end of the list fix one or two training errors each and add little on new text; Brill reports that the first 200 of 447 rules give almost all of the gain.
- The lexicon rule needs the full tag list of each training word, not only its most frequent tag.
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/brill-tagger/. The authors are listed in prov/W3YAEV.jsonl.
"""Transformation-based error-driven learning of tagging rules (Brill 1995).
Initial state: each known word gets its most frequent training tag (ties go
to the smallest tag name); an unknown word gets a default tag.
A rule is (template, args, a, b): "change tag a to tag b when the template
holds with these arguments". The templates are the eleven nonlexicalized
templates of Brill (1995), Section 4.1, and the lexicalized template "the
current word is w". Positions before the sentence read the tag "<s>" and
positions after it read "</s>".
Application has delayed effect, as in Brill's experiments: all positions
where the rule triggers are found first, then all of them are changed. With
the lexicon rule of Brill's Section 4.1, a known word may only change to a
tag it had at least once in training; an unknown word may change to any tag.
The score of a rule is the net number of errors it removes on the training
corpus: good (wrong tag a becomes the right tag b) minus bad (right tag a
becomes wrong). The learner picks the best rule, with ties broken by the
smallest rule in the order of rule_key, applies it, and repeats while the
best score is at least the threshold.
"""
from typing import Dict, Iterable, List, Sequence, Set, Tuple
LEFT, RIGHT = "<s>", "</s>"
TEMPLATES = ["PREV1", "NEXT1", "PREV2", "NEXT2", "PREV1OR2", "NEXT1OR2", "PREV1OR2OR3",
"NEXT1OR2OR3", "SURROUND", "PREVBIGRAM", "NEXTBIGRAM", "CURWD"]
Rule = Tuple[str, Tuple[str, ...], str, str]
def tag_at(tags: Sequence[str], p: int) -> str:
if p < 0:
return LEFT
if p >= len(tags):
return RIGHT
return tags[p]
def instances(words: Sequence[str], tags: Sequence[str], p: int) -> Set[Tuple[str, Tuple[str, ...]]]:
"""Every (template, args) that is true at position p."""
t = lambda d: tag_at(tags, p + d) # noqa: E731
out = {
("PREV1", (t(-1),)), ("NEXT1", (t(1),)), ("PREV2", (t(-2),)), ("NEXT2", (t(2),)),
("SURROUND", (t(-1), t(1))), ("PREVBIGRAM", (t(-2), t(-1))), ("NEXTBIGRAM", (t(1), t(2))),
("CURWD", (words[p],)),
}
for z in {t(-1), t(-2)}:
out.add(("PREV1OR2", (z,)))
for z in {t(1), t(2)}:
out.add(("NEXT1OR2", (z,)))
for z in {t(-1), t(-2), t(-3)}:
out.add(("PREV1OR2OR3", (z,)))
for z in {t(1), t(2), t(3)}:
out.add(("NEXT1OR2OR3", (z,)))
return out
def holds(template: str, args: Tuple[str, ...], words: Sequence[str], tags: Sequence[str], p: int) -> bool:
"""True when the template with these arguments holds at position p."""
t = lambda d: tag_at(tags, p + d) # noqa: E731
if template == "PREV1":
return t(-1) == args[0]
if template == "NEXT1":
return t(1) == args[0]
if template == "PREV2":
return t(-2) == args[0]
if template == "NEXT2":
return t(2) == args[0]
if template == "PREV1OR2":
return args[0] in (t(-1), t(-2))
if template == "NEXT1OR2":
return args[0] in (t(1), t(2))
if template == "PREV1OR2OR3":
return args[0] in (t(-1), t(-2), t(-3))
if template == "NEXT1OR2OR3":
return args[0] in (t(1), t(2), t(3))
if template == "SURROUND":
return (t(-1), t(1)) == args
if template == "PREVBIGRAM":
return (t(-2), t(-1)) == args
if template == "NEXTBIGRAM":
return (t(1), t(2)) == args
if template == "CURWD":
return words[p] == args[0]
raise ValueError("unknown template " + template)
def rule_key(r: Rule):
"""The tie order: template index, then arguments, then from tag, then to tag."""
return (TEMPLATES.index(r[0]), r[1], r[2], r[3])
class Lexicon:
"""Tag counts of each training word, for the initial annotator and the lexicon rule."""
def __init__(self, corpus, default: str = None):
self.counts: Dict[str, Dict[str, int]] = {}
total: Dict[str, int] = {}
for words, tags in corpus:
for w, g in zip(words, tags):
row = self.counts.setdefault(w, {})
row[g] = row.get(g, 0) + 1
total[g] = total.get(g, 0) + 1
self.default = default if default is not None else min(total, key=lambda g: (-total[g], g))
def initial(self, words: Sequence[str]) -> List[str]:
out = []
for w in words:
row = self.counts.get(w)
out.append(min(row, key=lambda g: (-row[g], g)) if row else self.default)
return out
def allows(self, w: str, b: str) -> bool:
return w not in self.counts or b in self.counts[w]
def apply_rule(rule: Rule, words: Sequence[str], tags: List[str], lex: Lexicon = None,
delayed: bool = True) -> List[str]:
"""Apply one rule to a sentence and return the new tags.
delayed=True finds every trigger first (Brill's choice); delayed=False
changes the tags left to right at once, so a change can trigger the next.
"""
template, args, a, b = rule
new = list(tags)
src = tags if delayed else new
for p in range(len(words)):
if new[p] == a and holds(template, args, words, src, p) and (lex is None or lex.allows(words[p], b)):
new[p] = b
return new
def errors(corpus_tags: Iterable[Sequence[str]], gold: Iterable[Sequence[str]]) -> int:
return sum(1 for ts, gs in zip(corpus_tags, gold) for t, g in zip(ts, gs) if t != g)
def best_rule(words_list, cur, gold, lex: Lexicon = None):
"""Return (rule, score) of the best rule on the current tagging, or (None, 0)."""
good: Dict[Rule, int] = {}
for words, ts, gs in zip(words_list, cur, gold): # @line L4
for p in range(len(words)):
if ts[p] != gs[p] and (lex is None or lex.allows(words[p], gs[p])):
for template, args in instances(words, ts, p):
r = (template, args, ts[p], gs[p])
good[r] = good.get(r, 0) + 1
by_env: Dict[Tuple[str, Tuple[str, ...], str], List[str]] = {}
for (template, args, a, b) in good:
by_env.setdefault((template, args, a), []).append(b)
bad: Dict[Rule, int] = {}
for words, ts, gs in zip(words_list, cur, gold): # @line L5
for p in range(len(words)):
if ts[p] == gs[p]:
for template, args in instances(words, ts, p):
for b in by_env.get((template, args, ts[p]), ()):
if lex is None or lex.allows(words[p], b):
r = (template, args, ts[p], b)
bad[r] = bad.get(r, 0) + 1
best, best_score = None, 0
for r in sorted(good, key=rule_key): # @line L6
s = good[r] - bad.get(r, 0)
if best is None or s > best_score:
best, best_score = r, s
return best, best_score
def train(corpus, threshold: int = 1, max_rules: int = 1000, default: str = None,
use_lexicon: bool = True):
"""Learn an ordered list of rules. Return (lexicon, rules, scores)."""
if threshold < 1:
raise ValueError("the threshold must be at least 1")
lex = Lexicon(corpus, default)
words_list = [list(w) for w, _ in corpus]
gold = [list(g) for _, g in corpus]
cur = [lex.initial(w) for w in words_list] # @line L1
rules: List[Rule] = [] # @line L2
scores: List[int] = []
while len(rules) < max_rules: # @line L3
r, s = best_rule(words_list, cur, gold, lex if use_lexicon else None)
if r is None or s < threshold: # @line L7
break
cur = [apply_rule(r, w, ts, lex if use_lexicon else None) for w, ts in zip(words_list, cur)] # @line L8
rules.append(r) # @line L9
scores.append(s)
return lex, rules, scores
def tag(words: Sequence[str], lex: Lexicon, rules: Sequence[Rule], use_lexicon: bool = True) -> List[str]:
"""Tag a sentence: the initial annotator, then every rule in order."""
ts = lex.initial(words)
for r in rules:
ts = apply_rule(r, words, ts, lex if use_lexicon else None)
return ts
test_brill_tagger.py 145 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/brill-tagger/. The authors are listed in prov/W3YAEV.jsonl.
import random
from itertools import product
import pytest
from brill_tagger import (LEFT, RIGHT, TEMPLATES, Lexicon, apply_rule, best_rule, errors, instances,
holds, rule_key, tag, train)
ONE_ARG = ["PREV1", "NEXT1", "PREV2", "NEXT2", "PREV1OR2", "NEXT1OR2", "PREV1OR2OR3", "NEXT1OR2OR3"]
TWO_ARG = ["SURROUND", "PREVBIGRAM", "NEXTBIGRAM"]
EXAMPLE = [
("we want to race".split(), ["PRP", "VBP", "TO", "VB"]),
("the race ended".split(), ["DT", "NN", "VBD"]),
("the race".split(), ["DT", "NN"]),
("a race is fun".split(), ["DT", "NN", "VBZ", "JJ"]),
("they like to race".split(), ["PRP", "VBP", "TO", "VB"]),
("we went to the race".split(), ["PRP", "VBD", "TO", "DT", "NN"]),
]
def all_rules(tags, vocab):
vals = list(tags) + [LEFT, RIGHT]
envs = [(t, (z,)) for t in ONE_ARG for z in vals]
envs += [(t, (z, w)) for t in TWO_ARG for z in vals for w in vals]
envs += [("CURWD", (w,)) for w in vocab]
return [(t, args, a, b) for t, args in envs for a in tags for b in tags if a != b]
def brute_best(words_list, cur, gold, lex, rules):
base = errors(cur, gold)
best, best_score = None, None
for r in sorted(rules, key=rule_key):
new = [apply_rule(r, w, ts, lex) for w, ts in zip(words_list, cur)]
s = base - errors(new, gold)
if best is None or s > best_score:
best, best_score = r, s
return best, best_score
def random_corpus(rng, tags, vocab, sentences):
corpus = []
for _ in range(sentences):
n = rng.randint(1, 6)
ws = [rng.choice(vocab) for _ in range(n)]
gs = [rng.choice(tags) for _ in range(n)]
corpus.append((ws, gs))
return corpus
def test_delayed_and_immediate_effect():
"""Brill (1995), Section 2: A A A A A A and the rule A -> B if the previous tag is A."""
words = ["x"] * 6
rule = ("PREV1", ("A",), "A", "B")
assert apply_rule(rule, words, ["A"] * 6) == ["A", "B", "B", "B", "B", "B"]
assert apply_rule(rule, words, ["A"] * 6, delayed=False) == ["A", "B", "A", "B", "A", "B"]
def test_instances_agree_with_holds():
rng = random.Random(4)
tags = ["A", "B", "C"]
vals = tags + [LEFT, RIGHT]
for _ in range(50):
n = rng.randint(1, 6)
words = [rng.choice("pqr") for _ in range(n)]
ts = [rng.choice(tags) for _ in range(n)]
for p in range(n):
inst = instances(words, ts, p)
for t in ONE_ARG:
for z in vals:
assert holds(t, (z,), words, ts, p) == ((t, (z,)) in inst)
for t in TWO_ARG:
for z, w in product(vals, vals):
assert holds(t, (z, w), words, ts, p) == ((t, (z, w)) in inst)
assert ("CURWD", (words[p],)) in inst
def test_best_rule_matches_brute_force():
rng = random.Random(1995)
tags = ["A", "B", "C"]
vocab = ["p", "q", "r", "s"]
rules = all_rules(tags, vocab)
checked = 0
for _ in range(12):
corpus = random_corpus(rng, tags, vocab, rng.randint(2, 5))
lex = Lexicon(corpus)
words_list = [w for w, _ in corpus]
gold = [g for _, g in corpus]
cur = [lex.initial(w) for w in words_list]
for _ in range(3):
r, s = best_rule(words_list, cur, gold, lex)
rb, sb = brute_best(words_list, cur, gold, lex, rules)
if sb < 1:
assert r is None or s == sb or s <= 0
break
assert (r, s) == (rb, sb)
checked += 1
cur = [apply_rule(r, w, ts, lex) for w, ts in zip(words_list, cur)]
assert checked >= 10
def test_training_scores_are_error_reductions():
rng = random.Random(7)
tags = ["A", "B", "C"]
vocab = ["p", "q", "r", "s", "t"]
corpus = random_corpus(rng, tags, vocab, 8)
lex, rules, scores = train(corpus)
cur = [lex.initial(w) for w, _ in corpus]
gold = [g for _, g in corpus]
e = errors(cur, gold)
for r, s in zip(rules, scores):
cur = [apply_rule(r, w, ts, lex) for (w, _), ts in zip(corpus, cur)]
e2 = errors(cur, gold)
assert e - e2 == s >= 1
e = e2
assert rules
assert [tag(w, lex, rules) for w, _ in corpus] == cur
def test_lexicon_rule_blocks_unseen_tags():
corpus = [(["the", "dog"], ["D", "N"])]
lex = Lexicon(corpus)
rule = ("PREV1", ("D",), "N", "V")
assert apply_rule(rule, ["the", "dog"], ["D", "N"], lex) == ["D", "N"]
assert apply_rule(rule, ["the", "cat"], ["D", "N"], lex) == ["D", "V"]
assert apply_rule(rule, ["the", "dog"], ["D", "N"]) == ["D", "V"]
def test_example_learns_nn_to_vb_after_to():
lex, rules, scores = train(EXAMPLE)
assert lex.initial(["race"]) == ["NN"]
assert rules[0] == ("PREV1", ("TO",), "NN", "VB") and scores[0] == 2
assert tag("they want to race".split(), lex, rules) == ["PRP", "VBP", "TO", "VB"]
assert tag("the race".split(), lex, rules) == ["DT", "NN"]
def test_initial_annotator_and_errors():
lex = Lexicon([(["a", "a", "b"], ["X", "Y", "Y"]), (["a"], ["Y"])], default="Z")
assert lex.initial(["a", "b", "c"]) == ["Y", "Y", "Z"]
with pytest.raises(ValueError):
train(EXAMPLE, threshold=0)
assert len(TEMPLATES) == 12
History
Before statistical taggers, taggers used hand-written rules. Church (1988) and DeRose (1988) showed that Markov model taggers trained on a tagged corpus did better. Brill proposed transformation-based error-driven learning as a way to learn rules automatically, with earlier versions in 1992 and 1994 (Brill 1995, footnote 9). His 1995 paper in Computational Linguistics describes the general method, proves that transformation lists are at least as expressive as decision trees, and reports results on the Penn Treebank that were better than those of the Markov model tagger it compares with, with a few hundred rules instead of thousands of probabilities. The method was later used for chunking, parsing and other labeling tasks.
References
- Brill 1995, Section 2 and Figures 1 and 2 (the learning scheme, and the A A A A A A example of delayed and immediate effect), Section 4.1 (the initial annotator, the lexicon rule, the nonlexicalized templates, Figure 3 with the learning pseudocode, Figure 4 with the first rules), Section 4.2 and Table 1 (lexicalized templates and closed-vocabulary results), Section 4.3 (unknown words and the open-vocabulary results)
- Christopher D. Manning and Hinrich Schütze, Foundations of Statistical Natural Language Processing, MIT Press, 1999, Chapter 10 (part-of-speech tagging)
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 W3YAEV Edit this page History Report an error Markdown