AI Wiki中文/EN

Named entity recognition: a name needs boundaries

命名实体识别

Define entity spans and BIO conventions, derive a linear-chain CRF and its gradients, and see why high token accuracy can hide missed entities.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Finding Acme is not the same as finding Acme Labs

Consider the invented sentence Ada joins Acme Labs. Suppose the annotation policy asks for people and organizations. The desired answer is the person Ada and the organization Acme Labs. Predicting only Acme finds a plausible name but gives the wrong organization boundary. Named entity recognition, NER, therefore asks for both a span and a category, not merely a label saying “this word looks like a name.”

Number tokens from zero and use half-open intervals: a span [a,b) contains positions a through b−1. The answers here are (0,1,PER) and (2,4,ORG). Keep the sentence identifier with each span when evaluating a corpus, or identical positions in unrelated sentences could be mistaken for the same entity.

“Entity” is an annotation decision. CoNLL-2003 uses PER, ORG, LOC and MISC, with flat, non-overlapping annotations and an explicit policy for embedded mentions. Our example uses only PER and ORG. A medical task might need another inventory; changing that inventory changes the task and the meaning of an evaluation score. CoNLL-2003, §2.3

NER locates a mention in text. It does not by itself determine which real-world person or organization that mention denotes; that is an entity-linking question. Nor does a mention detector decide that two pronouns refer to the same person. Keeping these tasks separate makes both errors and applications easier to understand.

A dictionary matcher is a useful baseline when a controlled list of names is available. Specify longest-match and overlap rules, then test unseen names and ambiguous uses of known names separately. It can supply a reliable starting point in a narrow task, but matching the spelling alone does not resolve context or annotation policy. The learned example below instead assigns scores to words and neighboring labels.

Compare legal BIO2 paths, exact entity spans and token accuracy. Adding correctly labelled outside tokens improves accuracy without repairing a broken entity.
Compare legal BIO2 paths, exact entity spans and token accuracy. Adding correctly labelled outside tokens improves accuracy without repairing a broken entity.

A sequence distribution with an explicit label convention

BIO2, IOB1 and IOBES are not interchangeable

BIO2 uses O outside an entity, B-X to begin an entity of type X, and I-X to continue it. Ada joins Acme Labs becomes B-PER O B-ORG I-ORG. An I-X may follow only B-X or I-X. Two adjacent B-PER labels represent two separate one-token people, not one two-token person.

The CoNLL-2003 paper describes the older IOB convention: I-X can begin an entity, and B-X distinguishes a new entity immediately following another of the same type. We call this IOB1 to distinguish it from BIO2. Its sequence I-ORG I-ORG O I-PER B-PER converts to B-ORG I-ORG O B-PER B-PER; the two final people must remain separate. The paper’s convention cannot be read as invalid BIO2 without first converting it. CoNLL-2003, §2.3

Lample and colleagues’ neural NER paper uses IOBES, which also marks entity ends and singleton entities. The associated loader contains a tag-scheme conversion step. Our code implements IOB1→BIO2 and strict BIO2 span extraction; it does not implement IOBES conversion. Declare the scheme before scoring, and reject malformed sequences rather than silently choosing a repair policy. Neural NER, §2.4 Pinned loader

Flat token tagging cannot represent every possible mention structure. A token inside both an organization and an embedded location needs more than one layer of labels; discontinuous mentions need a way to join separated intervals. Span-based or layered representations are alternatives to evaluate when the annotation task includes these cases. The flat model here intentionally does not claim that coverage.

Scores are not emission probabilities

For n tokens and K labels, let u_i(j) be a real score for assigning label j at position i. Let A_kj score a transition k→j, and let s_j and e_j score beginning and ending with j. The complete sequence score is:

S(x,y)=sy1+∑i=1nui(yi)+∑i=2nAyi−1,yi+eyn.S(x,y)=s_{y_1}+\sum_{i=1}^{n}u_i(y_i)+\sum_{i=2}^{n}A_{y_{i-1},y_i}+e_{y_n}.

Unlike HMM emission probabilities, these scores need not be positive or normalize row by row. In the neural paper, the unary scores come from a bidirectional recurrent encoder. Our small model looks them up in a word-by-label table, so it has no character or recurrent encoder. Both feed a linear-chain conditional random field, CRF, but their feature capabilities are very different. Neural NER, CRF formulation

Choose a set of allowed label sequences Y(x). The conditional distribution and negative log likelihood of a gold sequence y* are:

P(y∣x)=eS(x,y)Z(x),Z(x)=∑z∈Y(x)eS(x,z),ℓ(x,y∗)=log⁡Z(x)−S(x,y∗).P(y\mid x)=\frac{e^{S(x,y)}}{Z(x)},\qquad Z(x)=\sum_{z\in\mathcal Y(x)}e^{S(x,z)},\qquad \ell(x,y^*)=\log Z(x)-S(x,y^*).

The paper explicitly sums over all label sequences, including those that violate its label format. Our default instead excludes invalid BIO2 starts and transitions from both training and decoding, assigning their scores negative infinity. This changes the distribution. Merely learning transition scores does not mathematically guarantee valid output; an invalid unary preference can overwhelm finite transition penalties. The program’s bio2=False mode removes the hard restrictions but keeps the same five-label BIO2 inventory—it does not become the paper’s IOBES model. Neural NER, equation 1 and accompanying definition

Sum all paths without enumerating them

Let F_i(j) be the log sum of exponentiated prefix scores ending with j. LSE denotes stable log-sum-exp, computed after subtracting the largest input. With the chosen masks already applied:

F1(j)=sj+u1(j),Fi(j)=ui(j)+LSE⁡k(Fi−1(k)+Akj),log⁡Z=LSE⁡j(Fn(j)+ej).F_1(j)=s_j+u_1(j),\qquad F_i(j)=u_i(j)+\operatorname{LSE}_k(F_{i-1}(k)+A_{kj}),\qquad \log Z=\operatorname{LSE}_j(F_n(j)+e_j).

Replacing each LSE with a maximum and storing predecessor pointers yields the highest-scoring path, Viterbi decoding. Because every complete path shares the same partition function, maximizing S also maximizes its conditional probability. Replacing a sum with a maximum is a change of question, not an approximation to the same posterior.

The backward log score R_i(j) includes the suffix after position i and the ending score:

Rn(j)=ej,Ri(j)=LSE⁡k(Ajk+ui+1(k)+Ri+1(k)).R_n(j)=e_j,\qquad R_i(j)=\operatorname{LSE}_k(A_{jk}+u_{i+1}(k)+R_{i+1}(k)).

The node posterior q_i(j) and adjacent-label posterior q_i(k,j), with the latter referring to positions i−1 and i, follow by combining prefix and suffix:

qi(j)=exp⁡(Fi(j)+Ri(j)−log⁡Z),qi(k,j)=exp⁡(Fi−1(k)+Akj+ui(j)+Ri(j)−log⁡Z),i≥2.q_i(j)=\exp(F_i(j)+R_i(j)-\log Z),\qquad q_i(k,j)=\exp(F_{i-1}(k)+A_{kj}+u_i(j)+R_i(j)-\log Z),\quad i\ge2.

Summing an edge posterior over its second label must recover the previous node posterior; summing over its first label must recover the next one. These are useful consistency checks. Empty input has one empty path with score zero in this implementation, so log Z, loss and all gradients are zero.

The gradient is expected count minus observed count

Differentiating log Z gives the model’s expected use of a parameter. Subtracting the gold score removes its observed use:

∂ℓ∂ui(j)=qi(j)−1[yi∗=j],∂ℓ∂Akj=∑i=2n(qi(k,j)−1[yi−1∗=k,yi∗=j]).\frac{\partial\ell}{\partial u_i(j)}=q_i(j)-\mathbf1[y_i^*=j],\qquad \frac{\partial\ell}{\partial A_{kj}}=\sum_{i=2}^{n}\left(q_i(k,j)-\mathbf1[y_{i-1}^*=k,y_i^*=j]\right).

Start and end derivatives use the first and last node distributions minus their gold indicators. For a shared lexical table U, repeated occurrences of a word must accumulate their contributions to the same row:

∂ℓ∂Uv,j=∑i:id⁡(xi)=v(qi(j)−1[yi∗=j]).\frac{\partial\ell}{\partial U_{v,j}}=\sum_{i:\operatorname{id}(x_i)=v}\left(q_i(j)-\mathbf1[y_i^*=j]\right).

The program uses indexed addition, not assignment. Permanently forbidden transitions have zero model probability and never occur in valid gold sequences, so their gradients are zero; invalid constrained gold is rejected. Training minimizes the mean sentence loss, not the mean token loss. Including an empty sentence in that mean adds zero loss but still changes the number of sentences in the denominator.

Eleven paths or twenty-five?

Set every score to zero and use two tokens with the five labels O, B-PER, I-PER, B-ORG, I-ORG. Without constraints there are 5²=25 equally weighted paths. Under BIO2, the first label has three choices. Starting with O permits three second labels; starting with B-PER or B-ORG permits four each. Thus there are 3+4+4=11 allowed paths.

For a valid gold path, the losses are ln 25 and ln 11 respectively. The constrained first-position posterior is [3/11,4/11,0,4/11,0], and the second is [3/11,3/11,1/11,3/11,1/11]. Zero scores do not imply uniform node marginals when constraints allow different numbers of completions.

Adding the same constant c to every allowed complete-path score changes log Z by c but leaves probabilities and loss unchanged. The implementation removes common unary, transition and boundary offsets before dynamic programming, and computes the gold loss in the same centered coordinates. This avoids subtracting two huge, nearly equal absolute scores. Absolute scores returned for inspection can still lose small digits; numbers outside the supported floating-point range are rejected.

Train a small lexical CRF and inspect its spans

Save the complete program as ner.py and run python ner.py with Python 3.12.4 and NumPy 1.26.4. It uses four invented, explicitly labeled sentences, a training-only vocabulary and seed 29. Unseen words map to UNK without expanding the vocabulary. Full-batch training takes up to 60 steps, starting its backtracking search at learning rate 0.5 and accepting a sufficient decrease in the same stated loss. This optimizer is a teaching choice, not the original neural paper’s training configuration.

"""Original tiny linear-chain CRF and strict span evaluation for NER.

Default BIO2 constraints apply to both training and decoding. The cited neural
paper used IOBES and sums over all sequences; bio2=False demonstrates the
unrestricted normalization, while this toy keeps a BIO2 label inventory.
No LSTM, character encoder, external data or pretrained weights are used here.
"""
import json,math
import numpy as np
TAGS=('O','B-PER','I-PER','B-ORG','I-ORG')
UNK='<UNK>'


def text_token(value):
    if not isinstance(value,str) or not value or value==UNK or any(c.isspace() or 0xD800<=ord(c)<=0xDFFF for c in value):raise ValueError('One nonempty token without reserved UNK required')
    return value


def tag_parts(tag):
    if tag=='O':return 'O',None
    if not isinstance(tag,str) or len(tag)<3 or tag[0] not in 'BI' or tag[1]!='-' or not tag[2:] or any(c.isspace() for c in tag):raise ValueError('O, B-type or I-type required')
    return tag[0],tag[2:]


def bio2_masks(tags):
    parts=[tag_parts(t) for t in tags]
    if 'O' not in tags or len(set(tags))!=len(tags):raise ValueError('Unique BIO2 tags including O required')
    start=np.array([prefix!='I' for prefix,_ in parts])
    edge=np.array([[q!='I' or (p in ('B','I') and a==b) for q,b in parts] for p,a in parts])
    return start,edge


def iob1_to_bio2(tags):
    if not isinstance(tags,(list,tuple)):raise ValueError('Tag sequence required')
    result=[];previous_type=None
    for tag in tags:
        prefix,entity=tag_parts(tag)
        result.append('B-'+entity if prefix=='I' and entity!=previous_type else tag)
        previous_type=entity
    return result


def spans(tags,scheme='BIO2'):
    if scheme not in ('BIO2','IOB1') or not isinstance(tags,(list,tuple)):raise ValueError('Declared IOB1 or BIO2 sequence required')
    values=iob1_to_bio2(tags) if scheme=='IOB1' else list(tags);found=[];start=None;entity=None
    for i,tag in enumerate(values+['O']):
        prefix,kind=tag_parts(tag)
        if prefix=='I' and (start is None or kind!=entity):raise ValueError('Invalid BIO2 continuation')
        if prefix in ('O','B'):
            if start is not None:found.append((start,i,entity))
            start=i if prefix=='B' else None;entity=kind
    return found


def span_metrics(gold,predicted,scheme='BIO2'):
    if not isinstance(gold,(list,tuple)) or not isinstance(predicted,(list,tuple)) or len(gold)!=len(predicted):raise ValueError('Aligned sentences required')
    true=set();guess=set();correct=total=0
    for i,(g,p) in enumerate(zip(gold,predicted)):
        if len(g)!=len(p):raise ValueError('Aligned tokens required')
        true.update((i,*s) for s in spans(g,scheme));guess.update((i,*s) for s in spans(p,scheme))
        correct+=sum(a==b for a,b in zip(g,p));total+=len(g)
    tp=len(true&guess);fp=len(guess-true);fn=len(true-guess);denominator=2*tp+fp+fn
    return {'tp':tp,'fp':fp,'fn':fn,'precision':tp/(tp+fp) if tp+fp else None,'recall':tp/(tp+fn) if tp+fn else None,
            'f1':2*tp/denominator if denominator else None,'token_accuracy':correct/total if total else None,'tokens':total}


def initialize(sentences,seed=29):
    if type(seed) is not int or seed<0 or not isinstance(sentences,(list,tuple)) or not sentences:raise ValueError('Sentences and nonnegative seed required')
    words=set()
    for row in sentences:
        if not isinstance(row,(list,tuple)):raise ValueError('Pretokenized sentence required')
        words.update(text_token(w) for w in row)
    if not words:raise ValueError('At least one token required')
    vocabulary=[UNK]+sorted(words);k=len(TAGS);rng=np.random.default_rng(seed)
    return {'tags':list(TAGS),'vocabulary':vocabulary,'emission':rng.normal(0,.03,(len(vocabulary),k)),
            'transition':rng.normal(0,.03,(k,k)),'start':np.zeros(k),'end':np.zeros(k)}


def checked(model,words,bio2):
    if type(bio2) is not bool or not isinstance(words,(list,tuple)):raise ValueError('Boolean constraint policy and token sequence required')
    words=[text_token(w) for w in words];tags=model['tags'];vocabulary=model['vocabulary'];k=len(tags)
    start_mask,edge_mask=bio2_masks(tags)
    if not vocabulary or vocabulary[0]!=UNK or len(set(vocabulary))!=len(vocabulary):raise ValueError('Unique vocabulary with leading UNK required')
    p={key:np.asarray(model[key],dtype=float) for key in ('emission','transition','start','end')}
    for key,shape in [('emission',(len(vocabulary),k)),('transition',(k,k)),('start',(k,)),('end',(k,))]:
        if p[key].shape!=shape or not np.isfinite(p[key]).all():raise ValueError('Finite parameter tables with matching shapes required')
    index={w:i for i,w in enumerate(vocabulary)};ids=[index.get(w,0) for w in words]
    start=np.where(start_mask,p['start'],-np.inf) if bio2 else p['start']
    edge=np.where(edge_mask,p['transition'],-np.inf) if bio2 else p['transition']
    return p,ids,start,edge


def logsumexp(values):
    values=np.asarray(values,dtype=float)
    if np.isnan(values).any() or np.isposinf(values).any():raise ValueError('Invalid log scores')
    maximum=float(np.max(values))
    return -math.inf if maximum==-math.inf else maximum+math.log(float(np.exp(values-maximum).sum()))


def infer(model,words,bio2=True):
    p,ids,start,edge=checked(model,words,bio2);n=len(ids);k=len(model['tags'])
    if not n:return {'log_partition':0.,'centered_log_partition':0.,'score_offset':0.,'best_score':0.,'tags':[],'node':np.empty((0,k)),'edge':np.empty((0,k,k))}
    unary=p['emission'][ids];forward=np.empty((n,k));best=np.empty((n,k));back=np.zeros((n,k),dtype=int)
    # Remove path-independent constants before dynamic programming.
    umax=unary.max(axis=1);smax=float(start.max());emax=float(edge.max());endmax=float(p['end'].max())
    try:offset=math.fsum([*umax,smax,(n-1)*emax,endmax])
    except OverflowError as error:raise ValueError('Absolute sequence score cannot be represented') from error
    if not math.isfinite(offset):raise ValueError('Absolute sequence score cannot be represented')
    unary=unary-umax[:,None];start=start-smax;edge=edge-emax;end=p['end']-endmax
    try:
        with np.errstate(over='raise',invalid='raise'):
            forward[0]=best[0]=start+unary[0]
            for i in range(1,n):
                for j in range(k):
                    forward[i,j]=logsumexp(forward[i-1]+edge[:,j])+unary[i,j]
                    values=best[i-1]+edge[:,j];back[i,j]=int(np.argmax(values));best[i,j]=values[back[i,j]]+unary[i,j]
            z=logsumexp(forward[-1]+end);last=int(np.argmax(best[-1]+end));value=float(best[-1,last]+end[last])
            path=[last]
            for i in range(n-1,0,-1):path.append(int(back[i,path[-1]]))
            path.reverse();backward=np.empty((n,k));backward[-1]=end
            for i in range(n-2,-1,-1):
                for j in range(k):backward[i,j]=logsumexp(edge[j]+unary[i+1]+backward[i+1])
            node=np.exp(forward+backward-z);edges=np.empty((n-1,k,k))
            for i in range(n-1):edges[i]=np.exp(forward[i,:,None]+edge+unary[i+1,None,:]+backward[i+1,None,:]-z)
    except FloatingPointError as error:raise ValueError('CRF arithmetic exceeds the floating-point range') from error
    return {'log_partition':z+offset,'centered_log_partition':z,'score_offset':offset,'best_score':value+offset,'tags':[model['tags'][j] for j in path],'node':node,'edge':edges}


def score(model,words,labels,bio2=True):
    p,ids,start,edge=checked(model,words,bio2);lookup={t:i for i,t in enumerate(model['tags'])}
    if not isinstance(labels,(list,tuple)) or len(labels)!=len(ids) or any(t not in lookup for t in labels):raise ValueError('One known label per token required')
    if not ids:return 0.
    y=[lookup[t] for t in labels]
    value=start[y[0]]+p['end'][y[-1]]+sum(p['emission'][w,t] for w,t in zip(ids,y))+sum(edge[a,b] for a,b in zip(y,y[1:]))
    if np.isnan(value) or np.isposinf(value):raise ValueError('CRF score overflow')
    return float(value)


def loss_gradient(model,words,labels,bio2=True):
    p,ids,_,_=checked(model,words,bio2);gold=score(model,words,labels,bio2)
    if not math.isfinite(gold):raise ValueError('Gold sequence is excluded by the constraint policy')
    r=infer(model,words,bio2);gradient={key:np.zeros_like(value) for key,value in p.items()}
    if ids:
        y=[model['tags'].index(t) for t in labels];d=r['node'].copy();d[np.arange(len(y)),y]-=1;np.add.at(gradient['emission'],ids,d)
        gradient['transition']=r['edge'].sum(axis=0)
        for a,b in zip(y,y[1:]):gradient['transition'][a,b]-=1
        gradient['start']=r['node'][0].copy();gradient['start'][y[0]]-=1
        gradient['end']=r['node'][-1].copy();gradient['end'][y[-1]]-=1
    centered_gold=0.
    if ids:
        _,_,start,edge=checked(model,words,bio2)
        centered_gold=float(start[y[0]]-start.max())+float(p['end'][y[-1]]-p['end'].max())
        centered_gold+=sum(float(p['emission'][w,t]-p['emission'][w].max()) for w,t in zip(ids,y))
        centered_gold+=sum(float(edge[a,b]-edge.max()) for a,b in zip(y,y[1:]))
    return r['centered_log_partition']-centered_gold,gradient,r


def train(initial,sentences,labels,steps=60,rate=.5,bio2=True):
    if not isinstance(sentences,(list,tuple)) or not sentences or len(sentences)!=len(labels):raise ValueError('Aligned nonempty training collection required')
    if type(steps) is not int or steps<0 or isinstance(rate,bool) or not isinstance(rate,(int,float)) or not math.isfinite(rate) or rate<=0:raise ValueError('Nonnegative steps and positive finite rate required')
    keys=('emission','transition','start','end');model={key:(np.array(v,copy=True,dtype=float) if key in keys else list(v)) for key,v in initial.items()}
    def batch(current):
        total=0.;g={key:np.zeros_like(current[key]) for key in keys}
        for words,tags in zip(sentences,labels):
            value,part,_=loss_gradient(current,words,tags,bio2);total+=value
            for key in keys:g[key]+=part[key]
        return total/len(sentences),{key:value/len(sentences) for key,value in g.items()}
    value,g=batch(model);trace=[value]
    for _ in range(steps):
        norm=sum(float(np.sum(v*v)) for v in g.values())
        if norm<1e-24:break
        step=rate
        for _ in range(40):
            candidate=dict(model)
            for key in keys:candidate[key]=model[key]-step*g[key]
            try:new,ng=batch(candidate)
            except (ValueError,FloatingPointError):new=math.inf
            if new<=value-1e-4*step*norm:break
            step*=.5
        else:raise ValueError('No decreasing step found')
        model,value,g=candidate,new,ng;trace.append(value)
    return model,trace


def demo():
    sentences=[['Ada','joins','Acme','Labs'],['Bo','visits','Acme'],['Acme','hires','Ada'],['Ada','visits','Bo']]
    labels=[['B-PER','O','B-ORG','I-ORG'],['B-PER','O','B-ORG'],['B-ORG','O','B-PER'],['B-PER','O','B-PER']]
    initial=initialize(sentences);model,trace=train(initial,sentences,labels)
    queries=sentences+[['Mira','joins','Acme','Labs']];results=[]
    for words in queries:
        r=infer(model,words);results.append({'tokens':words,'tags':r['tags'],'spans':spans(r['tags']),'log_partition':r['log_partition'],'best_score':r['best_score'],'node':r['node'].tolist()})
    hand=initialize([['x','y']])
    for key in ('emission','transition','start','end'):hand[key][:]=0
    zero={str(policy):{'loss':loss_gradient(hand,['x','y'],['B-PER','I-PER'],policy)[0],
                       'node':infer(hand,['x','y'],policy)['node'].tolist()} for policy in [True,False]}
    hand['emission'][hand['vocabulary'].index('x'),2]=3.
    invalid={'unrestricted':infer(hand,['x'],False)['tags'],'constrained':infer(hand,['x'],True)['tags']}
    gold=[['B-PER','O','B-ORG','I-ORG']];pred=[['B-PER','O','B-ORG','O']]
    return {'training':sentences,'gold':labels,'loss_trace':trace,'queries':results,'zero_score_models':zero,'invalid_local_preference':invalid,
            'iob1':['I-ORG','I-ORG','O','I-PER','B-PER'],'converted_bio2':iob1_to_bio2(['I-ORG','I-ORG','O','I-PER','B-PER']),
            'span_boundary_error':span_metrics(gold,pred),'outside_inflation':span_metrics([gold[0]+['O']*20],[pred[0]+['O']*20]),
            'empty_entity_case':span_metrics([['O']],[['O']]),
            'scope':'Original lexical CRF with optional hard BIO2 constraints, exact forward-backward and Viterbi. No LSTM or CoNLL reproduction. Original CoNLL IOB1, BIO2 and paper unrestricted sequence normalization are distinguished; span metrics require exact type and boundaries.'}
if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=False,indent=2,allow_nan=False))

The mean training loss decreases from about 4.039219 to 0.075138. The four training sentences decode to their supplied labels. For the invented query Mira joins Acme Labs, the model also predicts a person followed by an organization. That one unseen-name example is not an estimate of generalization: this model has no spelling features and uses the same UNK row for every unseen spelling.

Dense inference costs O(nK²) time. Node tables require O(nK) space; this program also stores every adjacent-label posterior, so its working space is O(nK²). The parameters occupy O(VK+K²) space. A version that accumulates edge expectations while sweeping backward can avoid retaining the entire edge tensor, but that is not what this implementation stores.

Score complete spans

Represent predicted and gold entities as sets of (sentence, start, end, type). A true positive must match all four fields. Count unmatched predictions as FP and unmatched gold entities as FN. Then:

Precision=TPTP+FP,Recall=TPTP+FN,F1=2TP2TP+FP+FN.\mathrm{Precision}=\frac{TP}{TP+FP},\qquad \mathrm{Recall}=\frac{TP}{TP+FN},\qquad F_1=\frac{2TP}{2TP+FP+FN}.

This follows the task’s exact-entity evaluation principle; the program is not a copy or execution of the official CoNLL scoring script. Its undefined-denominator convention is explicit: return null for an undefined rate rather than silently making an all-O corpus perfect at entity recognition. CoNLL-2003, §2.4

For gold B-PER O B-ORG I-ORG and prediction B-PER O B-ORG O, token accuracy is 3/4, yet the organization boundary is wrong. There is one true positive, one false positive and one false negative, giving entity F1=1/2. Append twenty correctly predicted O tokens: token accuracy becomes 23/24, while entity F1 stays 1/2. Reporting token accuracy alone would conceal the same entity error behind more easy background positions.

An accurate extractor needs a stable task

Fix tokenization, label convention, type inventory and overlap policy before comparing systems. Keep document splits intact when names or nearly duplicate passages recur; otherwise memorizing a name can look like learning to recognize unseen entities. Report per-type errors, boundary errors and performance on unseen names as well as the pooled micro score. A dictionary baseline and a local token classifier can reveal where sequence structure actually helps.

The lexical CRF only sees word identity and neighboring labels. A contextual encoder changes what the unary scores can depend on; a CRF layer still controls how those scores combine across a path. Neither design removes the need for representative labels. Domain shifts can change whether a word is a name, which type it belongs to and how much of a phrase the annotation includes. Neural NER, encoder and CRF description

For an application, keep offsets back to the original text, test normalization and subword-to-token alignment, and record rejected or low-confidence cases according to the task’s error cost. A mention extracted with the right category but wrong offsets can still break highlighting, linking or downstream counts. These engineering checks concern the extraction interface; they are not implemented by the small tagger above.

The inspected author code pads boundaries with finite −1000 values and calls a forward helper. A finite penalty is not the same mathematical object as an impossible transition; we did not execute or fully audit that helper. Use the pinned code to inspect implementation choices, not to claim our hard-mask CRF is byte-for-byte equivalent. Pinned model code

Test the boundary, the distribution and the metric

  1. Understanding. Does B-PER B-PER mean one two-token person? How does IOB1 I-PER B-PER convert?

Answer: BIO2’s two B labels start two separate one-token entities. The IOB1 sequence also contains two entities and converts to B-PER B-PER. Merging them would change the gold boundaries rather than merely rename a format.

  1. Hand calculation. With all-zero scores and the five labels above, why is the two-token constrained loss ln 11 rather than ln 9 or ln 25?

Answer: O has three allowed continuations, and each of the two B labels has four. The sum is 11. I labels cannot start, but a matching I can continue its B, so counting only three choices independently at both positions incorrectly gives 9. The unrestricted inventory gives 25.

  1. Counterexample. A system misses the end of Acme Labs, then correctly labels twenty added background tokens. What happens to entity F1 and token accuracy in the example above?

Answer: TP=1, FP=1 and FN=1 do not change, so F1 remains 1/2. Token accuracy rises from 3/4 to 23/24. The added O tokens do not repair either the spurious short organization or the missing full organization.

  1. Method choice. An annotation project asks for an organization and an embedded location covering some of the same tokens. Can this single BIO2 path encode both, and what should change before evaluating a replacement?

Answer: It cannot assign two overlapping entity memberships to the same token. Choose an explicit nested-span or multiple-layer representation, define how boundaries and types are matched, and keep the same document split for a comparison. Do not discard the embedded entities merely to make the flat baseline appear complete.

Keep the source model and the teaching model distinct

The CoNLL-2003 task paper by Erik F. Tjong Kim Sang and Fien De Meulder supplies the annotation and exact-match evaluation conventions discussed here. The inspected portions cover §§2.3–2.4; this chapter does not reproduce its corpora or leaderboard. Task paper

Guillaume Lample, Miguel Ballesteros, Sandeep Subramanian, Kazuya Kawakami and Chris Dyer’s 2016 paper supplies the neural unary-score and CRF formulation, including unrestricted sequence normalization and IOBES. The derivations above use explicitly stated BIO2 masks, a lexical unary table and an original optimizer instead. Neural architectures paper

The author repository is pinned to 1c9618889fb89500cc5e70c45c27859b89d44449. Inspected ranges are model.py 277–317 and loader.py 32–53, not a complete audit of the project. The accompanying original tests enumerate paths independently, compare all 45 parameters of a two-word-class test model by finite differences, check repeated-word accumulation, and exercise exact-span and large-offset cases. The four-sentence training demo has a larger vocabulary; 45 is the gradient-check fixture’s parameter count, not the demo’s. Model Loader

Make a prediction, then check

With O, B-PER, I-PER, B-ORG and I-ORG, how many valid BIO2 paths do two tokens have?

Choose one answer

Learning objectives

  • Distinguish mention spans, entity types and linking.
  • Convert IOB1 to BIO2 without losing adjacent entity boundaries.
  • Derive constrained CRF normalization and expected-minus-observed gradients.
  • Evaluate exact spans and expose background-token accuracy inflation.

Prerequisites & connections

Explore related knowledge →

References

  1. Introduction to the CoNLL-2003 Shared Task: Language-Independent Named Entity Recognition
    Erik F. Tjong Kim Sang; Fien De Meulder · 2003
  2. Neural Architectures for Named Entity Recognition
    Guillaume Lample; Miguel Ballesteros; Sandeep Subramanian; Kazuya Kawakami; Chris Dyer · 2016
  3. Author neural NER tagger, pinned CRF and tag-loader code
    Guillaume Lample and tagger contributors

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-12 · Codex single-AI-author technical check: scoped neural NER/CoNLL papers and pinned tagger model/loader; eight paired equations and four explained exercises. Lexical linear CRF with hard BIO2 masks differs from LSTM/IOBES source model. Exact partition, node/edge marginals, expected-minus-gold gradients, repeated rows, offset stability, IOB1 conversion, exact entity metrics and O-token inflation. Actual 45-parameter difference fixture; no corpus or author-code reproduction.

  • Codex single-AI-author technical check: scoped neural NER/CoNLL papers and pinned tagger model/loader; eight paired equations and four explained exercises. Lexical linear CRF with hard BIO2 masks differs from LSTM/IOBES source model. Exact partition, node/edge marginals, expected-minus-gold gradients, repeated rows, offset stability, IOB1 conversion, exact entity metrics and O-token inflation. Actual 45-parameter difference fixture; no corpus or author-code reproduction.
  • Four original SVGs bind the exact MDX program. Nine figure tests validate numeric results, encodings and dependency arc geometry. Thirty standalone language/width cases and four fallback fonts passed; ten desktop/mobile screenshots were actually inspected. The original false arc crossing and its correction evidence are preserved. Complete article browser acceptance is separate; no human peer review or upstream execution.

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.