命名实体识别:名字还需要正确的边界
Named entity recognition
区分实体跨度和 BIO 约定,推导线性链 CRF 及其梯度,观察为什么很高的词元准确率也会掩盖实体漏检。
named-entity-recognition找到 Acme,不等于找到了 Acme Labs
看一个虚构句子:Ada joins Acme Labs。假设标注任务要求找出人名和机构名,答案应该是人名 Ada 与机构名 Acme Labs。只预测 Acme,虽然找到了一个像名字的词,却把机构边界截短了。命名实体识别(named entity recognition,NER)因此既要确定范围,也要确定类别,不能只标记“这个词看起来是名字”。
从零给词元编号,用左闭右开的区间表示跨度:[a,b) 包含位置 a 到 b−1。这里的答案是 (0,1,PER) 和 (2,4,ORG)。评测整个语料时,跨度还要带句子编号,否则不同句子中相同的位置可能被误认为同一个实体。
“实体”由标注规范定义。CoNLL-2003 使用 PER、ORG、LOC、MISC 四类,采用平面、不重叠的标注,并规定如何处理嵌套提及。本文只用 PER 和 ORG。医学任务可能需要另一套类别;改变类别集,也就改变了任务和评分的含义。CoNLL-2003 §2.3
NER 定位的是文本中的一次提及,不会单独确定它指现实世界中的哪一个人或机构;那属于实体链接问题。提及检测也不负责判断两个代词是否指同一人。把任务分清,错误和应用边界才容易解释。
如果有受控的名字清单,词典匹配是值得保留的基线。先规定最长匹配和重叠规则,再分别测试未见名字,以及已知名字在含混语境中的用法。它可以成为狭窄任务中可靠的起点,但只匹配拼写无法解决上下文和标注规范问题。下面的学习模型则给词及相邻标签赋分。
标签约定明确之后,才有序列分布
BIO2、IOB1 与 IOBES 不能混用
BIO2 用 O 表示实体外,B-X 表示 X 类实体的开始,I-X 表示它的延续。Ada joins Acme Labs 对应 B-PER O B-ORG I-ORG。I-X 前面只能是 B-X 或 I-X。相邻两个 B-PER 表示两个各占一个词元的人名,不是一个双词人名。
CoNLL-2003 论文描述的是更早的 IOB 约定:I-X 也可以开始一个实体,B-X 用来区分紧接在同类型实体后面的新实体。这里称它为 IOB1,以区别于 BIO2。序列 I-ORG I-ORG O I-PER B-PER 应转成 B-ORG I-ORG O B-PER B-PER,末尾两个人名必须保持分开。不能未经转换,就按 BIO2 把论文采用的格式判为非法。CoNLL-2003 §2.3
Lample 等人的神经 NER 论文使用 IOBES,还会显式标记实体结尾与单词元实体。配套 loader 中有标签格式转换步骤。本文代码实现 IOB1→BIO2 和严格的 BIO2 跨度提取,不实现 IOBES 转换。评分前声明格式;遇到非法序列就拒绝,而不是悄悄替它决定一种修复方式。神经 NER §2.4 固定 loader
平面词元标注不能表示所有提及结构。如果一个词元同时处于机构名和内嵌地点名中,就需要不止一层标签;不连续提及则需要把分开的区间连接起来。任务包含这些情况时,可以比较直接预测跨度或多层标注的方案。这里的平面模型不声称覆盖这些结构。
分数不是发射概率
对 n 个词元和 K 个标签,令 u_i(j) 是位置 i 取标签 j 的实数分数,A_kj 是转移 k→j 的分数,s_j、e_j 分别为以 j 开始和结束的分数。完整序列得分为:
与 HMM 发射概率不同,这些分数不必为正,也不需要逐行归一化。神经模型论文用双向循环编码器生成一元分数;本文小模型直接查“词×标签”表,没有字符或循环编码器。两者都可以连接线性链条件随机场(CRF),但能表达的特征差别很大。神经 NER 的 CRF 形式
先选择允许的标签序列集合 Y(x)。条件分布和标准序列 y* 的负对数似然为:
原论文明确对全部标签序列求和,包括违反标签格式的序列。本文默认在训练和解码两处都排除非法 BIO2 起点与转移,把其分数设为负无穷;这会改变分布。仅仅学习转移分数,并不能在数学上保证输出合法:某个非法标签很高的一元分数,可能压过有限的转移惩罚。代码的 bio2=False 模式移除硬限制,但仍保留同一套五标签 BIO2 标签集,不会变成论文的 IOBES 模型。神经 NER 式 1 及其集合定义
不枚举,也能把所有路径加起来
令 F_i(j) 为以 j 结束的前缀分数经过指数化、求和、取对数的结果。LSE 表示先减去最大输入再计算的稳定 log-sum-exp。把选定的掩码应用到分数后,有:
把每个 LSE 换成最大值,并记录前驱指针,就能得到分数最高的 Viterbi 路径。全部完整路径共享同一个配分函数,因此最大化 S 也就最大化条件概率。把求和换成最大值,是在回答另一个问题,不是对同一个后验进行近似。
后向对数分数 R_i(j) 包括位置 i 之后的后缀以及结束分数:
结合前缀与后缀,可得节点后验 q_i(j) 和相邻标签后验 q_i(k,j),后者对应位置 i−1 与 i:
边后验对第二个标签求和,应恢复前一位置的节点后验;对第一个标签求和,应恢复后一位置的节点后验。这些关系适合用来检查实现是否一致。本文把空输入定义为只有一条得分为零的空路径,因此 log Z、损失和全部梯度都是零。
梯度是期望计数减实际计数
对 log Z 求导,得到模型对某个参数使用次数的期望;再减去标准序列得分的导数,就减掉了实际使用次数:
起点和终点的导数分别用首尾节点分布减去标准标签的指示量。对共享词表 U,同一个词反复出现时,梯度要累加到同一行:
代码使用索引累加,而不是覆盖赋值。永久禁止的转移在模型中概率为零,也不会出现在合法标准序列中,因此梯度为零;约束下非法的标准序列会被拒绝。训练最小化的是平均句子损失,不是平均词元损失。平均值里加入一个空句,虽然加了零损失,但仍会改变分母中的句子数。
到底是十一条路径,还是二十五条?
把全部分数设为零,输入两个词元,标签为 O、B-PER、I-PER、B-ORG、I-ORG。没有约束时共有 5²=25 条等权路径。BIO2 下首标签有三种选择:以 O 开始,第二个标签可选三种;以 B-PER 或 B-ORG 开始,各可选四种。因此合法路径数是 3+4+4=11。
对一条合法标准路径,两种损失分别为 ln 25 与 ln 11。约束下第一个位置后验为 [3/11,4/11,0,4/11,0],第二个为 [3/11,3/11,1/11,3/11,1/11]。当约束允许的后续路径数不同时,零分数并不意味着节点后验均匀。
给每条合法完整路径的得分都加上常数 c,会让 log Z 增加 c,但概率和损失不变。实现先从一元、转移和边界分数中去掉公共偏置,再做动态规划,并在相同的中心化坐标中计算标准路径损失。这样可以避免两个巨大且相近的绝对分数直接相减。返回供观察的绝对分数仍可能丢失小数位;超出支持的浮点范围时,程序会拒绝计算。
训练小型词汇 CRF,再检查实体跨度
把完整程序保存为 ner.py,在 Python 3.12.4、NumPy 1.26.4 环境中运行 python ner.py。它使用四句虚构、显式标注的句子,仅由训练集构造词表,随机种子为 29。未见词映射到 UNK,不扩展词表。全批训练最多运行 60 步,每次从学习率 0.5 开始回溯搜索,只接受满足充分下降条件的同一损失更新。这是教学优化器,不是神经模型原论文的训练配置。
"""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))
平均训练损失从约 4.039219 降到 0.075138,四个训练句的解码都与给定标签一致。虚构查询 Mira joins Acme Labs 也被预测为一个人名和一个机构名。这一个未见人名例子不能估计泛化能力:模型没有拼写特征,所有未见拼写都用同一 UNK 行。
稠密推断耗时 O(nK²),节点表占 O(nK) 空间;本程序还保存每一对相邻标签的后验,因此工作空间是 O(nK²)。参数占 O(VK+K²)。另一种实现可以在后向扫描时直接累加边期望,不保存完整边张量,但本文代码没有采用这种存储方式。
按完整跨度计分
将预测和标准实体表示为 (句子, 起点, 终点, 类型) 的集合,四项都匹配才算真阳性 TP。没匹配到的预测算 FP,没被找回的标准实体算 FN。于是:
这遵循任务按完整实体精确匹配的原则;本程序没有复制或运行官方 CoNLL 评分脚本。未定义分母的约定也明确给出:相应比率返回 null,不把全是 O 的语料悄悄评成实体识别满分。CoNLL-2003 §2.4
标准标签为 B-PER O B-ORG I-ORG,预测为 B-PER O B-ORG O 时,词元准确率有 3/4,但机构边界错了。此时 TP=1、FP=1、FN=1,实体 F1=1/2。再加二十个正确预测的 O,词元准确率升到 23/24,实体 F1 仍为 1/2。只报告词元准确率,就会让更多容易的背景位置掩盖同一个实体错误。
可靠提取依赖稳定的任务定义
比较系统前,先固定分词、标签格式、类别集和重叠规则。名字或近重复段落反复出现时,应保持文档级数据划分,避免记住名字被误当成识别未见实体。除了汇总的微平均分数,还要报告各类型错误、边界错误及未见名字的表现。词典基线和局部词元分类器能帮助判断序列结构究竟在哪些地方有效。
词汇 CRF 只看到词身份及相邻标签。上下文编码器改变的是一元分数能够依赖哪些信息;CRF 层控制这些分数如何沿路径组合。无论哪种设计,都需要有代表性的标注。领域变化可能改变一个词是否为名字、属于哪一类,以及标注应该覆盖多长的短语。神经 NER 的编码器与 CRF 说明
用于实际应用时,要保留回到原文的偏移量,测试规范化和子词到词元的对齐,并按任务的错误代价处理拒绝或低置信度结果。即使提及类别正确,偏移量错误仍会破坏高亮、链接或后续统计。这些检查属于提取接口的工程要求,上面的小标注器没有实现它们。
核读的作者代码使用有限的 −1000 填充边界,再调用前向 helper。有限惩罚与“不可能转移”不是同一个数学对象;本次没有运行或完整审查那个 helper。固定源码适合检查实现选择,不能用来宣称本文硬掩码 CRF 与原实现逐字等价。固定模型代码
检查边界、分布与指标
- 理解。
B-PER B-PER表示一个双词人名吗?IOB1 的I-PER B-PER应如何转换?
答案:BIO2 中两个 B 分别开始两个单词元实体。这个 IOB1 序列同样有两个实体,转成 B-PER B-PER。把它们合并,会改变标准边界,而不只是改写格式。
- 手算。 上述五标签、全部零分数的双词元例子,为什么约束损失是 ln 11,而不是 ln 9 或 ln 25?
答案:O 有三个合法后继,两个 B 标签各有四个,总数是 11。I 不能开头,但可以接在匹配的 B 后面;把两个位置都独立算作三种选择,会误得 9。完全不受约束时才是 25。
- 反例。 系统漏掉
Acme Labs的末尾,再正确标注二十个新增背景词元。在上面的例子中,实体 F1 和词元准确率分别如何变化?
答案:TP=1、FP=1、FN=1 没变,F1 仍是 1/2。词元准确率从 3/4 升到 23/24。新增 O 并没有修好那个多报的短机构名,也没有找回完整机构名。
- 方法选择。 标注任务同时要求一个机构名及其内部地点名,两者覆盖部分相同词元。单条 BIO2 路径能否表示?评测替代方案前应改变什么?
答案:它不能让同一个词元同时属于两个重叠实体。应明确采用嵌套跨度或多层表示,规定如何匹配边界和类型,并保持同一文档划分来比较。不能为了让平面基线显得完整,就删掉内嵌实体。
把来源模型与教学模型分清
Erik F. Tjong Kim Sang 与 Fien De Meulder 的 CoNLL-2003 任务论文提供了本文讨论的标注和精确匹配约定。核读范围包括 §2.3—2.4;本文没有复现其语料或排行榜。任务论文
Guillaume Lample、Miguel Ballesteros、Sandeep Subramanian、Kazuya Kawakami、Chris Dyer 在 2016 年的论文中给出了神经一元分数与 CRF 形式,包括不限制标签格式的序列归一化以及 IOBES。上面的推导则明确采用 BIO2 掩码、词汇一元表和原创优化器。神经架构论文
作者仓库固定在提交 1c9618889fb89500cc5e70c45c27859b89d44449,核读 model.py 277—317 行和 loader.py 32—53 行,不是完整项目审计。原创配套测试独立枚举路径,对两个词表类别的小测试模型全部 45 个参数做有限差分,检查重复词累加、精确跨度和大偏置。四句训练演示的词表更大;45 指梯度检查模型的参数数,不是演示模型的。模型 Loader
先判断,再看解释
使用 O、B-PER、I-PER、B-ORG、I-ORG 时,两个词元有多少条合法 BIO2 路径?
学习目标
- 区分提及跨度、实体类型与实体链接。
- 转换 IOB1 为 BIO2 并保留相邻实体边界。
- 推导受约束 CRF 归一化及期望减观测梯度。
- 按精确跨度评测,识别背景词造成的准确率膨胀。
先修与延伸
查看知识关联图 →参考文献
- Introduction to the CoNLL-2003 Shared Task: Language-Independent Named Entity Recognition
Erik F. Tjong Kim Sang; Fien De Meulder · 2003 - Neural Architectures for Named Entity Recognition
Guillaume Lample; Miguel Ballesteros; Sandeep Subramanian; Kazuya Kawakami; Chris Dyer · 2016 - Author neural NER tagger, pinned CRF and tag-loader code
Guillaume Lample and tagger contributors
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(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.
- 单AI作者核对双语八组公式和四解释习题:词汇线性CRF、硬BIO2与原模型LSTM/IOBES区分;11合法与25无约束路径、节点/边后验、期望减金标梯度、重复行、偏移稳定性、45参数差分、IOB1转换、实体精确匹配及非实体词元准确率膨胀。未复现语料基准。
- 四张原创SVG绑定真实MDX程序。九项图检查核数值、编码及依存弧几何;30组独立语言/宽度组合与四备用字体验证通过,实际查看十张桌面/手机截图。保留原假交叉与纠错证据。完整文章浏览器验收另记,无人工同行审校或上游执行。
核对的来源位置:
- Introduction to the CoNLL-2003 Shared Task: Language-Independent Named Entity Recognition · Scoped §§2.3–2.4, text65–160: IOB1 convention, flat entity types and exact-match evaluation. No official scorer execution, corpus reuse or leaderboard reproduction.
- Neural Architectures for Named Entity Recognition · Scoped text92–210 and physical page3: neural unary scores, CRF sequence normalization including invalid paths, and IOBES. Our lexical hard-BIO2 model differs; original benchmarks not reproduced.
- Author neural NER tagger, pinned CRF and tag-loader code · Read model.py277–317 and same-commit loader.py32–53: finite boundary padding and conversion calls. Helpers unreviewed; no upstream execution. Root Apache-2.0 identity recorded separately; not a full material-license audit.
相关主题