By Sagi Shaier · 7 November 2026 · 10 min read
Named entity recognition and part-of-speech tagging: token classification explained
How a model tags the part of speech of every token and how BIO tags turn token labels into named entities, with a bidirectional RNN as one example built and scored in PyTorch.
Token classification gives a label to every token in a text instead of one label to the whole text. Part-of-speech tagging uses it to mark each word as a noun, verb, adjective and so on. Named entity recognition uses it to find names of people, companies and places. That is how a tool can redact names from a contract or index support tickets by product.
Language models work with tokens, which are whole words or pieces of words. Most examples in this post use one token per word to keep them simple, and one section covers what happens when a word is split into pieces.
One label per token
A text classifier reads "Sarah lives in Boston" and returns one label for the sentence, such as travel. A token classifier returns one label per token: Sarah gets B-PER, lives gets O, in gets O and Boston gets B-LOC. If the model reads five tokens, it returns five labels.

The tags in that example follow a scheme called BIO. B- marks the first token of a name, I- marks a later token inside the same name and O marks a token outside any name. The part after the dash is the type, so B-PER starts a person and B-LOC starts a location. The section on named entity recognition comes back to BIO in detail.
The output shape
A text classifier squeezes the whole text into one vector and scores the labels once. A token classifier keeps one vector per token and scores the labels at every position. With a batch of $B$ texts padded to $T$ tokens each, the encoder returns one hidden vector of size $d_h$ per token, so its output has shape $B \times T \times d_h$. The same linear layer is applied at every position $t$:
$$z_t = W h_t + b$$
$h_t$ is the hidden vector at position $t$, $W$ is a weight matrix with one row per tag and $b$ is a bias vector. The tag scores $z_t$ are called logits. With $C$ tags the logits have shape $B \times T \times C$, one score per tag at every position of every text.

nn.RNN in PyTorch returns two things. output holds the hidden state at every position and hn holds only the final hidden state. A text classifier feeds hn[-1] to its head. A token classifier feeds output, and the linear layer changes only the last dimension.
Part-of-speech tagging
Part-of-speech tagging (POS tagging) gives every token a grammatical category such as noun, verb, adjective or pronoun. A common tag list is Universal POS, which has 17 tags such as NOUN, VERB and ADJ. A few are less obvious: DET is a determiner such as "the", ADP is an adposition such as "in" and AUX is an auxiliary verb such as "is".
The same word can need different tags. In "She books a flight online", books is a verb. In "I love books about history", books is a noun. The tag depends on the words around it, so the model needs to see the context on both sides of each token.

POS tags help a search system treat nouns and verbs differently, help a grammar checker notice verb forms that disagree with nearby words, and help a parser decide how words attach to each other. Modern neural models often learn these patterns internally, so POS tagging is less visible in products than it used to be. It still shows the token classification pattern cleanly: one hidden vector and one tag distribution at every position.
A bidirectional tagger
Any encoder that returns one vector per token can feed the tag head, such as an LSTM or a transformer, and this post uses a bidirectional RNN as one example.
An RNN that reads left to right has only seen the tokens before position $t$. To tag books in "She books flights", the word "flights" after it helps too. A bidirectional RNN runs one pass forward and one pass backward and joins the two hidden states at every position:
$$h_t = [\overrightarrow{h_t} ; \overleftarrow{h_t}]$$
$\overrightarrow{h_t}$ carries the tokens up to $t$ and $\overleftarrow{h_t}$ carries the tokens after $t$. Joining them doubles the size of each hidden vector, so the linear head takes hidden_size * 2 inputs.

Training and predicting tags in PyTorch
Training uses cross-entropy at every real token, the negative log of the probability the model gave the correct tag. Sentences in a batch have different lengths, so the shorter ones are padded. The tag of every padding position is set to -100, and F.cross_entropy(..., ignore_index=-100) skips those positions. The code builds the tagger, trains one step on two sentences and predicts the tags of the first one:
1import torch
2import torch.nn as nn
3import torch.nn.functional as F
4
5torch.manual_seed(0)
6
7class POSTagger(nn.Module):
8 def __init__(self, vocab_size, emb_dim, hidden_size, num_tags):
9 super().__init__()
10 self.emb = nn.Embedding(vocab_size, emb_dim, padding_idx=0)
11 self.rnn = nn.RNN(emb_dim, hidden_size, batch_first=True, bidirectional=True)
12 self.head = nn.Linear(hidden_size * 2, num_tags)
13
14 def forward(self, input_ids):
15 output, hn = self.rnn(self.emb(input_ids)) # output: (batch, seq_len, hidden_size * 2)
16 return self.head(output) # (batch, seq_len, num_tags)
17
18vocab = {"<pad>": 0, "she": 1, "books": 2, "flights": 3, "the": 4, "are": 5, "heavy": 6}
19tag_names = ["PRON", "VERB", "NOUN", "DET", "AUX", "ADJ"]
20num_tags = len(tag_names)
21
22sentences = [["she", "books", "flights"], ["the", "books", "are", "heavy"]]
23tags = [["PRON", "VERB", "NOUN"], ["DET", "NOUN", "AUX", "ADJ"]]
24max_len = 4
25input_ids = torch.tensor([[vocab[w] for w in s] + [0] * (max_len - len(s)) for s in sentences])
26tag_ids = torch.tensor([[tag_names.index(t) for t in ts] + [-100] * (max_len - len(ts)) for ts in tags])
27print(tag_ids)
28
29model = POSTagger(len(vocab), emb_dim=16, hidden_size=32, num_tags=num_tags)
30optimizer = torch.optim.Adam(model.parameters(), lr=1e-2)
31
32logits = model(input_ids)
33print(logits.shape)
34loss = F.cross_entropy(logits.view(-1, num_tags), tag_ids.view(-1), ignore_index=-100)
35optimizer.zero_grad()
36loss.backward()
37optimizer.step()
38print(f"loss {loss.item():.3f}")
39
40model.eval()
41with torch.no_grad():
42 pred_ids = model(input_ids).argmax(dim=-1) # (batch, seq_len)
43print([tag_names[i] for i in pred_ids[0, :3]])1tensor([[ 0, 1, 2, -100],
2 [ 3, 2, 4, 5]])
3torch.Size([2, 4, 6])
4loss 1.686
5['PRON', 'VERB', 'NOUN']The logits have shape (2, 4, 6): two sentences, four positions and six tags. F.cross_entropy expects one row of scores per example, so view(-1, num_tags) turns the 8 token positions into 8 rows and tag_ids.view(-1) lines up the 8 target tags. The padded fourth position of the first sentence has the tag -100 and adds nothing to the loss. At prediction time the argmax over the last dimension picks the highest-scoring tag at each position, and the padding positions are dropped. After one step on these two sentences the model tags "she books flights" correctly, which says nothing yet about new sentences.
If you set bidirectional=True and keep nn.Linear(hidden_size, num_tags), PyTorch raises RuntimeError: mat1 and mat2 shapes cannot be multiplied, because each hidden vector is now twice as wide as the head expects.
POS taggers are usually scored by token accuracy, the share of real tokens with the correct tag. That works here because every token has a grammatical tag. Per-tag precision and recall are still worth checking for rare tags, and a confusion matrix shows common mix-ups such as NOUN versus PROPN (proper noun) or AUX versus VERB.
Named entity recognition
Named entity recognition, or NER, finds spans of text that name real things and gives each span a type. Common types are person (PER), organization (ORG) and location (LOC). Datasets often add more types such as dates, money amounts or products. In "Jordan signed with Nike in Chicago", the spans are Jordan as PER, Nike as ORG and Chicago as LOC.

Capital letters alone are not enough to find names. A name can span several tokens, such as "New York City". The type of a name can depend on the sentence around it, and not every capitalized phrase is a named entity.
BIO tags turn spans into token labels
The model outputs one label per token, while NER is judged on whole spans. BIO tags connect the two. For "New York City hired Ada Lovelace" the tags are B-LOC I-LOC I-LOC O B-PER I-PER. Reading them back gives two spans: tokens 0 to 3 as LOC and tokens 4 to 6 as PER, where the end index is exclusive. With the types PER, ORG and LOC there are 7 tags: O plus a B- and an I- tag for each type, so the head has 7 outputs.

The NER model has the same shape as the POS tagger, with BIO tags in place of grammar tags. The extra step comes after the argmax: the tag sequence has to be decoded into spans. Each position is scored on its own, so the argmax can return a sequence that breaks the BIO rules. O I-LOC I-LOC has no B-LOC to open the span, and in B-PER I-ORG the type changes in the middle of a span. The decoder below follows one rule for both cases: a stray I- with no open span gives no span, and a type change closes the span that was open. An extra "O" at the end closes a span that is still open on the last token.
1def decode_bio(tags):
2 spans = []
3 start = None
4 ent_type = None
5 for i, tag in enumerate(tags + ["O"]):
6 if tag.startswith("B-"):
7 if start is not None:
8 spans.append((start, i, ent_type))
9 start = i
10 ent_type = tag[2:]
11 elif tag == "O" or (tag.startswith("I-") and tag[2:] != ent_type):
12 if start is not None:
13 spans.append((start, i, ent_type))
14 start = None
15 ent_type = None
16 return spans
17
18print(decode_bio(["B-LOC", "I-LOC", "I-LOC", "O", "B-PER", "I-PER"]))
19print(decode_bio(["O", "I-LOC", "I-LOC"]))
20print(decode_bio(["B-PER", "I-ORG"]))1[(0, 3, 'LOC'), (4, 6, 'PER')]
2[]
3[(0, 1, 'PER')]tag[2:] drops the first two characters, so B-PER gives PER. The first call recovers New York City and Ada Lovelace. The second returns no span because no B- tag opens one. The third keeps B-PER as a one-token person and drops the mismatched I-ORG.
Labels for word pieces
NER datasets are usually labeled per word, while tokenizers can split a rare word into pieces. Kalamazoo might become Kal, ##ama and ##zoo, where ## marks a piece that continues the word before it. A common rule keeps the word's label on the first piece and gives the later pieces -100, so the loss ignores them. Padding positions also get -100. Hugging Face tokenizers have a word_ids() method that says which original word each token position came from, which is what the alignment code uses.

Scoring NER by spans
A predicted span counts as correct only when its start, its end and its type all match a gold span, the span marked in the labeled data. Predicting New York as LOC when the gold span is New York City is wrong, and so is predicting Jordan as LOC when the gold label is PER.

Token accuracy can look good while NER quality is poor, because most tokens are O and easy to get right. The code below scores the "boundary short" mistake both ways:
1gold_tags = ["B-LOC", "I-LOC", "I-LOC", "O", "B-PER", "I-PER"]
2pred_tags = ["B-LOC", "I-LOC", "O", "O", "B-PER", "I-PER"]
3
4token_acc = sum(g == p for g, p in zip(gold_tags, pred_tags)) / len(gold_tags)
5
6gold = {(0, 3, "LOC"), (4, 6, "PER")} # New York City, Ada Lovelace
7pred = {(0, 2, "LOC"), (4, 6, "PER")} # New York, Ada Lovelace
8
9correct = len(gold & pred)
10precision = correct / len(pred)
11recall = correct / len(gold)
12f1 = 2 * precision * recall / (precision + recall)
13print(f"token accuracy {token_acc:.2f}")
14print(f"span precision {precision:.2f} recall {recall:.2f} F1 {f1:.2f}")1token accuracy 0.83
2span precision 0.50 recall 0.50 F1 0.50One wrong tag out of six gives a token accuracy of 0.83. At the span level, precision is the share of predicted spans that are exact matches, which is 0.50 here. Recall is the share of gold spans the model found, also 0.50. The shortened New York span counts against both. F1 combines the two into 0.50. Reporting scores per type helps too, since a model can find PER names well and miss long ORG names.
Chunking
Chunking is a third token classification task. It groups neighboring tokens into flat phrases such as noun phrases (NP), verb phrases (VP) and prepositional phrases (PP), with the same BIO scheme: "The quick fox jumped over the fence" becomes B-NP I-NP I-NP B-VP B-PP B-NP I-NP. The chunks do not overlap or nest, which separates chunking from full parsing.
Common mistakes
- Feeding the final hidden state to a token head.
hn[-1]is one vector per sentence. A token classifier needsoutput, one vector per position. - Widening the encoder and not the head. A bidirectional RNN doubles the hidden size, so the head needs
hidden_size * 2inputs. - Forgetting
-100on padding and later word pieces. Those positions then train the model toward made-up tags. - Scoring NER by token accuracy. Report span-level precision, recall and F1, plus scores per entity type.
- Assuming argmax returns valid BIO. Decode with a rule for stray
I-tags and type changes.
Related concepts
Text classification returns one label for a whole text, and natural language inference returns one label for a pair of texts. Recurrent neural networks covers the RNN encoder and bidirectional RNNs in more depth. Word pieces such as ##ama come from subword tokenizers, covered in BPE vs WordPiece vs Unigram.
QuiddityML teaches token classification, POS tagging and NER as three concepts in the NLP tasks unit of its NLP track. The exercises include filling in the bidirectional POS tagger, spotting the bug in its head, putting the lines of decode_bio in order and writing it from scratch (QuiddityML).