Algorithmcore
HMM part-of-speech tagger
Also called bigram HMM tagger, trigram HMM tagger.
Tag words with an HMM whose states are tags: tag n-gram transitions and word emissions come from counts with smoothing, and Viterbi finds the best tag sequence in O(n k^(m+1)).
- Solves
- Part-of-speech tagging
- Time
- Θ(n k^(m+1)) worst
- Space
- Θ(n k^m) extra
- Where
- k = the number of tags; m = the order of the tag model; n = the number of words in the sentence
- Model
- Word RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Kenneth W. Church, Steven J. DeRose, Thorsten Brants, 1988
An HMM part-of-speech tagger treats the tags of a sentence as the hidden states of a hidden Markov model and the words as its outputs. It estimates the tag transition and word emission probabilities by counting in a tagged corpus, smooths them, and then finds the most probable tag sequence of a new sentence with the Viterbi algorithm. The Viterbi page describes the decoder for any HMM, and hmm-decoding states the decoding problem. This page is about the tagger as a whole: the boundary tags, the order of the model, the smoothing of the transitions, the handling of unknown words and the cost of a second-order state space, as in the TnT tagger of Brants (2000).
In plain words
Each word gets a tag such as noun or verb. The tagger learns two kinds of numbers from a corpus that people have already tagged: how often one tag follows the previous tag or two tags, and how often each tag produces each word. To tag a new sentence, it looks for the one sequence of tags that makes the sentence most likely under these numbers. There are far too many sequences to try one by one, but the best sequence that ends in a given tag at a given word only needs the best sequences that end one word earlier, so the search fills a table from left to right. Rare tag pairs get a share of the probability of shorter contexts, and a word never seen in training gets its tag guesses from its last letters.
The problem
Input: a tagged training corpus, the tag set with tags, an order , and a sentence . Output: a tag sequence that maximizes the model probability
where are start tags and is the end tag. With this is the bigram tagger, . With it is the trigram tagger of TnT, whose equation 1 has exactly this form with the end transition at the end. Since does not depend on , the same also maximizes . Logs are natural logs.
The algorithm
Training counts the predicted events. A sentence of tokens has of them: the tags and the end tag, each with its history of earlier symbols. Let be the count of a tag -gram whose last symbol is predicted, the number of predicted events whose history ends with the context , and the number of predicted events. The maximum likelihood estimates are and , with . TnT smooths by linear interpolation:
The weights come from deleted interpolation (Brants 2000, Figure 1). Start with all . For each -gram with count , compute the estimate of each order with this one event removed: for the last symbols of with context , and for order 0, with a zero denominator giving 0. Add to the weight of the order with the largest value, then divide all weights by their sum. Brants gives no tie rule; the code gives a tie to the higher order.
Known words use . An unknown word uses the suffix model (Brants 2000, Section 2.3, after Samuelsson 1993). From the tokens of rare words (frequency at most 10), estimate for each suffix of up to 10 letters. Then smooth from the empty suffix to the longest suffix of the word that was seen: , where is the suffix of length . The emission score is , which is up to the factor that is the same for all tags.
HMM-TAG(corpus, x_1 .. x_n, m) ▷ m = 1 bigram, m = 2 trigram (TnT)- 1
count the tag n-grams of lengths 1 .. m+1 over the predicted events, with m start tags <s> and one end tag </s> per sentence - 2
λ_0 .. λ_m ← DELETED-INTERPOLATION(counts) - 3
P(t | h) ← Σ_{j=0..m} λ_j P^(t | last j tags of h) - 4
P(w | t) ← f(w, t) / f(t) if w is known, else P(t | suffix of w) / P(t) - 5
δ_0(<s> .. <s>) ← 0 ▷ a state is the tuple of the last m tags - 6
for i ← 1 to n do - 7
for each tag t and state g: h ← (g without its first tag, t); δ_i(h) ← max over g of δ_{i-1}(g) + log P(t | g) + log P(x_i | t); ψ_i(h) ← the first maximizing g - 8
h_n ← the first state that maximizes δ_n(h) + log P(</s> | h) - 9
for i ← n downto 1 do y_i ← the last tag of h_i; h_{i-1} ← ψ_i(h_i) - 10
return y_1 .. y_n
The decoder works in log space with log 0 = -inf, because a product of a few hundred probabilities underflows in double precision. The test file has a sentence of 400 words whose plain product is 0.0, while its log score is about -834.4. The smallest positive double is about . Sums in log space use the log_add form of the log-sum-exp trick; the Viterbi recursion itself needs only max and +.
Example
Take a corpus of five tagged sentences, with D for determiner, J for adjective, N for noun and V for verb: "the/D dog/N runs/V", "the/D old/J dog/N runs/V", "dogs/N run/V", "the/D runs/N" and "old/J dogs/N walk/V". The bigram tagger () has predicted events. The tag counts are D 3, J 2, N 5, V 4 and </s> 5, and the history counts are <s> 5, D 3, J 2, N 5 and V 4. Deleted interpolation looks at the nine bigrams:
| bigram | count | bigram estimate | unigram estimate | winner |
|---|---|---|---|---|
(<s>, D) |
3 | 2/4 | 2/18 | λ_1 |
| (D, N) | 2 | 1/2 | 4/18 | λ_1 |
| (N, V) | 4 | 3/4 | 3/18 | λ_1 |
(V, </s>) |
4 | 3/3 | 4/18 | λ_1 |
| (J, N) | 2 | 1/1 | 4/18 | λ_1 |
| (D, J) | 1 | 0/2 | 1/18 | λ_0 |
(<s>, N) |
1 | 0/4 | 4/18 | λ_0 |
(N, </s>) |
1 | 0/4 | 4/18 | λ_0 |
(<s>, J) |
1 | 0/4 | 1/18 | λ_0 |
So and . For example , , , and .
Now tag "the runs". The word "runs" is a verb twice and a noun once, so and . Only D emits "the", so . At word 2 only N and V emit "runs":
- , so ;
- , so .
With the end transition, D N scores about and D V about . The tagger returns D N. The emission alone prefers V, but "the" is rarely followed by a verb, and the context wins. On "the dog runs" the same model returns D N V. The test file checks these sequences against a search over all tag sequences.
Correctness
The proof in proofs/correctness.md has two parts. First, after position the table holds, for each state of tags, the largest log probability of a tag prefix that ends in that state; this holds because the score of the next step depends only on the previous state, the new tag and the word (the optimal substructure of DAG dynamic programming). The end transition and the traceback then give a sequence of maximal . Second, the deleted interpolation weights are nonnegative and sum to 1, so each transition row is a convex combination of distributions when all its contexts were seen in training. A row whose context was never seen loses the mass of that order: TnT defines an estimate with a zero denominator as 0, so the model is deficient on such histories. This does not affect the correctness of the search, only the meaning of the scores.
Proof: The HMM tagger returns a most probable tag sequence, and its smoothed transitions are distributionsfull
Fix the order , the tag set with tags, a sentence with , and the two tables of the trained model: for a history of symbols from and a tag , and . Write and , and for the state after position . The model gives
with and .
Claim 1: Viterbi over states of m tags is exact
For and a state , let be the largest value of the partial sum over the tag prefixes with , and if there is none.
Invariant: after the loop of line L6 has run for position , the table delta holds for every state with , and back[i] holds for each such a state such that a best prefix for ends with a best prefix for .
Base: line L5 sets , the empty sum. No other state has a prefix of length 0.
Step: a prefix with is a prefix with some state , followed by the tag , and is with its first symbol dropped and appended. Its sum is . The last two terms depend only on and , so for a fixed the sum is largest when the prefix of length is a best prefix for . Hence , where ranges over the states whose last symbols are the first symbols of . Line L7 computes this maximum over all states in delta and keeps the maximizer. A state with or a tag with is skipped; it can only give , so the maximum does not change.
By the invariant for , line L8 finds the maximum over of , which is , because every full sequence is a prefix of length followed by the end transition. Line L9 follows the stored maximizers from the final state back to position 1. Each step goes from a state to a predecessor that is part of a best prefix, so the tags read off form a sequence whose log probability equals the maximum. If no state has a finite score, every sequence has probability 0 and the code raises an error instead.
Claim 2: the interpolated transitions are distributions
Let be the number of predicted events with tag -gram (line L1) and the number of predicted events whose history ends with the context . Each predicted event with history ending in has exactly one predicted tag, so . Hence for a seen context, the estimate is nonnegative and sums to 1 over . The same holds for the order 0 estimate , since counts all predicted events.
Line L2 adds the count of each -gram to exactly one weight, so the weights are nonnegative and their sum before normalization is the number of predicted events, . After normalization they sum to 1. Line L3 forms , where is the last symbols of . If every was seen in training, this is a convex combination of distributions on the same set, so it is a distribution. If some was not seen, its estimate is defined as 0 (the rule under Figure 1 of Brants 2000), and the row sums to when those weights are positive. Such histories never occur in the training data. The model is then deficient on them, which TnT accepts; the test file checks both cases in exact arithmetic.
The emission of a known word sums to 1 over the words of the lexicon for each tag, because each token tagged has one word. The score of an unknown word is , which is the inverted suffix probability up to a factor that is the same for every tag. A factor common to all tags at one position adds the same constant to every path, so it does not change the argmax of Claim 1.
Complexity
Decoding has states at each position and predecessors of each state that can differ in the first tag, so the time is : for the bigram tagger and for the trigram tagger. The back pointers take space. Training reads the corpus once, so it is linear in its size times for the -gram counts. Deleted interpolation looks at each distinct -gram once. The suffix model adds up to 10 trie or table lookups per unknown word and work for each suffix length. For the 45 tags of the Penn Treebank, per word for a full trigram search; this is why TnT adds a beam.
Properties
- Exact decoding: the Viterbi search finds a maximum of under the model (a theorem, proved above). The tagger is not exact in any stronger sense: its accuracy is a measurement.
- Generative: it models and so can use untagged text through the Baum-Welch algorithm, but it cannot use overlapping features of the word such as its suffix and its capitalization at the same time, except through special models such as the suffix model.
- Measured accuracy: TnT reports 96.7% on the Penn Treebank (97.0% on known tokens and 85.5% on unknown tokens, with 2.9% unknown tokens) and 96.7% on the German NEGRA corpus, each averaged over ten 90/10 splits (Brants 2000, Tables 2 and 5).
- The tie rule of the code is the first maximizer in a fixed order, so the output is deterministic.
Variants and improvements
- Order. The bigram tagger is the HMM tagger of most textbooks. TnT uses ; Brants reports that the second-order model with careful smoothing matches the maximum entropy tagger of Ratnaparkhi (1996).
- Context-dependent weights. One set of per frequency class of the history is a common alternative. Brants reports that the groupings he tried were at best equal to one context-free set of weights, and some were worse (Section 2.2).
- Other smoothing. Laplace smoothing, Kneser-Ney smoothing and backoff can replace interpolation; the deleted interpolation page covers the general method with held-out data.
- Capitalization. TnT adds a flag for a capitalized word to each tag in the context, which doubles the tag set (Section 2.4).
- Beam search. TnT drops each state whose score is below the best score divided by ; Brants reports about twice the speed with no change in accuracy (Section 2.5). The search is then no longer exact.
- Unsupervised training. With no tagged corpus, the Baum-Welch algorithm can fit the HMM from text and a tag dictionary; the Bayesian HMM tagger puts priors on the tables and samples instead.
- Discriminative taggers. The maximum entropy Markov model, the structured perceptron and the conditional random field keep the Viterbi search but score rich, overlapping features.
When to use it
Use an HMM tagger when you need a fast, simple and well-understood baseline that trains by counting in seconds, or when you want a generative model that can also use untagged text. A trigram HMM with good smoothing and suffix handling is close to the discriminative feature-based taggers of the late 1990s. For the best accuracy today, use a discriminative model with word features or a neural encoder such as the BiLSTM-CRF.
Pitfalls
- Underflow: multiply probabilities in log space. A product of a few hundred probabilities is 0.0 in double precision.
- Missing end transition: without the model prefers sequences that end in tags that rarely end a sentence.
- Zero transition and emission probabilities: an unsmoothed bigram that never occurred makes every sequence through it impossible. The unigram term of the interpolation keeps every tag reachable as long as .
- Unseen histories: with the TnT rule , the transition row of an unseen history sums to less than 1. This is harmless for tagging but wrong if the scores are used as probabilities.
- The weight of the suffix model: Brants's text says the standard deviation of the tag probabilities, while equation 10 as printed has no square root. The code takes the square root. Check which one an implementation uses before you compare numbers.
- Second-order cost: with near 50, the state space has states per word. Restrict the tags of known words to those seen in training, as the code does through the zero emissions, or use a beam.
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/hmm-part-of-speech-tagger/. The authors are listed in prov/GZMMN9.jsonl.
"""An HMM part-of-speech tagger of order m (m = 1 bigram, m = 2 trigram as in TnT).
Training counts tag n-grams in a tagged corpus. Each sentence gets m start
tags <s> and one end tag </s>, so a sentence of n tokens gives n + 1
predicted events. The transition model is the linear interpolation of
maximum likelihood estimates of orders 0 to m, with weights from Brants's
deleted interpolation (TnT, Figure 1). Known words use the maximum
likelihood emission f(w, t) / f(t). Unknown words use the TnT suffix model.
Decoding is the Viterbi algorithm in log space over states that are the
last m tags, so it costs O(n k^(m + 1)) time.
Tie rules:
- deleted interpolation: when two of the deleted estimates are equal, the
higher order wins (the first maximum in the order m, m - 1, ..., 0);
- Viterbi: among equal scores, the first predecessor state and the first
final state in the enumeration order win (tags in sorted order).
"""
import math
from fractions import Fraction
from itertools import product
from typing import Callable, Dict, List, Sequence, Tuple
from nlslog import NEG_INF, safe_log
BOS = "<s>"
EOS = "</s>"
def tag_events(tag_seqs: Sequence[Sequence[str]], m: int):
"""Count the predicted events of an order m tag model.
Return (ngram, hist, N). ngram[g] is the count of the tag n-gram g, for
lengths 1 to m + 1, where the last tag of g is a predicted tag (a real
tag or EOS). hist[h] is the number of predicted events whose history ends
with h, for lengths 1 to m. N is the number of predicted events.
"""
ngram: Dict[Tuple[str, ...], int] = {}
hist: Dict[Tuple[str, ...], int] = {}
N = 0
for tags in tag_seqs: # @line L1
seq = [BOS] * m + list(tags) + [EOS]
for i in range(m, len(seq)):
N += 1
for j in range(0, m + 1):
g = tuple(seq[i - j:i + 1])
ngram[g] = ngram.get(g, 0) + 1
if j > 0:
h = g[:-1]
hist[h] = hist.get(h, 0) + 1
return ngram, hist, N
def _ratio(a: int, b: int) -> Fraction:
"""a / b, and 0 when b is 0 (the rule under Brants's Figure 1)."""
return Fraction(0) if b == 0 else Fraction(a, b)
def deleted_interpolation(tag_seqs: Sequence[Sequence[str]], m: int) -> List[Fraction]:
"""Return [lambda_0, ..., lambda_m], the weights of orders 0 to m.
For each (m + 1)-gram g with count c > 0, compare the deleted estimates
(f(g[j:]) - 1) / (hist(g[j:-1]) - 1) for j = 0 .. m (order m - j), and
(f(t) - 1) / (N - 1) for order 0. Add c to the weight of the largest.
"""
ngram, hist, N = tag_events(tag_seqs, m)
lam = [0] * (m + 1)
for g, c in sorted(ngram.items()): # @line L2
if len(g) != m + 1:
continue
best_order, best = -1, Fraction(-1)
for order in range(m, -1, -1): # higher order first: it wins ties
tail = g[m - order:]
if order == 0:
v = _ratio(ngram[tail] - 1, N - 1)
else:
v = _ratio(ngram[tail] - 1, hist[tail[:-1]] - 1)
if v > best:
best_order, best = order, v
lam[best_order] += c
total = sum(lam)
return [Fraction(x, total) for x in lam]
class HMMTagger:
"""A trained tagger. corpus is a list of (words, tags) pairs."""
def __init__(self, corpus: Sequence[Tuple[Sequence[str], Sequence[str]]], m: int = 2,
max_suffix: int = 10, rare: int = 10):
if m < 1:
raise ValueError("the order m must be at least 1")
self.m = m
tag_seqs = [list(t) for _, t in corpus]
self.tags = sorted({t for ts in tag_seqs for t in ts})
self.ngram, self.hist, self.N = tag_events(tag_seqs, m)
self.lam = deleted_interpolation(tag_seqs, m)
self.wt: Dict[Tuple[str, str], int] = {}
self.ft: Dict[str, int] = {}
self.fw: Dict[str, int] = {}
for words, tags in corpus:
if len(words) != len(tags):
raise ValueError("words and tags differ in length")
for w, t in zip(words, tags):
self.wt[(w, t)] = self.wt.get((w, t), 0) + 1
self.ft[t] = self.ft.get(t, 0) + 1
self.fw[w] = self.fw.get(w, 0) + 1
self.max_suffix = max_suffix
self._suffix_init(rare)
# Transition model ------------------------------------------------------
def trans(self, h: Tuple[str, ...], t: str) -> Fraction:
"""P(t | h) = sum_j lambda_j P^(t | last j tags of h), for h of length m."""
p = self.lam[0] * Fraction(self.ngram.get((t,), 0), self.N) # @line L3
for j in range(1, self.m + 1):
ctx = tuple(h[self.m - j:])
p += self.lam[j] * _ratio(self.ngram.get(ctx + (t,), 0), self.hist.get(ctx, 0))
return p
# Emission model --------------------------------------------------------
def _suffix_init(self, rare: int) -> None:
"""Count (suffix, tag) over the tokens of rare words (all words if none is rare)."""
rare_words = {w for w, c in self.fw.items() if c <= rare} or set(self.fw)
self.sfx: Dict[str, Dict[str, int]] = {}
for (w, t), c in sorted(self.wt.items()):
if w not in rare_words:
continue
for i in range(0, min(self.max_suffix, len(w)) + 1):
s = w[len(w) - i:]
row = self.sfx.setdefault(s, {})
row[t] = row.get(t, 0) + c
total = sum(self.ft.values())
ps = [self.ft[t] / total for t in self.tags]
mean = sum(ps) / len(ps)
s = len(ps)
self.theta = math.sqrt(sum((p - mean) ** 2 for p in ps) / (s - 1)) if s > 1 else 1.0
def suffix_dist(self, w: str) -> Dict[str, float]:
"""TnT suffix model: P(t | longest seen suffix of w), at most max_suffix letters."""
row = self.sfx[""]
tot = sum(row.values())
p = {t: row.get(t, 0) / tot for t in self.tags}
for i in range(1, min(self.max_suffix, len(w)) + 1):
row = self.sfx.get(w[len(w) - i:])
if row is None:
break
tot = sum(row.values())
p = {t: (row.get(t, 0) / tot + self.theta * p[t]) / (1 + self.theta) for t in self.tags}
return p
def log_emit(self, w: str, t: str) -> float:
"""log P(w | t) for a known word; log P(t | suffix) / P(t) for an unknown word."""
if w in self.fw: # @line L4
return safe_log(Fraction(self.wt.get((w, t), 0), self.ft[t]))
prior = self.sfx[""]
p0 = prior.get(t, 0) / sum(prior.values())
if p0 == 0:
return NEG_INF
return safe_log(self.suffix_dist(w)[t] / p0)
def log_trans(self, h: Tuple[str, ...], t: str) -> float:
return safe_log(self.trans(h, t))
def tag(self, words: Sequence[str]) -> List[str]:
return viterbi(words, self.tags, self.m, self.log_trans, self.log_emit)[0]
def viterbi(words: Sequence[str], tags: Sequence[str], m: int,
log_trans: Callable[[Tuple[str, ...], str], float],
log_emit: Callable[[str, str], float]):
"""Return (best tags, best log P(x, y)) for an order m HMM.
A state is the tuple of the last m tags; BOS fills the tuple at the start.
log_trans(h, t) is log P(t | h) for a history h of m tags (t may be EOS).
Raises ValueError for an empty sentence or if every tag sequence has
probability 0.
"""
n = len(words)
if n == 0:
raise ValueError("empty sentence")
start = (BOS,) * m
delta = {start: 0.0} # @line L5
back: List[Dict[Tuple[str, ...], Tuple[str, ...]]] = []
lt: Dict[Tuple[Tuple[str, ...], str], float] = {}
def tr(h, t):
key = (h, t)
if key not in lt:
lt[key] = log_trans(h, t)
return lt[key]
for i in range(n): # @line L6
new: Dict[Tuple[str, ...], float] = {}
bp: Dict[Tuple[str, ...], Tuple[str, ...]] = {}
for t in tags:
e = log_emit(words[i], t)
if e == NEG_INF:
continue
for g, s in delta.items(): # @line L7
v = s + tr(g, t) + e
h = g[1:] + (t,)
if h not in new or v > new[h]:
new[h], bp[h] = v, g
delta = new
back.append(bp)
best_h, best = None, NEG_INF
for h, s in delta.items(): # @line L8
v = s + tr(h, EOS)
if best_h is None or v > best:
best_h, best = h, v
if best_h is None or best == NEG_INF:
raise ValueError("every tag sequence has probability 0")
out = []
h = best_h
for i in range(n - 1, -1, -1): # @line L9
out.append(h[-1])
h = back[i][h]
out.reverse()
return out, best # @line L10
def log_joint(words: Sequence[str], ys: Sequence[str], m: int,
log_trans: Callable, log_emit: Callable) -> float:
"""log P(x, y) for one tag sequence, by the product formula (for brute force)."""
h = (BOS,) * m
s = 0.0
for w, t in zip(words, ys):
s += log_trans(h, t) + log_emit(w, t)
h = h[1:] + (t,)
return s + log_trans(h, EOS)
def brute_force(words: Sequence[str], tags: Sequence[str], m: int,
log_trans: Callable, log_emit: Callable):
"""The best tag sequence by listing all k^n of them (first maximum wins)."""
best_y, best = None, NEG_INF
for ys in product(tags, repeat=len(words)):
v = log_joint(words, ys, m, log_trans, log_emit)
if best_y is None or v > best:
best_y, best = list(ys), v
return best_y, best
nlslog.py 152 lines
# SPDX-License-Identifier: MIT
# Shared helper of the natural-language-and-speech pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Log-space arithmetic and semirings for the natural-language-and-speech pages.
Every log is the natural log. A probability of 0 is NEG_INF (float("-inf")),
never a large negative number. A cost is -log p, so a probability of 0 is a
cost of POS_INF.
The semirings are (K, plus, times, zero, one) as on the weighted-automaton page:
PROB probabilities plus = + times = * zero = 0 one = 1
LOG log probabilities plus = log_add times = + zero = -inf one = 0
VITERBI log probabilities plus = max times = + zero = -inf one = 0
TROPICAL costs -log p plus = min times = + zero = +inf one = 0
LOG_COST costs -log p plus = -log_add(-a, -b), times = +, zero = +inf, one = 0
BOOLEAN truth values plus = or times = and zero = False one = True
COUNTING path counts plus = + times = * zero = 0 one = 1
This module holds no algorithm of any page: no forward, Viterbi, CKY, Eisner,
CTC or DTW recursion. The pages build their dynamic programs on top of it.
"""
import math
from dataclasses import dataclass
from typing import Any, Callable, Iterable, List, Sequence
NEG_INF = float("-inf")
POS_INF = float("inf")
def safe_log(p) -> float:
"""Return log p, and NEG_INF for p = 0. Raise ValueError for p < 0."""
if p < 0:
raise ValueError("log of a negative number")
if p == 0:
return NEG_INF
return math.log(p)
def log_add(a: float, b: float) -> float:
"""Return log(exp(a) + exp(b)) = max(a, b) + log(1 + exp(-|a - b|)).
log_add(NEG_INF, NEG_INF) is NEG_INF. No exp of a large number is taken.
"""
if a < b:
a, b = b, a
if b == NEG_INF or a == POS_INF:
return a
return a + math.log1p(math.exp(b - a))
def log_sum(xs: Iterable[float]) -> float:
"""Return log(sum of exp(x)) over xs. An empty input gives NEG_INF."""
xs = list(xs)
if not xs:
return NEG_INF
m = max(xs)
if m == NEG_INF or m == POS_INF:
return m
return m + math.log(math.fsum(math.exp(x - m) for x in xs))
def log_normalize(xs: Sequence[float]) -> List[float]:
"""Return the list x - log_sum(xs): log values whose exps sum to 1.
Raise ValueError if every value is NEG_INF (nothing to normalize).
"""
z = log_sum(xs)
if z == NEG_INF:
raise ValueError("every weight is zero")
return [x - z for x in xs]
def log_softmax(xs: Sequence[float]) -> List[float]:
"""Return log softmax(xs): the logits xs turned into log probabilities."""
return log_normalize(xs)
def softmax(xs: Sequence[float], temperature: float = 1.0) -> List[float]:
"""Return the probabilities exp(x / temperature) / sum, computed stably.
The temperature must be positive. Logits of NEG_INF get probability 0.
"""
if not temperature > 0:
raise ValueError("the temperature must be positive")
m = max(xs)
if m == NEG_INF:
raise ValueError("every logit is -inf")
es = [math.exp((x - m) / temperature) for x in xs]
s = math.fsum(es)
return [e / s for e in es]
def argmax(xs: Sequence[Any]) -> int:
"""Return the first index of a largest value. Raise ValueError if xs is empty."""
if len(xs) == 0:
raise ValueError("argmax of an empty sequence")
best = 0
for i in range(1, len(xs)):
if xs[i] > xs[best]:
best = i
return best
@dataclass(frozen=True)
class Semiring:
"""A semiring (K, plus, times, zero, one). idempotent is True when a plus a = a."""
name: str
plus: Callable[[Any, Any], Any]
times: Callable[[Any, Any], Any]
zero: Any
one: Any
idempotent: bool
def _add(a, b):
return a + b
def _mul(a, b):
return a * b
def _log_add_cost(a: float, b: float) -> float:
return -log_add(-a, -b)
PROB = Semiring("probability", _add, _mul, 0, 1, False)
LOG = Semiring("log", log_add, _add, NEG_INF, 0.0, False)
VITERBI = Semiring("viterbi", max, _add, NEG_INF, 0.0, True)
TROPICAL = Semiring("tropical", min, _add, POS_INF, 0.0, True)
LOG_COST = Semiring("log-cost", _log_add_cost, _add, POS_INF, 0.0, False)
BOOLEAN = Semiring("boolean", lambda a, b: a or b, lambda a, b: a and b, False, True, True)
COUNTING = Semiring("counting", _add, _mul, 0, 1, False)
def sr_sum(sr: Semiring, xs: Iterable[Any]) -> Any:
"""Return the semiring sum of xs, and sr.zero for an empty input."""
acc = sr.zero
for x in xs:
acc = sr.plus(acc, x)
return acc
def sr_prod(sr: Semiring, xs: Iterable[Any]) -> Any:
"""Return the semiring product of xs, and sr.one for an empty input."""
acc = sr.one
for x in xs:
acc = sr.times(acc, x)
return acc
test_hmm_part_of_speech_tagger.py 197 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hmm-part-of-speech-tagger/. The authors are listed in prov/GZMMN9.jsonl.
import math
import random
from fractions import Fraction
from itertools import product
import pytest
from hmm_part_of_speech_tagger import (BOS, EOS, HMMTagger, brute_force, deleted_interpolation,
log_joint, tag_events, viterbi)
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 random_tables(rng, tags, vocab, m):
"""A random order m HMM: rows of positive weights normalized to 1."""
states = list(product([BOS] + list(tags), repeat=m))
trans = {}
for h in states:
ws = [rng.random() + 0.01 for _ in range(len(tags) + 1)]
z = sum(ws)
for t, w in zip(list(tags) + [EOS], ws):
trans[(h, t)] = math.log(w / z)
emit = {}
for t in tags:
ws = [rng.random() + 0.01 for _ in vocab]
z = sum(ws)
for v, w in zip(vocab, ws):
emit[(v, t)] = math.log(w / z)
return (lambda h, t: trans[(h, t)]), (lambda w, t: emit[(w, t)])
@pytest.mark.parametrize("m", [1, 2])
def test_viterbi_matches_brute_force(m):
rng = random.Random(7 + m)
vocab = ["a", "b", "c", "d"]
for k in (1, 2, 3):
tags = ["T%d" % i for i in range(k)]
for n in range(1, 7):
lt, le = random_tables(rng, tags, vocab, m)
words = [rng.choice(vocab) for _ in range(n)]
y, s = viterbi(words, tags, m, lt, le)
yb, sb = brute_force(words, tags, m, lt, le)
assert abs(s - sb) < 1e-9
assert abs(log_joint(words, y, m, lt, le) - s) < 1e-9
if n <= 2:
assert y == yb
def test_viterbi_with_zero_emissions_matches_brute_force():
rng = random.Random(3)
tags = ["A", "B", "C"]
vocab = ["x", "y"]
lt, le0 = random_tables(rng, tags, vocab, 1)
zero = {("x", "B"), ("y", "A")}
def le(w, t):
return -math.inf if (w, t) in zero else le0(w, t)
for n in range(1, 7):
for words in product(vocab, repeat=n):
# Two orders of the same transitions give equal scores in exact
# arithmetic, so compare scores and not the paths themselves.
y, s = viterbi(list(words), tags, 1, lt, le)
yb, sb = brute_force(list(words), tags, 1, lt, le)
assert abs(s - sb) < 1e-9
assert abs(log_joint(list(words), y, 1, lt, le) - s) < 1e-9
def test_tag_events_counts():
ngram, hist, N = tag_events([["D", "N"]], 2)
assert N == 3
assert ngram[(BOS, BOS, "D")] == 1 and ngram[(BOS, "D", "N")] == 1 and ngram[("D", "N", EOS)] == 1
assert ngram[("D",)] == 1 and ngram[(EOS,)] == 1
assert hist[(BOS,)] == 1 and hist[(BOS, BOS)] == 1 and hist[("N",)] == 1 and hist[("D", "N")] == 1
def test_deleted_interpolation_hand_values():
tags = [t for _, t in CORPUS]
assert deleted_interpolation(tags, 1) == [Fraction(4, 19), Fraction(15, 19)]
assert deleted_interpolation(tags, 2) == [Fraction(4, 19), Fraction(4, 19), Fraction(11, 19)]
def test_deleted_interpolation_brute_force():
"""Recompute the weights by deleting one occurrence of each trigram and re-estimating."""
rng = random.Random(11)
for _ in range(30):
seqs = [[rng.choice("ABC") for _ in range(rng.randint(1, 5))] for _ in range(rng.randint(1, 6))]
events = []
for s in seqs:
q = [BOS, BOS] + s + [EOS]
events += [tuple(q[i - 2:i + 1]) for i in range(2, len(q))]
lam = [0, 0, 0]
for g in sorted(set(events)):
c = events.count(g)
rest = list(events)
rest.remove(g)
def est(order):
if order == 0:
return Fraction(sum(1 for e in rest if e[2] == g[2]), len(rest)) if rest else Fraction(0)
tail = g[2 - order:]
den = sum(1 for e in rest if e[2 - order:2] == tail[:-1])
num = sum(1 for e in rest if e[2 - order:] == tail)
return Fraction(num, den) if den else Fraction(0)
vals = [est(o) for o in (2, 1, 0)]
lam[2 - vals.index(max(vals))] += c
assert deleted_interpolation(seqs, 2) == [Fraction(x, sum(lam)) for x in lam]
@pytest.mark.parametrize("m", [1, 2])
def test_transition_rows_sum_to_one(m):
"""A row sums to 1 when every suffix of its history was seen; else it is deficient, as in TnT."""
tagger = HMMTagger(CORPUS, m=m)
full = 0
for h in product([BOS] + tagger.tags, repeat=m):
row = [tagger.trans(h, t) for t in tagger.tags + [EOS]]
assert all(0 <= p <= 1 for p in row)
if all(h[m - j:] in tagger.hist for j in range(1, m + 1)):
assert sum(row) == 1
full += 1
else:
assert sum(row) < 1
assert full >= 4
def test_known_emissions_sum_to_one():
tagger = HMMTagger(CORPUS, m=2)
for t in tagger.tags:
assert sum(Fraction(c, tagger.ft[t]) for (w, u), c in tagger.wt.items() if u == t) == 1
def test_suffix_model_is_a_distribution_and_uses_suffixes():
corpus = [
("he is walking".split(), ["P", "A", "G"]),
("she is talking".split(), ["P", "A", "G"]),
("he was singing".split(), ["P", "A", "G"]),
("the talk".split(), ["D", "N"]),
("the walk".split(), ["D", "N"]),
]
tagger = HMMTagger(corpus, m=2)
for w in ("jumping", "xyz", "ing", "k"):
d = tagger.suffix_dist(w)
assert abs(sum(d.values()) - 1) < 1e-12
assert max(tagger.suffix_dist("jumping").items(), key=lambda kv: kv[1])[0] == "G"
assert tagger.tag("she was jumping".split()) == ["P", "A", "G"]
@pytest.mark.parametrize("m", [1, 2])
def test_trained_tagger_matches_brute_force(m):
tagger = HMMTagger(CORPUS, m=m)
for words in (["the", "dog", "runs"], ["the", "runs"], ["old", "dogs", "run"], ["the", "cat", "runs"]):
y = tagger.tag(words)
yb, _ = brute_force(words, tagger.tags, m, tagger.log_trans, tagger.log_emit)
assert y == yb
def test_trained_tagger_on_training_sentences():
tagger = HMMTagger(CORPUS, m=2)
for words, tags in CORPUS:
assert tagger.tag(words) == tags
def test_underflow():
rng = random.Random(5)
tags = ["A", "B", "C"]
vocab = ["a", "b", "c", "d"]
lt, le = random_tables(rng, tags, vocab, 1)
words = [rng.choice(vocab) for _ in range(400)]
y, s = viterbi(words, tags, 1, lt, le)
p = 1.0
h = (BOS,)
for w, t in zip(words, y):
p *= math.exp(lt(h, t)) * math.exp(le(w, t))
h = (t,)
p *= math.exp(lt(h, EOS))
assert p == 0.0
assert math.isfinite(s) and s < -745
assert abs(log_joint(words, y, 1, lt, le) - s) < 1e-6
def test_errors():
with pytest.raises(ValueError):
viterbi([], ["A"], 1, lambda h, t: 0.0, lambda w, t: 0.0)
with pytest.raises(ValueError):
viterbi(["x"], ["A"], 1, lambda h, t: 0.0, lambda w, t: -math.inf)
with pytest.raises(ValueError):
HMMTagger(CORPUS, m=0)
History
Early taggers used hand-written rules. In 1988 Church published a stochastic parts program and DeRose a statistical tag disambiguator, both with tag sequence probabilities estimated from tagged text and a dynamic programming search. Brants (2000) gave a careful account of the details that most earlier papers left out: the start and end tags, context-independent deleted interpolation, the suffix model of Samuelsson (1993) for unknown words, a capitalization flag and a beam. He cites an independent comparison of seven taggers (Zavrel and Daelemans 1999) in which TnT had the highest accuracy and was also the fastest.
References
- Church 1988, the stochastic parts program with lexical and contextual probabilities estimated from the tagged Brown corpus
- DeRose 1988, tag disambiguation with tag transition probabilities and dynamic programming
- Brants 2000, Section 2.1 and equation 1 (the second-order model with start and end tags), Section 2.2 and Figure 1 (deleted interpolation), Section 2.3 (the suffix model), Section 2.4 (capitalization), Section 2.5 (beam search), Table 5 (Penn Treebank results)
- Christopher D. Manning and Hinrich Schütze, Foundations of Statistical Natural Language Processing, MIT Press, 1999, Chapter 10 (part-of-speech tagging, with Markov model taggers)
Where this leads
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 GZMMN9 Edit this page History Report an error Markdown