Part-of-speech tagging: decide what a word is doing here
词性标注
Build a first-order HMM tagger, derive exact sequence decoding and token posteriors, and test unknown words, sentence boundaries and evaluation choices.
part-of-speechThe same spelling can have a different job
In the invented sentences a fish swims and they fish, the spelling fish stays the same. In the first sentence it names the thing swimming; in the second it describes what the people do. Part-of-speech tagging assigns a grammatical category to each token in its context. Looking up one permanent label per spelling misses this distinction.
The input is a token sequence, such as [they, fish]; the output has the same length, such as [PRON, VERB]. Token boundaries and the label inventory are part of the task. Our four teaching labels are DET, NOUN, PRON and VERB. They deliberately merge auxiliaries and lexical verbs into VERB. They are not a claim that a real annotation scheme needs only four categories. Read tokenization first if the distinction between text and tokens is unfamiliar.
A useful baseline assigns each known word its most frequent training label and an unseen word the most frequent label overall. It is cheap, auditable and often reveals whether a more complicated tagger is doing anything useful. It cannot make fish change labels between these two contexts. A sequence model can use both the word and plausible transitions between labels. TnT is a statistical example of this approach; it uses second-order transitions. Here we begin with a smaller first-order hidden Markov model, HMM. TnT, model description
The labels are “hidden” when tagging a new sentence, even though they are supplied during supervised training. This article explains both the best complete label sequence and uncertainty at individual positions. Neither output gives an infallible grammatical judgment: it is a prediction under a particular model and annotation policy.
Score a complete sentence, including its end
Define the events before counting them
Let w_1,…,w_n be observed tokens and t_1,…,t_n labels from a set of size K. Write B for the beginning marker and E for the ending marker. Define a_ij as the probability of going from label i to label j, and b_j(w) as the probability of emitting word w from label j. We allow transitions from B to a label or E, and from a label to another label or E. No transition enters B and E emits no word.
The first-order assumption says the next label depends only on the preceding label. The emission assumption says a word depends only on its current label. Under these assumptions the joint probability is:
This is our explicit first-order formulation. TnT conditions each label on two preceding labels and includes a final boundary factor; the inspected NLTK first-order implementation instead terminates its Viterbi path by maximizing the final state score without our EOS factor. Boundary conventions are part of the model, not interchangeable punctuation. TnT, equation 1 Pinned NLTK implementation
For an empty sentence, define the joint mass to be a_BE. For nonempty input we abbreviate the sum over all K^n label paths as Z(w). This is the probability of the observed token sequence ending at this position under our model; it is not a free parameter or a sum over possible words.
The conditional distribution requires Z(w)>0. If all paths have zero probability, the model has no conditional answer for that sentence. Returning an arbitrary first label would hide that failure.
Estimate tables without looking at the test set
Count training transitions C_ij, including B→first and last→E separately for every sentence. Count label–word emissions C_jw after constructing the vocabulary from training data. An empty training sentence contributes B→E and no emission. With a nonnegative smoothing value α, and V vocabulary entries including UNK, use:
The first denominator has K+1 possible destinations, not K: ending a sentence is an event. With α=0 these are maximum-likelihood estimates for rows with observations. Every learned label in this implementation has observed emissions and an outgoing transition. With α>0 all allowed entries are positive; the model eventually ends with probability one because this finite table gives every label a positive ending probability. An arbitrary user-supplied stochastic table need not have that property if it permits a closed non-ending class.
The default α=0.5 is a teaching choice, not a tuned recommendation. NLTK’s supervised path collects starting-state, transition and emission frequencies and lets an estimator control smoothing; TnT uses interpolation and a more elaborate unknown-word treatment. Our additive table estimates do not reproduce those choices. NLTK, supervised training TnT, estimation and smoothing
Choose a minimum training count before mapping rare words to the reserved UNK entry. At test time an unseen spelling uses that same entry. UNK represents a mapped vocabulary class; b_j(UNK) is not an equal probability assigned separately to infinitely many spellings. Case is preserved. Adding test words to the vocabulary would change V and the smoothing denominators, so even an apparently harmless vocabulary update would change the model.
Viterbi chooses one whole path
Let D_i(j) be the greatest log joint score for the first i tokens among paths ending in label j. Two prefixes ending in the same label have exactly the same possible future factors under the first-order assumptions. The lower-scoring prefix can therefore be discarded. Initialize and extend:
Store the maximizing predecessor at each cell, then choose the last label using the ending factor and follow the stored pointers backward:
Zero probabilities become negative infinity. Log space avoids repeated multiplication of tiny probabilities. Equal scores use the first index in the program’s sorted label order; that deterministic tie rule is not linguistic evidence. The pinned NLTK routine illustrates the same predecessor-table idea, with the boundary difference described above. NLTK, Viterbi routine
Forward–backward keeps all paths
Replace the maximum by a sum of probability mass to obtain the forward log score F. The stable log-sum-exp operation is:
When every input is negative infinity, LSE is negative infinity; the ordinary shifted formula would subtract infinity from itself. Our code handles that case explicitly. The forward recurrence and evidence are:
Let R_i(j) be the log probability of the remaining words and the ending event after position i, given current label j. Then:
Combining the prefix and suffix and dividing by the evidence gives a posterior for each position:
These distributions sum to one across labels at each position, up to floating-point error. Choosing each position’s posterior mode maximizes expected token accuracy under the model; it need not maximize the probability of a complete path. It can even combine transitions that have zero probability. Viterbi answers the complete-path question. The forward/backward routines in NLTK are another implementation reference, using their own boundary and logarithm conventions. NLTK, forward and backward routines
A result small enough to audit by hand
Use labels N,V and emissions over UNK,x,y. The transition columns below are N,V,E; the emission columns are UNK,x,y.
| Row | Transition | Emission |
|---|---|---|
| B | 0.4, 0.4, 0.2 | none |
| N | 0.2, 0.6, 0.2 | 0.1, 0.6, 0.3 |
| V | 0.6, 0.1, 0.3 | 0.2, 0.2, 0.6 |
For input x y, the four joint path masses are NN=0.00288, NV=0.02592, VN=0.00288 and VV=0.00144. For example NV is 0.4×0.6×0.6×0.6×0.3. Their sum is 0.03312=207/6250. The best path is NV, with mass 81/3125 and conditional probability 18/23. The first-position posterior is [20/23,3/23]; the second is [4/23,19/23]. Dividing a best-path score by the evidence is different from reporting that score itself.
Run the complete small tagger
Save the following as pos.py and run python pos.py in Python 3.12.4 with NumPy 1.26.4 installed. It needs no corpus download. The six training sentences and three queries are invented and fully specified in demo. In they can fish, the training annotation uses the unusual but possible reading “they put fish into cans”: can is VERB and fish is NOUN. The separate query they fish uses fish as VERB. Without an explicit intended reading, a supposedly gold example could itself be ambiguous.
The program uses one (K+1)×(K+1) transition array. Index K denotes B when it is a row and E when it is a column; there is no extra trainable B-emission or outgoing E row. The implementation shares storage for boundary roles, not their meaning. Its normalization first scales each row by its maximum, avoiding overflow when α is extremely large. This is mathematically the same row normalization for finite positive rows, subject to floating-point precision.
"""Original first-order POS HMM with train-only vocabulary, EOS and exact decoding.
This is not TnT: no trigram interpolation, suffix model or beam pruning.
Tokenization and gold tags are supplied explicitly. Toy VERB merges auxiliaries
and lexical verbs; 'they can fish' is annotated with the canning reading. NumPy is the only dependency.
"""
from collections import Counter,defaultdict
import json,math
import numpy as np
UNK='<UNK>'
def token(value):
if not isinstance(value,str) or not value or value==UNK or any(c.isspace() or 0xD800<=ord(c)<=0xDFFF for c in value):
raise ValueError('Nonempty token without whitespace, surrogates or reserved UNK required')
return value
def fit(sentences,alpha=.5,min_count=1):
if isinstance(alpha,bool) or not isinstance(alpha,(int,float)) or not math.isfinite(alpha) or alpha<0:raise ValueError('Finite nonnegative smoothing required')
if type(min_count) is not int or min_count<1:raise ValueError('Positive minimum count required')
if not isinstance(sentences,(list,tuple)) or not sentences:raise ValueError('Labeled sentence collection required')
rows=[]
for sentence in sentences:
if not isinstance(sentence,(list,tuple)):raise ValueError('A sentence is a sequence of word/tag pairs')
row=[]
for pair in sentence:
if not isinstance(pair,(list,tuple)) or len(pair)!=2:raise ValueError('Word/tag pair required')
row.append((token(pair[0]),token(pair[1])))
rows.append(row)
frequencies=Counter(w for row in rows for w,_ in row);tag_counts=Counter(t for row in rows for _,t in row)
if not frequencies:raise ValueError('At least one labeled token required')
vocabulary=[UNK]+sorted(w for w,count in frequencies.items() if count>=min_count)
tags=sorted(tag_counts);word_id={w:i for i,w in enumerate(vocabulary)};tag_id={t:i for i,t in enumerate(tags)}
k=len(tags);transitions=np.full((k+1,k+1),alpha);emissions=np.full((k,len(vocabulary)),alpha)
by_word=defaultdict(Counter)
for row in rows:
previous=k
for word,tag in row:
current=tag_id[tag];transitions[previous,current]+=1;emissions[current,word_id.get(word,0)]+=1
by_word[word][tag]+=1;previous=current
transitions[previous,k]+=1
def winner(counts):return min(counts,key=lambda t:(-counts[t],t))
def normalized(table):
scaled=table/table.max(axis=1,keepdims=True)
return scaled/scaled.sum(axis=1,keepdims=True)
return {'tags':tags,'vocabulary':vocabulary,'transition':normalized(transitions),
'emission':normalized(emissions),'word_majority':{w:winner(c) for w,c in by_word.items()},
'default_tag':winner(tag_counts),'alpha':float(alpha),'min_count':min_count}
def checked(model,words):
if not isinstance(words,(list,tuple)):raise ValueError('Pretokenized sentence required')
words=[token(w) for w in words];tags=model['tags'];vocab=model['vocabulary'];k=len(tags)
if not k or len(set(tags))!=k or not vocab or vocab[0]!=UNK or len(set(vocab))!=len(vocab):raise ValueError('Unique tags and vocabulary with leading UNK required')
a=np.asarray(model['transition'],dtype=float);b=np.asarray(model['emission'],dtype=float)
if a.shape!=(k+1,k+1) or b.shape!=(k,len(vocab)):raise ValueError('HMM table dimensions disagree')
for table in [a,b]:
if not np.isfinite(table).all() or np.any(table<0) or not np.allclose(table.sum(axis=1),1,rtol=0,atol=1e-12):raise ValueError('Stochastic nonnegative tables required')
index={w:i for i,w in enumerate(vocab)}
with np.errstate(divide='ignore'):return np.log(a),np.log(b),[index.get(w,0) for w in words]
def logsumexp(values):
values=np.asarray(values,dtype=float)
if np.isnan(values).any() or np.isposinf(values).any():raise ValueError('Invalid log scores')
maximum=float(np.max(values))
return -math.inf if maximum==-math.inf else maximum+math.log(float(np.exp(values-maximum).sum()))
def log_joint(model,words,tags):
a,b,ids=checked(model,words);k=len(model['tags']);lookup={t:i for i,t in enumerate(model['tags'])}
if not isinstance(tags,(list,tuple)) or len(tags)!=len(ids) or any(t not in lookup for t in tags):raise ValueError('One known tag per token required')
previous=k;score=0.
for word,tag in zip(ids,tags):
current=lookup[tag];score+=a[previous,current]+b[current,word];previous=current
return float(score+a[previous,k])
def decode(model,words):
a,b,ids=checked(model,words);k=len(model['tags']);n=len(ids)
if not n:
value=float(a[k,k]);return {'status':'ok' if math.isfinite(value) else 'impossible','tags':[],
'log_joint':value if math.isfinite(value) else None,'log_evidence':value if math.isfinite(value) else None,'posteriors':[],'oov_positions':[]}
forward=np.empty((n,k));best=np.empty((n,k));back=np.zeros((n,k),dtype=int)
forward[0]=best[0]=a[k,:k]+b[:,ids[0]]
for i in range(1,n):
for j in range(k):
forward[i,j]=logsumexp(forward[i-1]+a[:k,j])+b[j,ids[i]]
scores=best[i-1]+a[:k,j];back[i,j]=int(np.argmax(scores));best[i,j]=scores[back[i,j]]+b[j,ids[i]]
evidence=logsumexp(forward[-1]+a[:k,k]);last=int(np.argmax(best[-1]+a[:k,k]));score=float(best[-1,last]+a[last,k])
oov=[i for i,word in enumerate(words) if word not in model['vocabulary']]
if not math.isfinite(evidence):return {'status':'impossible','tags':None,'log_joint':None,'log_evidence':None,'posteriors':None,'oov_positions':oov}
path=[last]
for i in range(n-1,0,-1):path.append(int(back[i,path[-1]]))
path.reverse();backward=np.empty((n,k));backward[-1]=a[:k,k]
for i in range(n-2,-1,-1):
for j in range(k):backward[i,j]=logsumexp(a[j,:k]+b[:,ids[i+1]]+backward[i+1])
post=np.exp(forward+backward-evidence)
return {'status':'ok','tags':[model['tags'][j] for j in path],'log_joint':score,'log_evidence':evidence,
'posteriors':post.tolist(),'oov_positions':oov}
def majority(model,words):
checked(model,words)
return [model['word_majority'].get(w,model['default_tag']) for w in words]
def accuracy(gold,predicted):
if len(gold)!=len(predicted):raise ValueError('Aligned sentences required')
correct=total=exact=0
for g,p in zip(gold,predicted):
if p is None or len(g)!=len(p):raise ValueError('Aligned predicted tags required')
correct+=sum(a==b for a,b in zip(g,p));total+=len(g);exact+=g==p
return {'tokens':total,'correct':correct,'token_accuracy':correct/total if total else None,
'sentences':len(gold),'exact_sentences':exact,'sentence_accuracy':exact/len(gold) if gold else None}
def demo():
training=[[('they','PRON'),('can','VERB'),('fish','NOUN')],[('a','DET'),('can','NOUN'),('rusts','VERB')],
[('fish','NOUN'),('swim','VERB')],[('they','PRON'),('fish','VERB')],[('a','DET'),('fish','NOUN'),('swims','VERB')],
[('can','VERB'),('they','PRON'),('fish','VERB')]]
model=fit(training);queries=[['they','fish'],['a','can'],['they','jump']]
gold=[['PRON','VERB'],['DET','NOUN'],['PRON','VERB']]
decoded=[decode(model,q) for q in queries];baseline=[majority(model,q) for q in queries]
rare=fit(training,min_count=2)
return {'training':training,'tags':model['tags'],'vocabulary':model['vocabulary'],'transition':model['transition'].tolist(),
'emission':model['emission'].tolist(),'queries':queries,'gold':gold,'decoded':decoded,'majority':baseline,
'hmm_accuracy':accuracy(gold,[d['tags'] for d in decoded]),'majority_accuracy':accuracy(gold,baseline),
'rare_vocabulary':rare['vocabulary'],'rare_unk_emissions':rare['emission'][:,0].tolist(),
'unsmoothed_unknown':decode(fit(training,alpha=0),['jump']),
'scope':'Original small first-order POS HMM, fixed train-only vocabulary with UNK and explicit EOS. Dense tables, exact log-space Viterbi/forward-backward; not TnT trigram/suffix/beam implementation or a treebank accuracy benchmark.'}
if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=False,indent=2,allow_nan=False))
The HMM gets 6/6 query labels and 3/3 complete query sentences correct against the supplied answers. The word-majority baseline gets 4/6 labels and 1/3 sentences. These overlapping, hand-written examples illustrate behavior; they are not a held-out estimate of accuracy. In particular jump is absent from training, and smoothing allows the context to favor VERB. With α=0, jump has zero emission probability under every label, and the output explicitly reports impossible.
With minimum count two, the vocabulary is [UNK, a, can, fish, they]; rare training words teach the UNK emission class instead of disappearing. Change the threshold, re-fit from the same training data, and inspect the UNK emission row contributions before checking predictions.
For a sentence of n tokens and K labels, dense Viterbi and forward–backward each take O(nK²) time. The stored tables and pointers take O(nK) space, excluding O(K²+KV) model storage. A forward pass that only needs evidence can retain two rows and use O(K) working space. Exact second-order decoding would instead keep label pairs as states, typically taking O(nK³) dense time and O(nK²) stored states; this is a consequence of the enlarged state, not a benchmark claim about TnT’s optimized implementation.
What the labeler cannot decide for you
The model sees no word suffixes, characters, embeddings or long-distance dependency beyond its one-label transition. An unseen proper name and an unseen verb both map to UNK; only their sequence context distinguishes them here. TnT’s suffix treatment addresses information this example omits. Richer contextual encoders can condition on much more text, and a conditional sequence model can use features without this HMM’s emission assumptions. Those are method choices, not an automatic guarantee of improvement on a new corpus. TnT, unknown-word discussion
Label policy and tokenization must be fixed before evaluation. A system that splits one token into two cannot be scored by silently zipping its labels against the old list. Report token accuracy and whole-sentence accuracy with their denominators; longer sentences provide more chances to make at least one error. Our scorer rejects length mismatches and returns null for a rate with no denominator. Its treatment of an aligned empty sentence as an exact sentence match is explicit in the implementation.
For a real comparison, keep train, validation and test sentences separate; fix the vocabulary and smoothing choices using only the allowed training/validation data. Report known-word and unknown-word accuracy, common label confusions, tokenization policy, corpus domain and label inventory. Inspect disputed annotations separately from model errors. A high posterior is confidence under the assumed tables, not evidence that the model is calibrated on another domain.
Part-of-speech tagging does not identify entity boundaries, word senses or complete syntax. Named entity recognition and dependency parsing ask different questions about the same sentence.
Check the modeling decisions
- Understanding. Why can the word-majority baseline not assign different labels to the two occurrences of
fishina fish swimsandthey fish?
Answer: Its prediction depends only on the word’s training counts. Both occurrences use the same table entry. A sequence model adds label-context factors, allowing the same emission word to participate in different best paths.
- Hand calculation. In the two-label table above, what is the conditional probability of the NV path for
x y, and how does it differ from the joint mass?
Answer: Divide 0.02592 by 0.03312 to obtain 18/23. The numerator is the joint mass of words, tags and ending; conditioning on the observed words and ending normalizes across the four paths. The evidence is not one merely because a conditional distribution will be normalized.
- Boundary case. A one-token sentence has prefix scores P(B→N,x)=0.6 and P(B→V,x)=0.15. Ending probabilities are 0.01 and 0.9. Which label wins with and without the ending factor? What happens if every complete path has zero mass?
Answer: Without EOS, N wins. With EOS, compare 0.006 and 0.135, so V wins. A zero-mass sentence has undefined conditional tag probabilities; the tagger should report that model failure rather than let an arbitrary tie-breaking label masquerade as a prediction.
- Transfer. A medical test corpus contains many unseen terms. A colleague proposes adding its vocabulary before computing smoothing tables. What would you do instead, and what would you measure?
Answer: Keep the evaluation protocol fixed: learn the vocabulary and UNK mapping from training data and tune thresholds on validation data. Adding test vocabulary changes denominators and uses test information. Measure known/unknown token accuracy and label confusions separately, then test a character/suffix-aware alternative under the same split. An explicitly transductive setup could allow unlabeled test vocabulary, but it must be declared and compared on that basis.
Read the assumptions as carefully as the recurrence
Thorsten Brants’s 2000 TnT paper explains a second-order statistical tagger, estimation, smoothing and unknown-word treatment. The methods and boundary discussion support the comparisons here; no paper benchmark is reproduced by the six-sentence program. TnT
The NLTK reference is pinned to commit fce04f99cadcc8cf93312b5f8336f5098d40890e, dated 2026-09-04. The inspected ranges cover the cached Viterbi path, forward/backward recurrences and supervised counts. They do not certify its unsupervised training, every probability class or all corpus integrations. This article’s code is an original teaching implementation and does not execute NLTK. Pinned source
The accompanying checks independently enumerate small paths, verify the displayed fractions, exercise sentence boundaries, empty input, unknown words and long-sequence underflow, and compare dense dynamic-programming marginals with direct conditional sums. These checks establish the stated numerical behaviors, not grammatical competence on a treebank.
Make a prediction, then check
One-token prefix scores for N and V are 0.6 and 0.15; their end probabilities are 0.01 and 0.9. Which tag wins with EOS?
Learning objectives
- Define tokenization, label inventory and a word-majority baseline.
- Derive an HMM path probability with explicit start and end events.
- Distinguish Viterbi paths from forward–backward token posteriors.
- Evaluate unknown words and token/sentence accuracy without test-vocabulary leakage.
Prerequisites & connections
Explore related knowledge →References
- TnT — A Statistical Part-of-Speech Tagger
Thorsten Brants · 2000 - NLTK HMM tagger, pinned implementation
NLTK contributors · 2026
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-12 · Codex single-AI-author technical check: scoped TnT model/estimation and pinned NLTK HMM; nine paired equations and four explained exercises. First-order additive teaching model with BOS/EOS differs from TnT second-order interpolation. Exact path enumeration, Viterbi, evidence and token posteriors, UNK training-only vocabulary, end-event reversal, finite boundaries and stated dense costs. Synthetic accuracy is not a corpus benchmark; no human peer review.
- Codex single-AI-author technical check: scoped TnT model/estimation and pinned NLTK HMM; nine paired equations and four explained exercises. First-order additive teaching model with BOS/EOS differs from TnT second-order interpolation. Exact path enumeration, Viterbi, evidence and token posteriors, UNK training-only vocabulary, end-event reversal, finite boundaries and stated dense costs. Synthetic accuracy is not a corpus benchmark; no human peer review.
- Four original SVGs bind the exact MDX program. Nine figure tests validate numeric results, encodings and dependency arc geometry. Thirty standalone language/width cases and four fallback fonts passed; ten desktop/mobile screenshots were actually inspected. The original false arc crossing and its correction evidence are preserved. Complete article browser acceptance is separate; no human peer review or upstream execution.
Source locations checked:
- TnT — A Statistical Part-of-Speech Tagger · Scoped model/estimation/smoothing text45–137; physical page1 inspected. Second-order labels, emissions and EOS; unknown-word opening only. No benchmark reproduction.
- NLTK HMM tagger, pinned implementation · Commit fce04f99cadcc8cf93312b5f8336f5098d40890e, September4. Read386–428,707–780,1070–1130: Viterbi, forward/backward and supervised counts; no EOS factor in this Viterbi terminal choice. No upstream execution or full-package audit.
Related topics