AI Wiki中文/EN

Coreference resolution: which mentions name the same entity?

共指消解

Derive antecedent probabilities and marginal training, inspect a clustering counterexample, and compare three evaluation measures.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Different phrases can point to the same person

In the invented passage Mina called Jo. The caller waited, Mina and the caller refer to the same person. They are two mentions: text spans that refer to an entity. Coreference resolution groups mentions that refer to the same entity. Detecting a person name is a different task, and identical spelling is not sufficient evidence: two people may share a name.

A mention can be a pronoun, a name or a longer noun phrase. Identity also differs from a related-object relation: a car and its wheels are associated but do not denote the same object. Pronoun interpretation can require speaker context; a bound pronoun in Every researcher checked her notes does not simply name one fixed person. This article uses within-document entity identity; richer anaphora and event coreference need their own annotation contracts.

An antecedent model asks each mention to choose an earlier mention or a dummy option. Connecting the chosen links produces clusters. In Lee and colleagues’ end-to-end model, candidates are spans rather than a separately supplied list of known mentions. Here we supply the mention list so that inference, learning and evaluation remain inspectable. Task and model, §§3–4

A best antecedent forest and a most probable grouping can disagree. The six possible forests, summed group probabilities and three split scores come from the supplied-mention example.
A best antecedent forest and a most probable grouping can disagree. The six possible forests, summed group probabilities and three split scores come from the supplied-mention example.

Normalize links, then understand the resulting clusters

Scores with a dummy alternative

Order n candidate mentions by their text positions. For mention i, allowed antecedents are earlier indices and dummy epsilon. Dummy may represent a new entity or a span that is not an entity mention; the link alone does not distinguish those cases. Our program retains every supplied mention, including singleton clusters, and does not implement mention detection.

Lee et al. add the current mention score, antecedent mention score and a pair score. Dummy has fixed score0. A best real score above0 beats it; in our code a tie goes to dummy because it is listed first. Scoring architecture Pinned author implementation

s(i,j)={0,j=ϵ,sm(i)+sm(j)+sa(i,j),j<i.s(i,j)=\begin{cases}0,&j=\epsilon,\\s_m(i)+s_m(j)+s_a(i,j),&j<i.\end{cases}

With allowed set A_i, apply softmax separately to each mention. For fixed document-derived scores, these distributions define a normalized distribution over antecedent configurations:

P(yi=j∣D)=es(i,j)∑k∈Aies(i,k),P(y∣D)=∏i=0n−1P(yi∣D).P(y_i=j\mid D)=\frac{e^{s(i,j)}}{\sum_{k\in A_i}e^{s(i,k)}}, \qquad P(\mathbf y\mid D)=\prod_{i=0}^{n-1}P(y_i\mid D).

The factorization is a modeling assumption, not a claim that language decisions are independent. Earlier-only links prevent cycles. Connected components recover entity groups; choosing each row’s best antecedent yields the most likely link forest under this model.

Training data usually supplies clusters, not one mandatory antecedent per mention. Let G_i be the available earlier mentions in i’s gold cluster. If none remain, or i is not a gold mention, use only dummy. The loss sums the negative log probability of this correct set:

L=−∑ilog⁡∑j∈GiP(yi=j∣D).\mathcal L=-\sum_i\log\sum_{j\in G_i}P(y_i=j\mid D).

Compute it as a difference of log-sum-exp terms, rather than summing tiny probabilities and taking log0. The pinned code implements that difference and sums losses across mentions. It invokes custom operations for pruning and gold labels; we inspected the call sites, not those operations’ internals. Learning, §6 Loss implementation

For a real or dummy logit, the derivative subtracts a distribution restricted to correct choices. A free mention score accumulates gradients from every real link in which that mention participates; dummy remains fixed.

∂L∂s(i,j)=pij−1[j∈Gi]pij∑k∈Gipik.\frac{\partial\mathcal L}{\partial s(i,j)}=p_{ij}-\mathbf1[j\in G_i]\frac{p_{ij}}{\sum_{k\in G_i}p_{ik}}.

For three mentions of one entity with zero scores, the second mention assigns1/2 to its correct antecedent; the third assigns total2/3 to its two correct antecedents. Total loss is log3. Arbitrarily forcing the third to select only one correct antecedent changes the loss to log6 and trains a different objective.

The best forest need not give the most likely grouping

Suppose mention1 chooses dummy with probability0.45 or mention0 with0.55. Mention2 chooses dummy/mention0/mention1 with probabilities0.4/0.3/0.3. Mention0 has only dummy.

The highest-probability forest connects1 to0 and leaves2 alone: probability0.55×0.4=0.22. But the all-together cluster can arise through two forests, with total probability0.55×(0.3+0.3)=0.33. The operation changes when probabilities of equivalent forests are added:

P(C∣D)=∑y: clusters⁡(y)=CP(y∣D),clusters⁡(arg⁡max⁡yP(y))≠arg⁡max⁡CP(C) in general.P(C\mid D)=\sum_{\mathbf y:\,\operatorname{clusters}(\mathbf y)=C}P(\mathbf y\mid D), \qquad \operatorname{clusters}(\arg\max_{\mathbf y}P(\mathbf y))\ne\arg\max_C P(C)\ \text{in general}.

This is an original small counterexample, not an asserted error in the source paper. Our decoder returns the best forest’s clusters; it does not optimize the marginal probability of a partition.

Fit scores and inspect every decision

Run the complete block with Python3.12 and NumPy1.26. The four supplied mentions have invented gold cluster labels[0,1,0,1]. We optimize scalar mention/pair scores directly; no text encoder, mention detector or pretrained model is hidden behind an API. Fifty line-search steps reduce this fixed example’s summed loss from3.178054 to0.051008 and return clusters[0,2] and[1,3]. This is score fitting, not evidence of language generalization.

"""Original antecedent-score teaching model and explicitly scoped partition metrics."""
import json,math
import numpy as np


def validate(mentions,pairs):
    m=np.asarray(mentions,dtype=float);p=np.asarray(pairs,dtype=float)
    if m.ndim!=1 or len(m)>80 or p.shape!=(len(m),len(m)):
        raise ValueError('at most80 mentions and a square pair matrix required')
    if not np.isfinite(m).all() or not np.isfinite(p).all() or np.any(np.abs(m)>1e100) or np.any(np.abs(p)>1e100):
        raise ValueError('finite bounded scores required')
    return m,p


def distribution(mentions,pairs,allowed=None):
    m,p=validate(mentions,pairs);n=len(m)
    if allowed is None: allowed=np.tril(np.ones((n,n),dtype=bool),-1)
    allowed=np.asarray(allowed)
    if allowed.shape!=(n,n) or allowed.dtype!=bool or np.any(np.triu(allowed)):
        raise ValueError('boolean mask may allow earlier mentions only')
    rows=[]
    for i in range(n):
        js=[-1]+[j for j in range(i) if allowed[i,j]]
        scores=np.array([0.]+[m[i]+m[j]+p[i,j] for j in js[1:]])
        shifted=scores-np.max(scores);log_norm=math.log(float(np.exp(shifted).sum()))
        log_probs=shifted-log_norm
        rows.append({'antecedents':js,'scores':scores.tolist(),'log_probabilities':log_probs.tolist(),
                     'probabilities':np.exp(log_probs).tolist()})
    return rows


def clusters(antecedents):
    roots=[];groups={}
    for i,j in enumerate(antecedents):
        if type(j) is not int or not -1<=j<i:raise ValueError('antecedents must precede mentions')
        root=i if j==-1 else roots[j];roots.append(root);groups.setdefault(root,[]).append(i)
    return list(groups.values())


def decode(mentions,pairs,allowed=None):
    rows=distribution(mentions,pairs,allowed)
    links=[r['antecedents'][int(np.argmax(r['probabilities']))] for r in rows]
    log_probability=sum(r['log_probabilities'][r['antecedents'].index(j)] for r,j in zip(rows,links))
    return {'antecedents':links,'clusters':clusters(links),'log_probability':log_probability,'rows':rows}


def loss_gradient(mentions,pairs,gold,allowed=None):
    m,p=validate(mentions,pairs);rows=distribution(m,p,allowed)
    if len(gold)!=len(m) or any(x is not None and (type(x) is not int or x<0) for x in gold):
        raise ValueError('gold labels must be nonnegative integers or None')
    gm=np.zeros_like(m);gp=np.zeros_like(p);loss=0.
    for i,row in enumerate(rows):
        ids=row['antecedents'];correct=[k for k,j in enumerate(ids) if j>=0 and gold[i] is not None and gold[j]==gold[i]]
        if not correct:correct=[0]
        logs=np.asarray(row['log_probabilities']);gold_logs=logs[correct]
        center=float(np.max(gold_logs));log_mass=center+math.log(float(np.exp(gold_logs-center).sum()));loss-=log_mass
        residual=np.asarray(row['probabilities']);residual[correct]-=np.exp(gold_logs-log_mass)
        for k,j in enumerate(ids):
            if j>=0:gm[i]+=residual[k];gm[j]+=residual[k];gp[i,j]+=residual[k]
    return loss,gm,gp


def partition(values):
    result=[];seen=set()
    for group in values:
        if not group or any(not isinstance(x,str) or not x for x in group):raise ValueError('nonempty string mentions required')
        current=set(group)
        if len(current)!=len(group) or seen&current:raise ValueError('mentions must occur exactly once per partition')
        result.append(current);seen|=current
    return result


def measures(key,response):
    k,r=partition(key),partition(response)
    # Exact maximum-weight bipartite matching by bitmask DP, for small examples.
    if min(len(k),len(r))>10 or max(len(k),len(r))>100:raise ValueError('teaching alignment limit')
    def ratio(a,b):return a/b if b else 0.
    def prf(precision,recall):return {'precision':precision,'recall':recall,'f1':ratio(2*precision*recall,precision+recall)}
    def muc(left,right):
        num=den=0;covered=set().union(*right) if right else set()
        for group in left:
            parts=sum(bool(group&other) for other in right)+len(group-covered)
            num+=len(group)-parts;den+=len(group)-1
        return ratio(num,den)
    def b3(left,right):
        return ratio(sum(len(a&b)**2/len(a) for a in left for b in right),sum(map(len,left)))
    small,large=(k,r) if len(k)<=len(r) else (r,k);dp={0:0.}
    for a in large:
        nxt=dict(dp)
        for mask,value in dp.items():
            for j,b in enumerate(small):
                if not mask&(1<<j):
                    target=mask|(1<<j);score=value+2*len(a&b)/(len(a)+len(b));nxt[target]=max(nxt.get(target,0.),score)
        dp=nxt
    alignment=max(dp.values());muc_result=prf(muc(r,k),muc(k,r));b3_result=prf(b3(r,k),b3(k,r));ceaf=prf(ratio(alignment,len(r)),ratio(alignment,len(k)))
    return {'muc':muc_result,'b3':b3_result,'ceaf_e':ceaf,'mean_f1':sum(x['f1'] for x in [muc_result,b3_result,ceaf])/3,
            'policy':'Score supplied partitions including singletons; missing/spurious mentions retained; zero denominators map to0. Not an official CoNLL file scorer.'}


def fit(mentions,pairs,gold,steps=50):
    m,p=validate(mentions,pairs);m=m.copy();p=p.copy();trace=[]
    if type(steps) is not int or not 0<=steps<=1000:raise ValueError('steps must be0..1000')
    for step in range(steps+1):
        loss,gm,gp=loss_gradient(m,p,gold);trace.append(loss)
        if step==steps:break
        rate=1.
        for _ in range(40):
            new_m=m-rate*gm;new_p=p-rate*gp;new,_,_=loss_gradient(new_m,new_p,gold)
            if new<=loss-1e-4*rate*float(gm@gm+np.sum(gp*gp)):m,p=new_m,new_p;break
            rate*=.5
        else:raise ArithmeticError('line search did not accept a step')
    return m,p,trace


def demo():
    m=np.zeros(4);p=np.zeros((4,4));gold=[0,1,0,1]
    trained_m,trained_p,trace=fit(m,p,gold)
    counter=np.zeros((3,3));counter[1,0]=math.log(11/9);counter[2,:2]=math.log(3/4)
    return {'initial':decode(m,p),'trained':decode(trained_m,trained_p),'gold':gold,'loss_trace':trace,
            'mention_scores':trained_m.tolist(),'pair_scores':trained_p.tolist(),'map_forest_counterexample':decode(np.zeros(3),counter),
            'split_example':measures([['a','b','c']],[['a','b'],['c']]),
            'missing_spurious_example':measures([['a','b','c'],['d','e','f','g']],[['a','b'],['c','d'],['f','g','h','i']]),
            'scope':'Fixed ordered mentions; optimize scalar mention/pair scores, not a trained text encoder, mention detector, or corpus benchmark.'}

if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))

The program returns all antecedent probabilities, selected links, clusters, losses and three evaluation measures. It also reproduces the small missing/spurious-mention example from Pradhan et al., separately from our invented training case. Worked evaluation, §4

For n supplied mentions, constructing all pair distributions costs O(n²), with O(n²) stored scores and probabilities. Gradients visit each allowed pair. Cluster recovery follows earlier roots in O(n) expected dictionary time. These bounds omit the text encoder: the original all-span model has O(T²) spans and potentially O(T⁴) pairs for T tokens, motivating width limits, mention pruning and antecedent limits. Inference, §5

Our CEAF matching routine is exact for small examples: if the two partitions have a and b entities, set k=min(a,b) and l=max(a,b). Bitmask matching costs O(lk2^k) time and O(2^k) state space; set intersections add work depending on mention counts. The code limits k to10 and l to100. A scalable assignment algorithm is the appropriate replacement for larger evaluations.

Decide what the evaluator is allowed to forget

Good clustering of supplied gold mentions can hide poor mention detection. Keep missing and spurious mentions visible rather than quietly adding matching mentions to the opposite partition. Pradhan et al. explain how different mention treatments changed reported scores. Our routine scores the supplied partitions, retains singletons and maps zero denominators to0; it is not the official CoNLL file scorer. Scoring conventions and example

Let K contain gold entities and R predicted entities. For a gold entity K_i, p(K_i) counts its nonempty intersections with predicted entities plus each missing mention as a separate part. MUC recall measures how many required links remain connected; precision reverses gold and prediction:

RMUC=∑i(∣Ki∣−∣p(Ki)∣)∑i(∣Ki∣−1).R_{\rm MUC}=\frac{\sum_i(|K_i|-|p(K_i)|)}{\sum_i(|K_i|-1)}.

B³ gives credit at mention level. With missing mentions kept missing, recall is:

RB3=∑i∑j∣Ki∩Rj∣2/∣Ki∣∑i∣Ki∣.R_{B^3}=\frac{\sum_i\sum_j |K_i\cap R_j|^2/|K_i|}{\sum_i|K_i|}.

Precision swaps K and R. Entity-based CEAF allows each entity to align with at most one entity on the other side. Define similarity phi and find the largest total over one-to-one partial alignments pi:

ϕ(Ki,Rj)=2∣Ki∩Rj∣∣Ki∣+∣Rj∣,A=max⁡π∑(i,j)∈πϕ(Ki,Rj),RCEAFe=A∣K∣,PCEAFe=A∣R∣.\phi(K_i,R_j)=\frac{2|K_i\cap R_j|}{|K_i|+|R_j|},\qquad A=\max_{\pi}\sum_{(i,j)\in\pi}\phi(K_i,R_j),\qquad R_{\rm CEAF_e}=\frac A{|K|},\quad P_{\rm CEAF_e}=\frac A{|R|}.

For each measure, compute F1 as2PR/(P+R) under the stated zero policy. The CoNLL-style arithmetic mean combines three F1 values; it is not the F1 obtained by averaging their precision and recall first. Matching this formula alone does not establish benchmark comparability. Metric definitions Paper table1 caption

Fmean=FMUC+FB3+FCEAFe3.F_{\rm mean}=\frac{F_{\rm MUC}+F_{B^3}+F_{\rm CEAF_e}}3.

Other limits remain: ambiguous names, domain and language changes, distant antecedents pruned out of view, quotation and speaker shifts, and inconsistent entity definitions. A high score under one annotation policy does not settle those interpretations.

Trace the links and challenge the score

  1. Should a car and its wheels belong to one identity cluster? Does dummy prove that a span is not a mention?

Answer: No to both. The wheels relate to the car but are not the same object. Dummy can also start a new entity; distinguishing a false mention requires an additional mention policy.

  1. Three mentions belong to one entity and all logits are0. Why is marginal loss log3 rather than log6, and what are the third row’s real-logit derivatives?

Answer: The correct masses are1,1/2,2/3. Their product is1/3. Restricting the final choice to one antecedent would instead give1/6. Each real derivative is1/3−1/2=−1/6; either correct link is allowed.

  1. Use the0.45/0.55 and0.4/0.3/0.3 example. Does local argmax recover the highest-probability entity grouping?

Answer: It returns{0,1},{2}, whose best forest has probability0.22. The single cluster{0,1,2} receives0.33 after its two forests are summed. Enumerating all six configurations confirms normalization and the reversal.

  1. Gold is{a,b,c}; prediction is{a,b},{c}. Compute the three F1 values under our policy.

Answer: MUC has precision1 and recall1/2, so F1=2/3. B³ has precision1 and recall5/9, so F1=5/7. CEAF_e aligns the gold entity to{a,b}, giving similarity4/5, precision2/5 and recall4/5, hence F1=8/15. The measures penalize the split differently; none is a universal substitute for the others.

Keep model architecture and evaluation policy separate

Lee et al.‘s2017 system learns span representations using contextual boundaries and an attention-based span head, then prunes and scores antecedents. The pinned author code connects these factors to a marginalized loss. Our program isolates that decision layer; it does not reproduce the character CNN, bidirectional LSTM, span selection or published training run. Model and learning Fixed implementation

Pradhan et al.‘s2014 evaluation paper supplies a complementary lesson: matching a metric’s name does not guarantee matching mention treatment. Retain versioned scoring rules and report whether mentions were predicted. Evaluation reference

Use named entity recognition to study typed span detection and contextual embeddings for representations. Entity linking maps mentions to a knowledge-base identity; within-document coreference can group them even when no such identifier exists. The semantic-role topic assigns roles relative to a predicate, a different relation from entity identity.

Make a prediction, then check

A mention has two correct available antecedents. What probability enters marginal training?

Choose one answer

Learning objectives

  • Distinguish mentions, entity clusters and antecedent links.
  • Derive marginal training over multiple correct antecedents.
  • Explain why the most likely forest need not give the most likely partition.
  • Compute and compare MUC,B3 and entity-based CEAF under declared mention policies.

Prerequisites & connections

Explore related knowledge →

References

  1. End-to-end Neural Coreference Resolution
    Kenton Lee, Luheng He, Mike Lewis and Luke Zettlemoyer · 2017
  2. Scoring Coreference Partitions of Predicted Mentions: A Reference Implementation
    Sameer Pradhan, Xiaoqiang Luo, Marta Recasens, Eduard Hovy, Vincent Ng and Michael Strube · 2014
  3. Author coreference model, pinned 2017 implementation
    Kenton Lee and contributors · 2017

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-12 · Single AI author checked nine paired equations and four explained exercises against scoped Lee2017, pinned author scoring/loss code and Pradhan2014. Supplied ordered mentions, zero dummy, available gold antecedent marginalization and full score gradients checked. Independent six-forest enumeration distinguishes MAP forest0.22 from partition mass0.33; permutation oracle checks bounded CEAF matching. MUC/B3/CEAF missing, spurious and singleton conventions stated. Pradhan worked fixture attributed; no text encoder, official file scorer or corpus reproduction.

  • Single AI author checked nine paired equations and four explained exercises against scoped Lee2017, pinned author scoring/loss code and Pradhan2014. Supplied ordered mentions, zero dummy, available gold antecedent marginalization and full score gradients checked. Independent six-forest enumeration distinguishes MAP forest0.22 from partition mass0.33; permutation oracle checks bounded CEAF matching. MUC/B3/CEAF missing, spurious and singleton conventions stated. Pradhan worked fixture attributed; no text encoder, official file scorer or corpus reproduction.
  • Four original computed SVGs bind exact bilingual MDX. Eleven figure checks and36 isolated language/width cases with four fallback fonts passed; six actual desktop/mobile screenshots inspected by this AI author. This is separate from final full-page browser acceptance, with no human peer-review claim.
  • Post-freeze presentation correction: literal-set delimiters escaped after an actual Astro prerender failure. Frozen original, failure log and before/after patch retained at editorial/corrections/011a-literal-sets; program, equations and wording unchanged. Corrected-render validation is recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.