Algorithm Search⌘K

Definitionintro

Span-level F1 score

Also called CoNLL F1, exact-match entity F1.

Precision and recall of predicted spans that match a gold span exactly in boundaries and type, combined as their harmonic mean.

The span-level F1 score measures how well a system finds labeled spans, such as the named entities of named entity recognition or the chunks of text chunking. It counts whole spans, not tokens: a predicted span is correct only when a gold span has exactly the same first token, the same last token and the same type. Precision is the share of predicted spans that are correct, recall is the share of gold spans that are found, and F1 is their harmonic mean. The CoNLL-2000 chunking task and the CoNLL-2003 named entity task used this score, computed by their script conlleval over the whole test set, and it is still the standard score for these tasks.

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 type XX. It uses fencepost indices: (i,j,X)(i, j, X) covers the tokens i+1,…,ji + 1, \ldots, j.

Counts. Let GsG_s be the set of gold spans and PsP_s the set of predicted spans of sentence ss. Over a corpus, the counts are summed over the sentences:

TP=∑s∣Gs∩Ps∣,FP=∑s∣Ps∖Gs∣,FN=∑s∣Gs∖Ps∣.\mathrm{TP} = \sum_s |G_s \cap P_s|, \qquad \mathrm{FP} = \sum_s |P_s \setminus G_s|, \qquad \mathrm{FN} = \sum_s |G_s \setminus P_s|.

Scores. Precision is P=TP/(TP+FP)P = \mathrm{TP} / (\mathrm{TP} + \mathrm{FP}), recall is R=TP/(TP+FN)R = \mathrm{TP} / (\mathrm{TP} + \mathrm{FN}), and

F1=2PRP+R=2 TP2 TP+FP+FN(TP>0).F_1 = \frac{2 P R}{P + R} = \frac{2\,\mathrm{TP}}{2\,\mathrm{TP} + \mathrm{FP} + \mathrm{FN}} \quad (\mathrm{TP} > 0).

A ratio with a zero denominator is taken as 0 in the code; state the convention when you report it. Since the counts are summed before the division, this is the micro average: each span counts once, so frequent types weigh more. The general Fβ=(1+β2)PR/(β2P+R)F_\beta = (1 + \beta^2) P R / (\beta^2 P + R) weighs recall β\beta times as much as precision; CoNLL used β=1\beta = 1.

From tags. Taggers output tags, not spans. The CoNLL scripts read the spans from B, I and O tags with one rule (Tjong Kim Sang and Buchholz 2000, page 130): a B-X starts a span, and an I-X also starts a span when it follows O, the start of the sentence or a tag of another type. A span ends before an O, before a tag that starts a span, or at the end of the sentence. With this rule every tag sequence gives a span set, valid or not (see BIO encoding).

  1. SPAN-F1(gold tags, predicted tags of each sentence)
  2. 1read the spans of each tag sequence: B-X, or I-X after O, the start or another type, starts a span
  3. 2a span ends before O, before a tag that starts a span, or at the end of the sentence
  4. 3TP ← Σ over sentences |G_s ∩ P_s| ▷ same i, same j, same type
  5. 4FP ← Σ |P_s| - |G_s ∩ P_s|
  6. 5FN ← Σ |G_s| - |G_s ∩ P_s|
  7. 6P ← TP / (TP + FP), or 0 if no span is predicted
  8. 7R ← TP / (TP + FN), or 0 if there is no gold span
  9. 8F1 ← 2 P R / (P + R), or 0 if P + R = 0

Properties (theorems, from the definition). F1F_1 lies between min⁡(P,R)\min(P, R) and max⁡(P,R)\max(P, R), and it is 1 only when the predicted spans equal the gold spans. A predicted span that overlaps a gold span but has a wrong boundary or a wrong type is one false positive and also one false negative, so a near miss costs more than predicting nothing at that place, which costs only the false negative. TN does not appear: the number of spans a system could have predicted and did not is not counted. The test file checks these facts and the identity F1=2TP/(2TP+FP+FN)F_1 = 2\mathrm{TP} / (2\mathrm{TP} + \mathrm{FP} + \mathrm{FN}) with exact fractions on random span sets, and checks the reading of tags against a second reader that first repairs the tags.

Examples and non-examples

Take the sentence "John Smith works for Acme Corp in Paris" with 8 tokens:

token John Smith works for Acme Corp in Paris
gold B-PER I-PER O O B-ORG I-ORG O B-LOC
predicted B-PER O O O B-ORG I-ORG O B-ORG

The gold spans are (0,2,PER)(0, 2, \mathrm{PER}), (4,6,ORG)(4, 6, \mathrm{ORG}) and (7,8,LOC)(7, 8, \mathrm{LOC}). The predicted spans are (0,1,PER)(0, 1, \mathrm{PER}), (4,6,ORG)(4, 6, \mathrm{ORG}) and (7,8,ORG)(7, 8, \mathrm{ORG}). Only "Acme Corp" matches, so TP = 1, FP = 2 and FN = 2, and P=R=F1=1/3P = R = F_1 = 1/3. The predicted span "John" has the wrong end and "Paris" has the wrong type; each counts once as FP and once as FN. The token accuracy is 6/8=3/46/8 = 3/4, much higher, because the 4 O tokens are easy.

Per type: PER and LOC have F1=0F_1 = 0, and ORG has P=1/2P = 1/2 and R=1R = 1, so F1=2/3F_1 = 2/3. The macro average, the mean of the per-type F1 values, is 2/92/9; it gives each type the same weight, while the micro average 1/31/3 gives each span the same weight.

Tags that are not valid IOB2 still have spans: O I-ORG I-ORG gives the span (1,3,ORG)(1, 3, \mathrm{ORG}), and B-PER I-ORG gives two spans of one token. IOB1 tags are read by the same rule: I-X I-X B-X O gives (0,2,X)(0, 2, X) and (2,3,X)(2, 3, X).

Non-examples:

  • Token-level F1 or accuracy, computed over tags, is not the span score: in the example it gives credit for "John" although the entity "John Smith" was not found.
  • Overlap or partial match scores give credit when a predicted span overlaps a gold span. They are other scores, and a number from them cannot be compared with exact-match F1.
  • Scores on gold spans only, such as the accuracy of typing given entities, measure classification, not finding.
  • Precision and recall: the two ratios, here over spans. A span-level confusion matrix has no true negative cell.
  • BIO encoding: how spans become tags and how invalid tag sequences are read.
  • B-cubed metric: the coreference score that, like span F1, uses precision and recall, but over clusters of mentions.
  • Significance: two systems on the same test set can be compared with a permutation test on sentences, since span F1 is not a mean of independent per-sentence scores.

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.

span_f1_score.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/span-f1-score/. The authors are listed in prov/Q2NAGZ.jsonl.

"""Span-level precision, recall and F1, with exact match of boundaries and type.

A span (i, j, X) uses fencepost indices: it covers the tokens i+1 .. j of the
sentence (0-based tokens i .. j-1) and has the type X. A predicted span is
correct only if a gold span has the same i, the same j and the same X. Counts
are summed over all sentences before the ratios are taken (micro average).
All values are exact Fractions.

bio_to_spans reads B/I/O tags as the CoNLL chunk rules do: a B-X starts a
span; an I-X starts a span when it follows O, the sentence start or a tag of
another type; a span ends before O, before a tag that starts a span, or at the
end of the sentence. This reads valid IOB2 and IOB1 tags, and any other
sequence of O, B-X and I-X tags.
"""

from fractions import Fraction
from typing import Dict, Iterable, List, Optional, Sequence, Set, Tuple

Span = Tuple[int, int, str]


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


def bio_to_spans(tags: Sequence[str]) -> List[Span]:
    spans: List[Span] = []
    start, cur = 0, None
    for p, tag in enumerate(tags):
        prefix, label = split(tag)
        starts = prefix == "B" or (prefix == "I" and label != cur)  # @line L1
        if cur is not None and (prefix == "O" or starts):  # @line L2
            spans.append((start, p, cur))
            cur = None
        if starts:
            start, cur = p, label
    if cur is not None:
        spans.append((start, len(tags), cur))
    return spans


def counts(gold: Iterable[Set[Span]], pred: Iterable[Set[Span]]) -> Tuple[int, int, int]:
    """True positives, false positives and false negatives, summed over the sentences."""
    tp = fp = fn = 0
    for g, p in zip(gold, pred):
        g, p = set(g), set(p)
        hit = len(g & p)  # @line L3
        tp += hit
        fp += len(p) - hit  # @line L4
        fn += len(g) - hit  # @line L5
    return tp, fp, fn


def prf(tp: int, fp: int, fn: int) -> Tuple[Fraction, Fraction, Fraction]:
    """Precision, recall and F1. A ratio with a zero denominator is taken as 0."""
    p = Fraction(tp, tp + fp) if tp + fp else Fraction(0)  # @line L6
    r = Fraction(tp, tp + fn) if tp + fn else Fraction(0)  # @line L7
    f = 2 * p * r / (p + r) if p + r else Fraction(0)  # @line L8
    return p, r, f


def span_f1(gold_tags: Sequence[Sequence[str]], pred_tags: Sequence[Sequence[str]]):
    """Micro-averaged precision, recall and F1 over sentences given as tag sequences."""
    for g, p in zip(gold_tags, pred_tags):
        if len(g) != len(p):
            raise ValueError("gold and predicted sentences differ in length")
    return prf(*counts([set(bio_to_spans(g)) for g in gold_tags], [set(bio_to_spans(p)) for p in pred_tags]))


def per_type(gold: Sequence[Set[Span]], pred: Sequence[Set[Span]]) -> Dict[str, Tuple[Fraction, Fraction, Fraction]]:
    """Precision, recall and F1 for each type separately."""
    types = sorted({x for s in list(gold) + list(pred) for _, _, x in s})
    out = {}
    for x in types:
        g = [{s for s in sent if s[2] == x} for sent in gold]
        p = [{s for s in sent if s[2] == x} for sent in pred]
        out[x] = prf(*counts(g, p))
    return out


def macro_f1(gold: Sequence[Set[Span]], pred: Sequence[Set[Span]]) -> Fraction:
    """The mean of the per-type F1 values."""
    table = per_type(gold, pred)
    return sum((f for _, _, f in table.values()), Fraction(0)) / len(table) if table else Fraction(0)


def token_accuracy(gold_tags: Sequence[Sequence[str]], pred_tags: Sequence[Sequence[str]]) -> Fraction:
    pairs = [(a, b) for g, p in zip(gold_tags, pred_tags) for a, b in zip(g, p)]
    return Fraction(sum(a == b for a, b in pairs), len(pairs))
test_span_f1_score.py 106 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/span-f1-score/. The authors are listed in prov/Q2NAGZ.jsonl.

import random
from fractions import Fraction

from span_f1_score import bio_to_spans, counts, macro_f1, per_type, prf, span_f1, token_accuracy

# The example of the page: John Smith works for Acme Corp in Paris
GOLD = ["B-PER", "I-PER", "O", "O", "B-ORG", "I-ORG", "O", "B-LOC"]
PRED = ["B-PER", "O", "O", "O", "B-ORG", "I-ORG", "O", "B-ORG"]


def test_page_example():
    assert bio_to_spans(GOLD) == [(0, 2, "PER"), (4, 6, "ORG"), (7, 8, "LOC")]
    assert bio_to_spans(PRED) == [(0, 1, "PER"), (4, 6, "ORG"), (7, 8, "ORG")]
    assert counts([set(bio_to_spans(GOLD))], [set(bio_to_spans(PRED))]) == (1, 2, 2)
    assert span_f1([GOLD], [PRED]) == (Fraction(1, 3), Fraction(1, 3), Fraction(1, 3))
    assert token_accuracy([GOLD], [PRED]) == Fraction(3, 4)
    table = per_type([set(bio_to_spans(GOLD))], [set(bio_to_spans(PRED))])
    assert table["PER"] == (0, 0, 0)
    assert table["ORG"] == (Fraction(1, 2), Fraction(1), Fraction(2, 3))
    assert table["LOC"] == (0, 0, 0)
    assert macro_f1([set(bio_to_spans(GOLD))], [set(bio_to_spans(PRED))]) == Fraction(2, 9)


def test_partial_overlap_is_a_false_positive_and_a_false_negative():
    assert counts([{(0, 2, "PER")}], [{(0, 1, "PER")}]) == (0, 1, 1)
    assert counts([{(0, 2, "PER")}], [{(0, 2, "ORG")}]) == (0, 1, 1)
    assert prf(0, 1, 1) == (0, 0, 0)


def test_chunk_rules():
    assert bio_to_spans(["O", "I-X", "I-X"]) == [(1, 3, "X")]  # I-X after O starts a span
    assert bio_to_spans(["B-X", "I-Y"]) == [(0, 1, "X"), (1, 2, "Y")]
    assert bio_to_spans(["I-X", "I-X", "B-X", "O"]) == [(0, 2, "X"), (2, 3, "X")]  # IOB1
    assert bio_to_spans(["B-X", "B-X"]) == [(0, 1, "X"), (1, 2, "X")]
    assert bio_to_spans([]) == [] and bio_to_spans(["O", "O"]) == []


def repair_then_read(tags):
    """An independent reader: first rewrite each I-X that cannot continue a span as B-X, then read runs."""
    fixed = []
    for p, t in enumerate(tags):
        if t.startswith("I-") and (p == 0 or tags[p - 1] == "O" or tags[p - 1][2:] != t[2:]):
            t = "B-" + t[2:]
        fixed.append(t)
    spans, p = [], 0
    while p < len(fixed):
        if fixed[p].startswith("B-"):
            q = p + 1
            while q < len(fixed) and fixed[q] == "I-" + fixed[p][2:]:
                q += 1
            spans.append((p, q, fixed[p][2:]))
            p = q
        else:
            p += 1
    return spans


def test_reader_against_repair():
    rng = random.Random(1)
    alphabet = ["O", "B-X", "I-X", "B-Y", "I-Y"]
    for _ in range(2000):
        tags = [rng.choice(alphabet) for _ in range(rng.randint(0, 8))]
        assert bio_to_spans(tags) == repair_then_read(tags)


def random_spans(rng, n):
    out, i = set(), 0
    while i < n:
        if rng.random() < 0.4:
            j = rng.randint(i + 1, min(n, i + 3))
            out.add((i, j, rng.choice("XY")))
            i = j
        else:
            i += 1
    return out


def test_identities_on_random_data():
    rng = random.Random(2)
    for _ in range(500):
        gold = [random_spans(rng, 8) for _ in range(3)]
        pred = [random_spans(rng, 8) for _ in range(3)]
        tp, fp, fn = counts(gold, pred)
        p, r, f = prf(tp, fp, fn)
        # Brute force over all spans of the corpus, tagged with the sentence number.
        g = {(k,) + s for k, sent in enumerate(gold) for s in sent}
        q = {(k,) + s for k, sent in enumerate(pred) for s in sent}
        assert (tp, fp, fn) == (len(g & q), len(q - g), len(g - q))
        if tp:
            assert f == Fraction(2 * tp, 2 * tp + fp + fn)
            assert f == 1 / ((1 / p + 1 / r) / 2)
            assert min(p, r) <= f <= max(p, r)
        else:
            assert f == 0
        # Micro average: the corpus counts are the sums of the sentence counts.
        parts = [counts([a], [b]) for a, b in zip(gold, pred)]
        assert (tp, fp, fn) == tuple(sum(c[k] for c in parts) for k in range(3))


def test_perfect_and_empty():
    assert span_f1([GOLD], [GOLD]) == (1, 1, 1)
    assert prf(0, 0, 0) == (0, 0, 0)
    assert prf(0, 0, 3) == (0, 0, 0)

References

  1. Tjong Kim Sang and Buchholz 2000, page 130 (the chunk tags, and the rule that an I-X tag after O or after a tag of another type starts a new chunk), and the evaluation by precision, recall and F of the chunks
  2. Tjong Kim Sang and De Meulder 2003, the section on evaluation (a named entity counts as correct only if it matches the gold entity exactly)

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/Q2NAGZ/text.yaml