Algorithm Search⌘K

Definitionintro

BIO encoding

Also called IOB tagging, BIOES encoding.

Encode spans as token tags B for the first token, I for the next ones and O outside, so span finding becomes sequence labeling.

BIO encoding turns a set of labeled, non-overlapping spans of a sentence into one tag per token: B-X on the first token of a span with label X, I-X on the other tokens of the span, and O on the tokens outside every span. With it, finding spans such as noun phrase chunks or named entities becomes sequence labeling, and any tagger can do it. This page defines the encoding, its variants IOB1, IOB2 and BIOES, which tag sequences are valid, and how to repair invalid ones. The tasks that use it are on the pages for text chunking and named entity recognition. A semi-Markov CRF works on the spans directly and does not need the encoding.

Definition

Spans. A sentence has tokens 1,…,n1, \ldots, n. A span is a triple (i,j,X)(i, j, X) with 0≤i<j≤n0 \le i < j \le n and a label XX from a set of LL labels. It uses fencepost indices: (i,j,X)(i, j, X) covers the tokens i+1,…,ji + 1, \ldots, j. A span set is a set of spans that do not overlap. Spans may touch: (0,2,X)(0, 2, X) and (2,3,X)(2, 3, X) are two spans, not one.

IOB2 (also called BIO). The tag of token pp is B-X if pp is the first token of a span with label XX, I-X if pp is another token of such a span, and O if no span covers pp. A tag sequence is valid when every I-X directly follows a B-X or an I-X.

IOB1. Ramshaw and Marcus (1995, Section 4.1) introduced chunk tags with I on every token inside a chunk, O outside, and B only to mark the first token of a chunk that directly follows another chunk. With labels, the tag is B-X on the first token of a span with label XX that starts right where another span with label XX ends, and I-X on every other covered token. A sequence is valid when every B-X directly follows a B-X or an I-X. Tjong Kim Sang and Veenstra (1999) gave the names IOB1 and IOB2, and also defined IOE1 and IOE2, which mark the last token of a span with E instead of the first token with B.

BIOES (also written IOBES, or BILOU with L for last and U for unit). S-X marks a span of one token. A longer span gets B-X on its first token, E-X on its last and I-X in between. A sequence is valid when the tags of each span appear in the order B I ... I E or as one S, with the same label, and O appears only outside spans.

The encoding and the decoding are both one pass from left to right:

  1. ENCODE(spans, n, scheme)
  2. 1tags ← O at every position
  3. 2for each span (i, j, X) in order of i do
  4. 3tags[i+1 .. j] ← I-X
  5. 4IOB2: tags[i+1] ← B-X
  6. 5IOB1: if the previous span ends at i and has label X then tags[i+1] ← B-X
  7. 6BIOES: if j = i+1 then tags[j] ← S-X else tags[i+1] ← B-X; tags[j] ← E-X
  8. 7return tags
  9. REPAIR(tags) ▷ any sequence of O, B-X, I-X becomes valid IOB2
  10. 8for p ← 1 to n do
  11. 9if tags[p] = I-X and (p = 1 or tags[p-1] = O or the label of tags[p-1] is not X) then
  12. 10tags[p] ← B-X ▷ the CoNLL-2000 rule: this I-X starts a chunk
  13. 11return tags

Bijection (a theorem). For each scheme, ENCODE is a bijection from the span sets on nn tokens to the valid tag sequences of length nn, and the decoder is its inverse. In IOB2, a span starts exactly at a B tag and continues over the I tags that follow it with the same label, so the spans can be read back, and a valid sequence has a span at each B. IOB1 keeps the boundaries because B appears exactly where two spans with the same label touch; at any other start of a span the change from O or from another label shows the boundary. BIOES marks both ends. The number of span sets satisfies a0=1a_0 = 1, a1=L+1a_1 = L + 1 and an=(L+2)an−1−an−2a_n = (L + 2) a_{n-1} - a_{n-2}: either token nn is outside every span (an−1a_{n-1} ways), or it ends a span that starts at one of the nn positions with one of LL labels, which gives an=an−1+L(a0+⋯+an−1)a_n = a_{n-1} + L (a_0 + \cdots + a_{n-1}), and the difference of two such lines gives the recurrence. For L=1L = 1 the numbers 1, 2, 5, 13, 34, 89 are every other Fibonacci number. The test file checks the bijection and these counts by enumerating all tag sequences for n≤4n \le 4 with two labels, and the round trip for n≤5n \le 5.

Repair. A tagger that predicts each tag alone can output an invalid IOB2 sequence, such as O I-X. The CoNLL-2000 evaluation reads an I-X that follows O, the sentence start, or a tag with another label as the start of a new chunk (Tjong Kim Sang and Buchholz 2000, page 130). REPAIR rewrites such an I-X as B-X. The result is always valid, a valid sequence does not change, and the only changes are I-X to B-X. Ramshaw and Marcus used the same kind of local repair for their tags: a B right after an O is read as an I (Section 4.1).

Examples and non-examples

The CoNLL-2000 style sentence "He reckons the current account deficit" has the spans (0,1,NP)(0, 1, \mathrm{NP}), (1,2,VP)(1, 2, \mathrm{VP}) and (2,6,NP)(2, 6, \mathrm{NP}):

token He reckons the current account deficit
IOB2 B-NP B-VP B-NP I-NP I-NP I-NP
IOB1 I-NP I-VP I-NP I-NP I-NP I-NP
BIOES S-NP S-VP B-NP I-NP I-NP E-NP

Touching spans with the same label, (0,2,NP)(0, 2, \mathrm{NP}) and (2,3,NP)(2, 3, \mathrm{NP}) on four tokens, give B-NP I-NP B-NP O in IOB2, I-NP I-NP B-NP O in IOB1, and B-NP E-NP S-NP O in BIOES. Without the B, the plain I-NP I-NP I-NP O would read as one span of three tokens: this is why the B tag exists.

Non-examples:

  • O I-X is not valid IOB2, since I-X does not follow a tag with label X. It is valid IOB1. Repair turns it into O B-X.
  • B-X I-Y is not valid IOB2. Repair gives B-X B-Y: two spans of one token.
  • O B-X is not valid IOB1, because IOB1 uses B only right after a span with the same label.
  • B-X alone and B-X O are not valid BIOES, since the span has no E-X.
  • Nested or overlapping spans, such as an entity inside another entity, cannot be encoded at all: each token gets one tag. Use a different method for nested spans.
  • Sequence labeling: the general problem that the encoding reduces span finding to.
  • Text chunking and named entity recognition: the two main tasks that use BIO tags.
  • Constrained decoding: a first-order tagger such as a conditional random field or the BiLSTM-CRF can forbid the invalid transitions (O to I-X, and B-X or I-X to I-Y with Y≠XY \ne X) by giving them a score of −∞-\infty, so the Viterbi algorithm returns only valid sequences.
  • Choice of scheme (a measurement): Tjong Kim Sang and Veenstra (1999, Table 2) found that the choice among IOB1, IOB2, IOE1 and IOE2 changed the F score of their noun phrase chunker by less than one point (88.67 to 89.17 in their first series). BIOES makes both ends of each span explicit, at the cost of twice as many tags per label.
  • Semi-Markov CRF: labels whole spans and needs no token tags.

Code

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.

bio_encoding.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bio-encoding/. The authors are listed in prov/ANKPZQ.jsonl.

"""Convert between labeled spans and token tags in the IOB1, IOB2 (BIO) and BIOES schemes.

A span is (i, j, label) with 0 <= i < j <= n. It covers the tokens i+1 .. j
(fencepost indices), which are the list positions i .. j-1. Spans must not
overlap.

IOB2: B-X on the first token of a span, I-X on the others, O outside.
IOB1: I-X on every token of a span, except B-X on the first token of a span
      that directly follows a span with the same label.
BIOES: S-X for a one-token span; B-X, I-X ... I-X, E-X for longer spans.

decode() accepts only valid tag sequences. repair() turns any sequence of
O, B-X and I-X tags into a valid IOB2 sequence with the rule of the CoNLL-2000
evaluation: an I-X that follows O, the sentence start, or a tag with another
label starts a new span.
"""

from typing import List, Optional, Sequence, Tuple

Span = Tuple[int, int, str]
SCHEMES = ("IOB1", "IOB2", "BIOES")


def split(tag: str) -> Tuple[str, Optional[str]]:
    if tag == "O":
        return "O", None
    prefix, sep, label = tag.partition("-")
    if not sep or prefix not in ("B", "I", "E", "S") or not label:
        raise ValueError("bad tag " + repr(tag))
    return prefix, label


def check_spans(spans: Sequence[Span], n: int) -> List[Span]:
    out = sorted(spans)
    end = 0
    for i, j, _ in out:
        if not (0 <= i < j <= n) or i < end:
            raise ValueError("spans must satisfy 0 <= i < j <= n and must not overlap")
        end = j
    return out


def encode(spans: Sequence[Span], n: int, scheme: str = "IOB2") -> List[str]:
    """Return the n tags of a set of spans."""
    if scheme not in SCHEMES:
        raise ValueError("unknown scheme " + scheme)
    tags = ["O"] * n  # @line L1
    prev_end, prev_label = None, None
    for i, j, x in check_spans(spans, n):  # @line L2
        for p in range(i, j):
            tags[p] = "I-" + x  # @line L3
        if scheme == "IOB2":
            tags[i] = "B-" + x  # @line L4
        elif scheme == "IOB1":
            if prev_end == i and prev_label == x:
                tags[i] = "B-" + x  # @line L5
        else:
            if j - i == 1:
                tags[i] = "S-" + x  # @line L6
            else:
                tags[i], tags[j - 1] = "B-" + x, "E-" + x
        prev_end, prev_label = j, x
    return tags  # @line L7


def decode(tags: Sequence[str], scheme: str = "IOB2") -> List[Span]:
    """Return the spans of a valid tag sequence. Raise ValueError if it is not valid."""
    if scheme not in SCHEMES:
        raise ValueError("unknown scheme " + scheme)
    bioes = scheme == "BIOES"
    spans: List[Span] = []
    start, label = None, None  # the open span, if any

    def close(p):
        nonlocal start, label
        if start is not None:
            if bioes:
                raise ValueError("a BIOES span must end with E-X")
            spans.append((start, p, label))
        start, label = None, None

    for p, tag in enumerate(tags):
        prefix, x = split(tag)
        if prefix in ("E", "S") and not bioes:
            raise ValueError(tag + " is not a tag of " + scheme)
        inside = start is not None and label == x
        if prefix == "O":
            close(p)
        elif prefix == "B":
            if scheme == "IOB1" and not inside:
                raise ValueError("IOB1 uses B-X only right after a span labeled X")
            close(p)
            start, label = p, x
        elif prefix == "S":
            close(p)
            spans.append((p, p + 1, x))
        elif inside:
            if prefix == "E":
                spans.append((start, p + 1, label))
                start, label = None, None
        elif scheme == "IOB1" and prefix == "I":
            close(p)
            start, label = p, x
        else:
            raise ValueError("an inside tag must continue a span with the same label")
    close(len(tags))
    return spans


def repair(tags: Sequence[str]) -> List[str]:
    """Make any sequence of O, B-X and I-X tags valid IOB2, by the CoNLL-2000 rule."""
    out = []
    prev = "O"
    for tag in tags:  # @line L8
        prefix, x = split(tag)
        if prefix not in ("B", "I", "O"):
            raise ValueError("repair takes O, B-X and I-X tags")
        if prefix == "I" and (prev == "O" or split(prev)[1] != x):  # @line L9
            tag = "B-" + x  # @line L10
        out.append(tag)
        prev = tag
    return out  # @line L11


def is_valid(tags: Sequence[str], scheme: str = "IOB2") -> bool:
    try:
        decode(tags, scheme)
    except ValueError:
        return False
    return True


def convert(tags: Sequence[str], source: str, target: str) -> List[str]:
    return encode(decode(tags, source), len(tags), target)
test_bio_encoding.py 98 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bio-encoding/. The authors are listed in prov/ANKPZQ.jsonl.

from itertools import product

import pytest

from bio_encoding import SCHEMES, convert, decode, encode, is_valid, repair

LABELS = ["X", "Y"]


def all_span_sets(n, labels):
    """Every set of non-overlapping labeled spans on n tokens, by brute force."""
    out = []

    def go(p, acc):
        if p == n:
            out.append(list(acc))
            return
        go(p + 1, acc)
        for j in range(p + 1, n + 1):
            for x in labels:
                acc.append((p, j, x))
                go(j, acc)
                acc.pop()

    go(0, [])
    return out


def alphabet(scheme, labels):
    prefixes = "BIES" if scheme == "BIOES" else "BI"
    return ["O"] + [pr + "-" + x for pr in prefixes for x in labels]


def test_round_trip_for_every_span_set():
    for n in range(0, 6):
        sets = all_span_sets(n, LABELS)
        for scheme in SCHEMES:
            seen = set()
            for spans in sets:
                tags = encode(spans, n, scheme)
                assert len(tags) == n
                assert decode(tags, scheme) == sorted(spans)
                seen.add(tuple(tags))
            assert len(seen) == len(sets)


def test_valid_sequences_are_exactly_the_encodings():
    """The encoding is a bijection between span sets and valid tag sequences."""
    for n in range(0, 5):
        count = len(all_span_sets(n, LABELS))
        for scheme in SCHEMES:
            valid = [t for t in product(alphabet(scheme, LABELS), repeat=n) if is_valid(list(t), scheme)]
            assert len(valid) == count
            for t in valid:
                assert encode(decode(list(t), scheme), n, scheme) == list(t)


def test_examples():
    # "He reckons the current account deficit": spans (0,1,NP), (1,2,VP), (2,6,NP)
    spans = [(0, 1, "NP"), (1, 2, "VP"), (2, 6, "NP")]
    assert encode(spans, 6, "IOB2") == ["B-NP", "B-VP", "B-NP", "I-NP", "I-NP", "I-NP"]
    assert encode(spans, 6, "IOB1") == ["I-NP", "I-VP", "I-NP", "I-NP", "I-NP", "I-NP"]
    assert encode(spans, 6, "BIOES") == ["S-NP", "S-VP", "B-NP", "I-NP", "I-NP", "E-NP"]
    adjacent = [(0, 2, "NP"), (2, 3, "NP")]
    assert encode(adjacent, 4, "IOB1") == ["I-NP", "I-NP", "B-NP", "O"]
    assert encode(adjacent, 4, "IOB2") == ["B-NP", "I-NP", "B-NP", "O"]
    assert convert(["I-NP", "I-NP", "B-NP", "O"], "IOB1", "BIOES") == ["B-NP", "E-NP", "S-NP", "O"]


def test_invalid_sequences():
    assert not is_valid(["O", "I-X"], "IOB2")
    assert not is_valid(["B-X", "I-Y"], "IOB2")
    assert is_valid(["O", "I-X"], "IOB1")
    assert not is_valid(["O", "B-X"], "IOB1")
    assert not is_valid(["B-X"], "BIOES")
    assert not is_valid(["B-X", "O"], "BIOES")
    assert not is_valid(["E-X"], "IOB2")
    with pytest.raises(ValueError):
        decode(["Q-X"])
    with pytest.raises(ValueError):
        encode([(0, 2, "X"), (1, 3, "Y")], 3)


def test_repair_follows_conll_rule():
    assert repair(["O", "I-X", "I-X"]) == ["O", "B-X", "I-X"]
    assert repair(["B-X", "I-Y", "I-Y", "I-X"]) == ["B-X", "B-Y", "I-Y", "B-X"]
    for n in range(0, 6):
        for t in product(alphabet("IOB2", LABELS), repeat=n):
            r = repair(list(t))
            assert is_valid(r, "IOB2")
            if is_valid(list(t), "IOB2"):
                assert r == list(t)
            # The repaired sequence keeps every B-X, every O and every label.
            for a, b in zip(t, r):
                assert a == b or (a.startswith("I-") and b == "B-" + a[2:])

References

  1. Ramshaw and Marcus 1995, Section 4.1 (the chunk tags I, O and B, with B only on the first word of a baseNP that directly follows another baseNP, and the local repair of a B after an O), the abstract (about 92% recall and precision for baseNP chunks)
  2. Tjong Kim Sang and Veenstra 1999, Section 2.1 and Table 1 (the formats IOB1, IOB2, IOE1, IOE2, IO and the bracket formats, on one example sentence), Table 2 (the results of each format)
  3. Tjong Kim Sang and Buchholz 2000, page 130 (the chunk tags of the shared task, and the rule that an I-X tag after O or after a tag of another type starts a new chunk)

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
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)
WritingW4 complete
  • a review of the text: no review record reviews/ANKPZQ/text.yaml