Algorithm Search⌘K

Definitionadvanced

B-cubed metric

Also called B3 coreference score.

Coreference precision and recall averaged over mentions, from the overlap of the predicted and gold clusters that hold each mention.

The B-cubed metric scores a coreference resolution system by asking, for each mention, how much the system's cluster of that mention agrees with the gold cluster of that mention. Bagga and Baldwin (1998) proposed it because the earlier MUC score counts only links and cannot tell a small merge error from a large one. B-cubed (B3 for short) is one of the three scores whose mean is the CoNLL coreference score, with MUC and CEAF-e. It is defined on partitions of the same set of mentions; with mentions found by the system the two sides cover different mentions, and the reference scorer of Pradhan et al. (2014) fixes how to extend it.

Definition

Let MM be a set of NN mentions. The key K\mathcal{K} is the gold partition of MM into entities, and the response R\mathcal{R} is the system's partition of the same MM. For a mention mm, let K(m)K(m) be the key cluster and R(m)R(m) the response cluster that contain mm. The precision and recall of the mention are

P(m)=∣K(m)∩R(m)∣∣R(m)∣,Rec(m)=∣K(m)∩R(m)∣∣K(m)∣.P(m) = \frac{|K(m) \cap R(m)|}{|R(m)|}, \qquad \mathrm{Rec}(m) = \frac{|K(m) \cap R(m)|}{|K(m)|}.

B-cubed precision and recall are the averages over mentions, P=1N∑mP(m)P = \frac{1}{N} \sum_m P(m) and Rec=1N∑mRec(m)\mathrm{Rec} = \frac{1}{N} \sum_m \mathrm{Rec}(m), and F1=2P⋅Rec/(P+Rec)F_1 = 2 P \cdot \mathrm{Rec} / (P + \mathrm{Rec}). Bagga and Baldwin allow a weight per mention in place of 1/N1/N; the equal weights are the usual choice and the one the code uses.

  1. B-CUBED(key K, response R over the same mentions)
  2. 1for each mention m do
  3. 2c ← |K(m) ∩ R(m)|
  4. 3P ← P + c / |R(m)|
  5. 4Rec ← Rec + c / |K(m)|
  6. 5P ← P / N, Rec ← Rec / N
  7. 6return P, Rec, and F1 = 2 P Rec / (P + Rec)

Grouping the mentions by the pair of clusters that holds them gives the same values as a sum over cells: P=1N∑K∈K∑S∈R∣K∩S∣2/∣S∣P = \frac{1}{N} \sum_{K \in \mathcal{K}} \sum_{S \in \mathcal{R}} |K \cap S|^2 / |S|, and the same with ∣K∣|K| for recall. So B-cubed costs O(N)O(N) time with a hash map from mentions to clusters.

Properties (theorems, from the definition). Every P(m)P(m) and Rec(m)\mathrm{Rec}(m) is positive, because mm itself is in both clusters, so PP and RR are above 0. Swapping key and response swaps precision and recall. F1=1F_1 = 1 exactly when the response equals the key. A response of all singletons has precision 1, and a response of one cluster has recall 1. The test file checks these facts and the cell formula with exact fractions on random partitions.

For contrast, the MUC score of Vilain et al. (1995) counts links: its recall is ∑K(∣K∣−∣p(K)∣)/∑K(∣K∣−1)\sum_{K} (|K| - |p(K)|) / \sum_K (|K| - 1), where p(K)p(K) is the set of parts that the response cuts KK into, and precision swaps the roles. CEAF (Luo 2005) aligns key and response entities one to one with the best total similarity, an assignment problem solved by the Hungarian algorithm; CEAF-e uses the similarity 2∣K∩S∣/(∣K∣+∣S∣)2 |K \cap S| / (|K| + |S|). The CoNLL score is the mean of the MUC, B-cubed and CEAF-e F1 values.

Examples and non-examples

The example of Bagga and Baldwin (1998) has 12 mentions and the key {1,…,5}\{1, \ldots, 5\}, {6,7}\{6, 7\}, {8,9,A,B,C}\{8, 9, A, B, C\}. Two responses each make one merge:

response MUC P MUC R B3 P B3 R
merge {6,7}\{6, 7\} into {8,…,C}\{8, \ldots, C\} 9/10 1 16/21 ≈ 0.762 1
merge {1,…,5}\{1, \ldots, 5\} with {8,…,C}\{8, \ldots, C\} 9/10 1 7/12 ≈ 0.583 1

For the first response, the 5 mentions of {1,…,5}\{1, \ldots, 5\} have precision 1, mentions 6 and 7 have 2/72/7, and the 5 others have 5/75/7; the mean is (5+4/7+25/7)/12=16/21(5 + 4/7 + 25/7)/12 = 16/21. In the second, 10 mentions have precision 5/105/10 and 2 have 1, so the mean is 7/127/12. MUC gives the same 9/10 to both, since each response has one wrong link; B-cubed says that joining two large entities is the worse error.

The extremes show what each score rewards. With the same key:

response MUC P, R, F1 B3 P, R, F1
all 12 singletons 0, 0, 0 1, 1/4, 2/5
one cluster of all 12 9/11, 1, 9/10 3/8, 1, 6/11

MUC gives a high score to the single cluster and nothing to the singletons. B-cubed is milder in both directions, and it gives a lot of precision credit to singletons, which is why scores on data with many singleton mentions look high.

Non-examples:

  • Mention-level accuracy (the share of mentions given the right antecedent) is not B-cubed: it depends on which antecedent was chosen, while B-cubed sees only the clusters.
  • Pairwise F1, over all pairs of mentions placed in the same cluster, is a different score; it weighs large clusters quadratically.
  • B-cubed on key and response with different mention sets is not defined by the formula above: a mention found only by the system has no key cluster. Reference scorers add such mentions as singletons or remove them; report which.
  • Span F1 score: precision, recall and F1 for finding mentions or entities as spans, which is the step before clustering.
  • MUC and CEAF: the other two scores of the CoNLL average. MUC ignores singletons, CEAF-e counts each entity once through the alignment.
  • Partitions: the number of possible responses on NN mentions is the Bell number (see Bell numbers), so a score cannot be maximized by trying them all except for tiny NN.
  • Mention-pair model and span-ranking model: the systems usually scored with these metrics.

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.

b_cubed_metric.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/b-cubed-metric/. The authors are listed in prov/3YEMMH.jsonl.

"""The B-cubed coreference score (Bagga and Baldwin 1998), and the MUC score for contrast.

A clustering is a list of clusters, each a collection of mention ids; the key
(gold) and the response (system) clusterings must cover the same mentions,
each mention exactly once. All values are exact Fractions.

B-cubed: for each mention m, let K(m) be its key cluster and R(m) its response
cluster. Its precision is |K(m) & R(m)| / |R(m)| and its recall is
|K(m) & R(m)| / |K(m)|. The score averages these over the mentions, with equal
weights, and F is the harmonic mean of the two averages.

MUC (Vilain et al. 1995): recall is the sum over key clusters K of
|K| - |p(K)|, divided by the sum of |K| - 1, where p(K) is the set of parts
that the response cuts K into. Precision swaps the roles of key and response.
"""

from fractions import Fraction
from typing import Dict, Hashable, Iterable, List, Sequence, Tuple

Clustering = Sequence[Iterable[Hashable]]


def index(clusters: Clustering) -> Tuple[List[frozenset], Dict[Hashable, int]]:
    """The clusters as frozensets, and the cluster number of each mention."""
    sets = [frozenset(c) for c in clusters]
    where: Dict[Hashable, int] = {}
    for k, c in enumerate(sets):
        if not c:
            raise ValueError("empty cluster")
        for m in c:
            if m in where:
                raise ValueError("mention in two clusters: %r" % (m,))
            where[m] = k
    return sets, where


def _check(key: Clustering, response: Clustering):
    ks, kw = index(key)
    rs, rw = index(response)
    if set(kw) != set(rw):
        raise ValueError("key and response must cover the same mentions")
    return ks, kw, rs, rw


def harmonic(p: Fraction, r: Fraction) -> Fraction:
    return 2 * p * r / (p + r) if p + r else Fraction(0)


def b_cubed(key: Clustering, response: Clustering) -> Tuple[Fraction, Fraction, Fraction]:
    """B-cubed precision, recall and F1, each mention with weight 1/N."""
    ks, kw, rs, rw = _check(key, response)
    n = len(kw)
    if n == 0:
        return Fraction(0), Fraction(0), Fraction(0)
    p = r = Fraction(0)
    for m in kw:  # @line L1
        k, s = ks[kw[m]], rs[rw[m]]
        both = len(k & s)  # @line L2
        p += Fraction(both, len(s))  # @line L3
        r += Fraction(both, len(k))  # @line L4
    p, r = p / n, r / n  # @line L5
    return p, r, harmonic(p, r)  # @line L6


def _muc_recall(ks: List[frozenset], rw: Dict[Hashable, int]) -> Fraction:
    num = den = 0
    for k in ks:
        parts = {rw[m] for m in k}
        num += len(k) - len(parts)
        den += len(k) - 1
    return Fraction(num, den) if den else Fraction(0)


def muc(key: Clustering, response: Clustering) -> Tuple[Fraction, Fraction, Fraction]:
    """MUC precision, recall and F1 (a ratio with a zero denominator is taken as 0)."""
    ks, kw, rs, rw = _check(key, response)
    r = _muc_recall(ks, rw)
    p = _muc_recall(rs, kw)
    return p, r, harmonic(p, r)
test_b_cubed_metric.py 83 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/b-cubed-metric/. The authors are listed in prov/3YEMMH.jsonl.

import random
from fractions import Fraction

import pytest

from b_cubed_metric import b_cubed, muc

# The example of Bagga and Baldwin (1998): mentions 1..12, with A, B, C written as 10, 11, 12.
KEY = [[1, 2, 3, 4, 5], [6, 7], [8, 9, 10, 11, 12]]
MERGE_SMALL = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11, 12]]
MERGE_LARGE = [[1, 2, 3, 4, 5, 8, 9, 10, 11, 12], [6, 7]]
SINGLETONS = [[m] for m in range(1, 13)]
ONE = [list(range(1, 13))]


def test_bagga_baldwin_example():
    assert b_cubed(KEY, MERGE_SMALL)[:2] == (Fraction(16, 21), Fraction(1))
    assert b_cubed(KEY, MERGE_LARGE)[:2] == (Fraction(7, 12), Fraction(1))
    # MUC cannot tell the two errors apart.
    assert muc(KEY, MERGE_SMALL) == muc(KEY, MERGE_LARGE)
    assert muc(KEY, MERGE_SMALL)[:2] == (Fraction(9, 10), Fraction(1))


def test_extreme_responses():
    assert b_cubed(KEY, SINGLETONS) == (Fraction(1), Fraction(1, 4), Fraction(2, 5))
    assert b_cubed(KEY, ONE) == (Fraction(3, 8), Fraction(1), Fraction(6, 11))
    assert muc(KEY, SINGLETONS) == (0, 0, 0)
    assert muc(KEY, ONE) == (Fraction(9, 11), Fraction(1), Fraction(9, 10))
    assert b_cubed(KEY, KEY) == (1, 1, 1) and muc(KEY, KEY) == (1, 1, 1)


def test_bad_input():
    with pytest.raises(ValueError):
        b_cubed([[1, 2]], [[1]])
    with pytest.raises(ValueError):
        b_cubed([[1, 2]], [[1, 2], [2]])


def random_partition(rng, items):
    labels = {m: rng.randrange(len(items)) for m in items}
    groups = {}
    for m, g in labels.items():
        groups.setdefault(g, []).append(m)
    return list(groups.values())


def test_identities_on_random_partitions():
    rng = random.Random(1)
    for _ in range(500):
        n = rng.randint(1, 9)
        items = list(range(n))
        key, resp = random_partition(rng, items), random_partition(rng, items)
        p, r, f = b_cubed(key, resp)
        # The sum over pairs of clusters: precision = sum |K & R|^2 / |R|, over N.
        cells = [(len(set(k) & set(s)), len(k), len(s)) for k in key for s in resp]
        assert p == sum(Fraction(c * c, b) for c, a, b in cells) / n
        assert r == sum(Fraction(c * c, a) for c, a, b in cells) / n
        # Swapping key and response swaps precision and recall.
        assert b_cubed(resp, key)[:2] == (r, p)
        assert 0 < p <= 1 and 0 < r <= 1
        same = sorted(map(sorted, key)) == sorted(map(sorted, resp))
        assert (f == 1) == same
        # MUC recall from the meet: (N - cells of the meet) / (N - key clusters).
        meet = sum(1 for c, a, b in cells if c)
        mp, mr, mf = muc(key, resp)
        assert mr == (Fraction(n - meet, n - len(key)) if n > len(key) else 0)
        assert mp == (Fraction(n - meet, n - len(resp)) if n > len(resp) else 0)


def test_b_cubed_brute_force_per_mention():
    rng = random.Random(2)
    for _ in range(300):
        items = list(range(rng.randint(1, 8)))
        key, resp = random_partition(rng, items), random_partition(rng, items)
        kc = {m: set(c) for c in key for m in c}
        rc = {m: set(c) for c in resp for m in c}
        # Count, for each mention, the mentions that share both clusters, one by one.
        p = sum(Fraction(sum(1 for x in rc[m] if x in kc[m]), len(rc[m])) for m in items) / len(items)
        r = sum(Fraction(sum(1 for x in kc[m] if x in rc[m]), len(kc[m])) for m in items) / len(items)
        assert b_cubed(key, resp)[:2] == (p, r)

References

  1. Bagga and Baldwin 1998, the critique of the MUC score, the B-cubed definition with weights per mention, and the example with key clusters of 5, 2 and 5 mentions
  2. Vilain et al. 1995, the MUC link-based recall and precision
  3. Luo 2005, the CEAF metric and its comparison with MUC and B-cubed
  4. Sameer Pradhan, Xiaoqiang Luo, Marta Recasens, Eduard Hovy, Vincent Ng and Michael Strube, Scoring coreference partitions of predicted mentions: a reference implementation, ACL 2014, pages 30 to 35, the definitions of MUC, B-cubed and CEAF as implemented in the reference scorer, and their extension to predicted mentions

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