Algorithm Search⌘K

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)).

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
Properties
deterministicexactofflineiterative
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 YY with kk tags, an order m≥1m \ge 1, and a sentence x=x1…xnx = x_1 \ldots x_n. Output: a tag sequence y=y1…yny = y_1 \ldots y_n that maximizes the model probability

P(x,y)=∏i=1n+1P(yi∣yi−m,…,yi−1)∏i=1nP(xi∣yi),P(x, y) = \prod_{i=1}^{n+1} P(y_i \mid y_{i-m}, \ldots, y_{i-1}) \prod_{i=1}^{n} P(x_i \mid y_i),

where y1−m=⋯=y0=⟨s⟩y_{1-m} = \cdots = y_0 = \langle s \rangle are start tags and yn+1=⟨/s⟩y_{n+1} = \langle /s \rangle is the end tag. With m=1m = 1 this is the bigram tagger, P(x,y)=∏i=1n+1P(yi∣yi−1)∏i=1nP(xi∣yi)P(x, y) = \prod_{i=1}^{n+1} P(y_i \mid y_{i-1}) \prod_{i=1}^{n} P(x_i \mid y_i). With m=2m = 2 it is the trigram tagger of TnT, whose equation 1 has exactly this form with the end transition P(tT+1∣tT)P(t_{T+1} \mid t_T) at the end. Since P(x)P(x) does not depend on yy, the same yy also maximizes P(y∣x)P(y \mid x). Logs are natural logs.

The algorithm

Training counts the predicted events. A sentence of nn tokens has n+1n + 1 of them: the tags y1,…,yny_1, \ldots, y_n and the end tag, each with its history of mm earlier symbols. Let f(g)f(g) be the count of a tag nn-gram gg whose last symbol is predicted, fh(c)f_h(c) the number of predicted events whose history ends with the context cc, and NN the number of predicted events. The maximum likelihood estimates are P^(t∣c)=f(c t)/fh(c)\hat P(t \mid c) = f(c\,t) / f_h(c) and P^(t)=f(t)/N\hat P(t) = f(t) / N, with 0/0=00/0 = 0. TnT smooths by linear interpolation:

P(t∣h)=λ0P^(t)+λ1P^(t∣yi−1)+⋯+λmP^(t∣yi−m,…,yi−1).P(t \mid h) = \lambda_0 \hat P(t) + \lambda_1 \hat P(t \mid y_{i-1}) + \cdots + \lambda_m \hat P(t \mid y_{i-m}, \ldots, y_{i-1}).

The weights come from deleted interpolation (Brants 2000, Figure 1). Start with all λj=0\lambda_j = 0. For each (m+1)(m+1)-gram gg with count c=f(g)>0c = f(g) > 0, compute the estimate of each order with this one event removed: (f(gj)−1)/(fh(cj)−1)(f(g_j) - 1) / (f_h(c_j) - 1) for the last j+1j + 1 symbols gjg_j of gg with context cjc_j, and (f(t)−1)/(N−1)(f(t) - 1) / (N - 1) for order 0, with a zero denominator giving 0. Add cc 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 P(w∣t)=f(w,t)/f(t)P(w \mid t) = f(w, t) / f(t). 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 P^(t∣ℓ)\hat P(t \mid \ell) for each suffix ℓ\ell of up to 10 letters. Then smooth from the empty suffix to the longest suffix of the word that was seen: P(t∣ℓi)=(P^(t∣ℓi)+θP(t∣ℓi−1))/(1+θ)P(t \mid \ell_i) = (\hat P(t \mid \ell_i) + \theta P(t \mid \ell_{i-1})) / (1 + \theta), where ℓi\ell_i is the suffix of length ii. The emission score is P(t∣ℓ)/P(t)P(t \mid \ell) / P(t), which is P(ℓ∣t)P(\ell \mid t) up to the factor P(ℓ)P(\ell) that is the same for all tags.

  1. HMM-TAG(corpus, x_1 .. x_n, m) ▷ m = 1 bigram, m = 2 trigram (TnT)
  2. 1count 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
  3. 2λ_0 .. λ_m ← DELETED-INTERPOLATION(counts)
  4. 3P(t | h) ← Σ_{j=0..m} λ_j P^(t | last j tags of h)
  5. 4P(w | t) ← f(w, t) / f(t) if w is known, else P(t | suffix of w) / P(t)
  6. 5δ_0(<s> .. <s>) ← 0 ▷ a state is the tuple of the last m tags
  7. 6for i ← 1 to n do
  8. 7for 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
  9. 8h_n ← the first state that maximizes δ_n(h) + log P(</s> | h)
  10. 9for i ← n downto 1 do y_i ← the last tag of h_i; h_{i-1} ← ψ_i(h_i)
  11. 10return 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 e−745e^{-745}. 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 (m=1m = 1) has N=19N = 19 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 λ0=4/19\lambda_0 = 4/19 and λ1=15/19\lambda_1 = 15/19. For example P(N∣D)=419⋅519+1519⋅23=210/361P(N \mid D) = \frac{4}{19} \cdot \frac{5}{19} + \frac{15}{19} \cdot \frac{2}{3} = 210/361, P(V∣D)=419⋅419=16/361P(V \mid D) = \frac{4}{19} \cdot \frac{4}{19} = 16/361, P(D∣⟨s⟩)=183/361P(D \mid \langle s \rangle) = 183/361, P(⟨/s⟩∣N)=77/361P(\langle /s \rangle \mid N) = 77/361 and P(⟨/s⟩∣V)=305/361P(\langle /s \rangle \mid V) = 305/361.

Now tag "the runs". The word "runs" is a verb twice and a noun once, so P(runs∣V)=2/4P(\text{runs} \mid V) = 2/4 and P(runs∣N)=1/5P(\text{runs} \mid N) = 1/5. Only D emits "the", so δ1(D)=log⁡(183/361)\delta_1(D) = \log(183/361). At word 2 only N and V emit "runs":

  • δ2(N)=δ1(D)+log⁡(210/361)+log⁡(1/5)\delta_2(N) = \delta_1(D) + \log(210/361) + \log(1/5), so eδ2(N)≈0.0590e^{\delta_2(N)} \approx 0.0590;
  • δ2(V)=δ1(D)+log⁡(16/361)+log⁡(1/2)\delta_2(V) = \delta_1(D) + \log(16/361) + \log(1/2), so eδ2(V)≈0.0112e^{\delta_2(V)} \approx 0.0112.

With the end transition, D N scores about 0.0590⋅77/361≈0.012580.0590 \cdot 77/361 \approx 0.01258 and D V about 0.0112⋅305/361≈0.009490.0112 \cdot 305/361 \approx 0.00949. 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 knk^n tag sequences.

Correctness

The proof in proofs/correctness.md has two parts. First, after position ii the table holds, for each state of mm 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 P(x,y)P(x, y). 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 m≥1m \ge 1, the tag set YY with kk tags, a sentence x1…xnx_1 \ldots x_n with n≥1n \ge 1, and the two tables of the trained model: P(t∣h)P(t \mid h) for a history hh of mm symbols from Y∪{⟨s⟩}Y \cup \{\langle s \rangle\} and a tag t∈Y∪{⟨/s⟩}t \in Y \cup \{\langle /s \rangle\}, and P(w∣t)P(w \mid t). Write y1−m=⋯=y0=⟨s⟩y_{1-m} = \cdots = y_0 = \langle s \rangle and yn+1=⟨/s⟩y_{n+1} = \langle /s \rangle, and hi=(yi−m+1,…,yi)h_i = (y_{i-m+1}, \ldots, y_i) for the state after position ii. The model gives

log⁡P(x,y)=∑i=1n(log⁡P(yi∣hi−1)+log⁡P(xi∣yi))+log⁡P(⟨/s⟩∣hn),\log P(x, y) = \sum_{i=1}^{n} \bigl( \log P(y_i \mid h_{i-1}) + \log P(x_i \mid y_i) \bigr) + \log P(\langle /s \rangle \mid h_n),

with log⁡0=−∞\log 0 = -\infty and −∞+a=−∞-\infty + a = -\infty.

Claim 1: Viterbi over states of m tags is exact

For 0≤i≤n0 \le i \le n and a state hh, let δi(h)\delta_i(h) be the largest value of the partial sum Si(y1…yi)=∑j=1i(log⁡P(yj∣hj−1)+log⁡P(xj∣yj))S_i(y_1 \ldots y_i) = \sum_{j=1}^{i} (\log P(y_j \mid h_{j-1}) + \log P(x_j \mid y_j)) over the tag prefixes y1…yiy_1 \ldots y_i with hi=hh_i = h, and −∞-\infty if there is none.

Invariant: after the loop of line L6 has run for position ii, the table delta holds δi(h)\delta_i(h) for every state hh with δi(h)>−∞\delta_i(h) > -\infty, and back[i] holds for each such hh a state gg such that a best prefix for hh ends with a best prefix for gg.

Base: line L5 sets δ0(⟨s⟩m)=0\delta_0(\langle s \rangle^m) = 0, the empty sum. No other state has a prefix of length 0.

Step: a prefix y1…yiy_1 \ldots y_i with hi=hh_i = h is a prefix y1…yi−1y_1 \ldots y_{i-1} with some state g=hi−1g = h_{i-1}, followed by the tag t=yit = y_i, and hh is gg with its first symbol dropped and tt appended. Its sum is Si−1(y1…yi−1)+log⁡P(t∣g)+log⁡P(xi∣t)S_{i-1}(y_1 \ldots y_{i-1}) + \log P(t \mid g) + \log P(x_i \mid t). The last two terms depend only on gg and tt, so for a fixed gg the sum is largest when the prefix of length i−1i - 1 is a best prefix for gg. Hence δi(h)=max⁡g(δi−1(g)+log⁡P(t∣g)+log⁡P(xi∣t))\delta_i(h) = \max_g (\delta_{i-1}(g) + \log P(t \mid g) + \log P(x_i \mid t)), where gg ranges over the states whose last m−1m - 1 symbols are the first m−1m - 1 symbols of hh. Line L7 computes this maximum over all states gg in delta and keeps the maximizer. A state gg with δi−1(g)=−∞\delta_{i-1}(g) = -\infty or a tag with log⁡P(xi∣t)=−∞\log P(x_i \mid t) = -\infty is skipped; it can only give −∞-\infty, so the maximum does not change.

By the invariant for i=ni = n, line L8 finds the maximum over hh of δn(h)+log⁡P(⟨/s⟩∣h)\delta_n(h) + \log P(\langle /s \rangle \mid h), which is max⁡ylog⁡P(x,y)\max_y \log P(x, y), because every full sequence is a prefix of length nn 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 f(g)f(g) be the number of predicted events with tag nn-gram gg (line L1) and fh(c)f_h(c) the number of predicted events whose history ends with the context cc. Each predicted event with history ending in cc has exactly one predicted tag, so ∑tf(c t)=fh(c)\sum_t f(c\,t) = f_h(c). Hence for a seen context, the estimate P^(t∣c)=f(c t)/fh(c)\hat P(t \mid c) = f(c\,t) / f_h(c) is nonnegative and sums to 1 over t∈Y∪{⟨/s⟩}t \in Y \cup \{\langle /s \rangle\}. The same holds for the order 0 estimate f(t)/Nf(t) / N, since NN counts all predicted events.

Line L2 adds the count of each (m+1)(m+1)-gram to exactly one weight, so the weights are nonnegative and their sum before normalization is the number of predicted events, N>0N > 0. After normalization they sum to 1. Line L3 forms P(t∣h)=∑j=0mλjP^(t∣cj)P(t \mid h) = \sum_{j=0}^{m} \lambda_j \hat P(t \mid c_j), where cjc_j is the last jj symbols of hh. If every cjc_j was seen in training, this is a convex combination of distributions on the same set, so it is a distribution. If some cjc_j was not seen, its estimate is defined as 0 (the rule under Figure 1 of Brants 2000), and the row sums to 1−∑unseen jλj<11 - \sum_{\text{unseen } j} \lambda_j < 1 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 f(w,t)/f(t)f(w, t) / f(t) of a known word sums to 1 over the words of the lexicon for each tag, because each token tagged tt has one word. The score of an unknown word is P(t∣suffix)/P(t)P(t \mid \text{suffix}) / P(t), which is the inverted suffix probability up to a factor P(suffix)P(\text{suffix}) 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 kmk^m states at each position and kk predecessors of each state that can differ in the first tag, so the time is Θ(nkm+1)\Theta(n k^{m+1}): Θ(nk2)\Theta(n k^2) for the bigram tagger and Θ(nk3)\Theta(n k^3) for the trigram tagger. The back pointers take Θ(nkm)\Theta(n k^m) space. Training reads the corpus once, so it is linear in its size times mm for the nn-gram counts. Deleted interpolation looks at each distinct (m+1)(m+1)-gram once. The suffix model adds up to 10 trie or table lookups per unknown word and O(k)O(k) work for each suffix length. For the 45 tags of the Penn Treebank, k3=91125k^3 = 91125 per word for a full trigram search; this is why TnT adds a beam.

Properties

  • Exact decoding: the Viterbi search finds a maximum of P(x,y)P(x, y) under the model (a theorem, proved above). The tagger is not exact in any stronger sense: its accuracy is a measurement.
  • Generative: it models P(x,y)P(x, y) 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 m=2m = 2; Brants reports that the second-order model with careful smoothing matches the maximum entropy tagger of Ratnaparkhi (1996).
  • Context-dependent weights. One set of λ\lambda 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 θ=1000\theta = 1000; 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 P(⟨/s⟩∣h)P(\langle /s \rangle \mid h) 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 λ0>0\lambda_0 > 0.
  • Unseen histories: with the TnT rule 0/0=00/0 = 0, 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 θ\theta 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 kk near 50, the state space has k2k^2 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.

hmm_part_of_speech_tagger.pyI0RawGitHub
# 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

  1. Church 1988, the stochastic parts program with lexical and contextual probabilities estimated from the tagged Brown corpus
  2. DeRose 1988, tag disambiguation with tag transition probabilities and dynamic programming
  3. 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)
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example