Sub topic 2
Entity spans and BIO tags
This chapter assumes you can write basic Python and know what a token is. It also assumes you have a rough idea of what a classifier does. Here you will learn how a named entity, which covers several words, becomes one label per token. Models, training code and evaluation all depend on that conversion.
Entities as character spans
An entity is a span: a contiguous stretch of text with a label. The most precise way to store one is a triple of start character, end character and label. The end offset is exclusive, as in Python slicing.
text = "Ada Lovelace worked in London."
start = text.index("London")
end = start + len("London")
print((start, end, "GPE"), text[start:end])Character offsets do not depend on any tokenizer. Annotation tools usually export them, and spaCy's Span and Hugging Face's start and end fields both use them. The catch is that a model does not see characters. It sees tokens, so offsets must be mapped onto tokens before training and mapped back after prediction.
Two rules hold in most NER datasets:
- Spans do not overlap. "Bank of America" is one ORG, and "America" inside it is not also a GPE.
- Spans do not nest. Some research datasets allow nesting, but the tools in this tutorial do not.
Why tag tokens instead of spans
A token classifier assigns exactly one label to each token. Entity boundaries still have to be encoded in those labels. Suppose you used only the entity type:
Ada PER
Lovelace PER
met O
Charles PER
Babbage PERIf two people sit next to each other with no word between them, you cannot tell where one ends and the next begins. Boundary information has to live in the tags.
The BIO scheme
BIO, also called IOB2, prefixes each label with a position marker:
| Tag | Meaning |
|---|---|
| `B-X` | Beginning of an entity of type X |
| `I-X` | Inside an entity of type X (a continuation) |
| `O` | Outside any entity |
A new entity always starts with B-, so two adjacent entities of the same type are separable.
| Token | Ada | Lovelace | met | Charles | Babbage | in | London | . |
|---|---|---|---|---|---|---|---|---|
| Tag | B-PER | I-PER | O | B-PER | I-PER | O | B-LOC | O |
With K entity types, BIO gives 2K + 1 labels. Four types such as PER, ORG, LOC and MISC give nine tags.
Other schemes you will meet
- IOB1 uses
B-only when two entities of the same type are adjacent. Older CoNLL-2003 files use it. - BILOU (also called BIOES) adds
L-for the last token andU-for a single-token entity (a "unit"). It has 4K + 1 labels. The extra boundary information can help a model, and spaCy uses it internally.
| Scheme | Tags for "Ada Lovelace" (PER) and "London" (LOC) |
|---|---|
| BIO (IOB2) | B-PER I-PER … B-LOC |
| BILOU | B-PER L-PER … U-LOC |
If you load a dataset, check which scheme it uses before you train. Mixing IOB1 and IOB2 silently produces wrong spans.
Converting spans to BIO tags by hand
The function below shows the logic. It takes tokens with their character offsets and a list of spans. Tokens inside a span get B- for the first one and I- for the rest.
import spacy
def spans_to_bio(tokens, spans):
"""tokens: list of (text, start, end); spans: list of (start, end, label)."""
tags = ["O"] * len(tokens)
for s_start, s_end, label in spans:
first = True
for i, (_, t_start, t_end) in enumerate(tokens):
if t_start >= s_start and t_end <= s_end:
tags[i] = ("B-" if first else "I-") + label
first = False
return tags
nlp = spacy.blank("en")
text = "Ada Lovelace worked in London."
doc = nlp.make_doc(text)
tokens = [(t.text, t.idx, t.idx + len(t.text)) for t in doc]
london = text.index("London")
spans = [(0, 12, "PER"), (london, london + 6, "LOC")]
for (word, _, _), tag in zip(tokens, spans_to_bio(tokens, spans)):
print(f"{word:10} {tag}")This prints B-PER, I-PER, O, O, B-LOC and O for the six tokens. The function only tags tokens that fall entirely inside a span. If a span cuts through a token, such as an annotation covering Lovelac only, that token stays O and the entity is partly lost. That is the same alignment problem spaCy reports, described below.
Boundary mismatches
Character offsets and tokenizer boundaries often disagree. Annotators may highlight London in London. or U.K inside U.K., and punctuation or hyphenated words make this worse.
spaCy gives you a tool to check this. doc.char_span returns None when the offsets do not line up with token boundaries:
import spacy
nlp = spacy.blank("en")
doc = nlp.make_doc("Ada Lovelace worked in London.")
print(doc.char_span(0, 12, label="PERSON")) # Ada Lovelace
print(doc.char_span(0, 8, label="PERSON")) # None: ends inside "Lovelace"Always count how many spans return None when you prepare training data. A high count means your annotation tool and tokenizer disagree, and you will lose training signal without any error message.
Tags in spaCy
spaCy stores entities as Span objects in doc.ents, but each token also carries its BIO information. token.ent_iob_ is "B", "I", "O", or an empty string when no entity decision has been made. token.ent_type_ is the label.
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("Apple is looking at buying a U.K. startup for $1 billion.")
for token in doc:
print(f"{token.text:10} {token.ent_iob_:2} {token.ent_type_}")Multi-token entities such as $1 billion show B on the first token and I on the rest. The exact labels depend on the model version.
To convert between character offsets and tags, spaCy provides helpers in spacy.training. These use the BILUO scheme, which is spaCy's name for BILOU:
import spacy
from spacy.training import offsets_to_biluo_tags, biluo_tags_to_offsets
nlp = spacy.blank("en")
text = "Ada Lovelace worked in London."
doc = nlp.make_doc(text)
london = text.index("London")
offsets = [(0, 12, "PERSON"), (london, london + 6, "GPE")]
tags = offsets_to_biluo_tags(doc, offsets)
print(tags) # ['B-PERSON', 'L-PERSON', 'O', 'O', 'U-GPE', 'O']
print(biluo_tags_to_offsets(doc, tags))When a span does not align with tokens, offsets_to_biluo_tags puts - at the affected tokens. That marks them as missing annotation. It does not mean O.
Invalid tag sequences
A token classifier predicts each tag fairly independently. Nothing guarantees a legal sequence. Common illegal outputs in BIO are:
O I-PER: anI-tag with noB-before it.B-PER I-LOC: a type change inside an entity.
Tools handle these differently. Many evaluation libraries treat a stray I-X as the start of an entity. The Hugging Face pipeline's aggregation strategies repair some cases when they merge tokens into entities. Constrained decoding (for example with a CRF layer) forbids illegal transitions, but the plain linear head used in the later chapters does not. When a result looks strange, print the raw tags first.
Entity-level scoring depends on spans
Once tags are decoded into spans, an entity counts as correct only if its type and both boundaries match. The seqeval library scores BIO sequences that way:
from seqeval.metrics import classification_report, f1_score
y_true = [["B-PER", "I-PER", "O", "B-LOC"]]
y_pred = [["B-PER", "I-PER", "O", "O"]]
print(f1_score(y_true, y_pred))
print(classification_report(y_true, y_pred))The model found the person and missed the location. Precision is 1.0, recall is 0.5 and F1 is about 0.67. A token-level accuracy of 75% (three of four tags right) would hide this. A later chapter covers evaluation in depth.
Choosing a scheme in practice
- Use BIO (IOB2) with Hugging Face datasets and
seqeval. This is the default convention there. - Let spaCy handle BILUO conversion for you. You give it character spans and it does the rest.
- Keep character offsets as your source of truth. Re-derive tags whenever you change the tokenizer.
- Never mix schemes across train and test files.
Exercise
Tokenize "Tim Cook met Satya Nadella" as five tokens. Both people are PER. Write the BIO tags. Then explain why the BIO tags for "Tim Cook Satya Nadella" (with "met" removed) are still unambiguous, while tags made only of types (PER PER PER PER) are not.
Show answer
With "met": B-PER I-PER O B-PER I-PER. Without "met": B-PER I-PER B-PER I-PER. The second B-PER marks the start of a new entity, so the boundary between the two people is clear. Type-only tags (PER PER PER PER) cannot show where the first person ends, so you could read them as one four-token entity or as two two-token entities.