语义角色标注:谁对谁做了什么?
Semantic role labeling
区分语义角色与句法,推导带约束的区间选择及梯度,运行完整小型模型。
semantic-role-labeling谁把什么交给了谁?
在虚构句子 Mina handed Jo a map on Monday 中,识别出人名或名词,还不能说明谁递出了地图。更有用的表示把 handed 与给予者、接收者、物品和时间联系起来。语义角色标注(semantic role labeling,SRL)识别的就是这类谓词—论元关系。
把句子改成 A map was handed to Jo by Mina,语法主语变了,给予者却不必改变。句法提供线索,主语标签本身不是语义角色。Gildea和Jurafsky的统计系统使用短语类型、位置、语态、中心词等特征;其最初的角色分类实验给定论元边界,把“选标签”与“找出论元”分开。方法与特征,§4
标签集也是任务定义的一部分。FrameNet为语义框架定义角色;PropBank在谓词的frameset内给角色编号:ARG0通常近似施事,ARG1通常近似受事或主题,但编号不是通用定义。尤其是更高编号的角色,必须查具体谓词的说明。角色体系,§2 PropBank,§3
本文给虚构的传递框架规定ARG0=给予者、ARG1=物品、ARG2=接收者、ARGM-TMP=时间。这是教学定义,不表示已经核读实际hand的frames文件。程序接收谓词位置和候选区间,回答哪些候选可以共存;它不会从原始文本中自动找出候选。
选择相容的集合,而不是孤立地选标签
先规定输出空间
词元从0编号,区间采用左闭右开[a,b)。例句共七个词元,谓词下标为1;目标论元区间是[0,1)、[2,3)、[3,5)和[5,7)。每个候选c包含起点、终点、角色和特征向量x_c。给定权重w,选中集合Y的分数按候选相加:
在这一个谓词的输出中,区间不得重叠、不得包含谓词词元,声明为核心角色的标签至多出现一次;修饰语可以重复。允许空集合,不强制填满角色。不同谓词自己的论元结构可以复用同一个词元。这些是本文解码器的假设,不是PropBank的完整标注规则。
令V为所有相容集合构成的有限集合族。条件对数线性模型对整个候选集合归一化:
逐个选择最高分候选,可能选出重叠区间或重复ARG0。分别归一化各候选,也是在定义另一个输出空间。
用状态记住已经用过的角色
状态(t,M)表示t之前的词元已经处理,位掩码M记录已用核心角色。起点为(0,0)。一条边跳过词元t,得分为0;从t开始的候选则跳到自己的终点,加上候选分数,并在角色尚未使用时设置对应位。修饰语不设置位。每个相容集合恰好对应一条路径:跳过未覆盖词元,每个已选区间只走一次。
对从u到v、得分为s_e的边e,累积前向对数质量alpha。初始alpha(0,0)=0,其他位置为负无穷;所有终点掩码都纳入求和,没有额外结束分数。
把logaddexp换成max,就得到Viterbi分数及回溯指针。计算边缘概率时,再求后向对数质量beta,所有终点掩码初始化为0。同一个候选可能从不同掩码状态出发,因此要累加属于它的所有边概率:
给定合法金标集合G,负对数似然的梯度是“模型期望选中的特征减去金标特征”。若矩阵X的每行为一个候选的特征,g为候选是否属于金标的指示向量:
三个候选就能手算
取a=[0,1)/ARG0、b=[1,2)/ARG0、c=[1,2)/ARG1,它们分数的指数分别为2、3、5。合法集合为:空、a、b、c、{a,c}。{a,b}违反角色唯一性,{b,c}则重叠。
若有n个词元、C个候选、R种唯一角色,每次前向、后向或边缘概率计算需要O((n+C)2^R)时间;表格与回溯指针占O(n2^R+C)空间。D维线性特征的打分及梯度另需O(CD)计算。这是本程序的稠密掩码复杂度,不表示所有SRL系统都采用指数规模的角色状态。
运行完整的约束算例
Python3.12和NumPy1.26即可,不需要下载数据、模型或调用API。把下面整段保存为一个文件运行。候选边界与每个候选的三个数值特征都是明确给定的:第一项是虚构基础分数,另外两项区分相容选择与竞争选择。因此,拟合演示的是目标函数及其导数,不是已经学会了理解语言。
初始最优集合选择Mina/ARG0、Jo/ARG2、a map/ARG1及on Monday/ARGM-TMP,总分11.5。竞争候选Jo/ARG0拥有最高单项分数5,选择它却会阻止更好的组合。50步确定性线搜索把这个例子的损失从0.823570降到0.007673。输出的边缘概率、手算例与完整损失曲线都可以独立核对。
"""Original span-selection SRL teaching model; gold predicate/candidates supplied."""
import json, math
import numpy as np
def validate(n, predicate, spans, scores, core):
if type(n) is not int or not 0 <= n <= 80: raise ValueError('token count must be 0..80')
if predicate is not None and (type(predicate) is not int or not 0 <= predicate < n):
raise ValueError('predicate index outside sentence')
if len(spans) > 2000 or len(core) > 8 or len(set(core)) != len(core):
raise ValueError('candidate/unique-role limit or duplicate core role')
if any(not isinstance(r,str) or not r for r in core): raise ValueError('invalid core role')
normalized=[]
for item in spans:
if len(item) != 3: raise ValueError('span needs start,end,role')
start,end,role=item
if type(start) is not int or type(end) is not int or not 0 <= start < end <= n:
raise ValueError('invalid half-open span')
if not isinstance(role,str) or not role: raise ValueError('invalid role')
if predicate is not None and start <= predicate < end: raise ValueError('argument includes predicate')
normalized.append((start,end,role))
if len(set(normalized)) != len(normalized): raise ValueError('duplicate labelled candidate')
scores=np.asarray(scores,dtype=float)
if scores.shape != (len(spans),) or not np.isfinite(scores).all() or np.any(np.abs(scores)>1e100):
raise ValueError('finite bounded score vector required')
return normalized,scores
def infer(n, predicate, spans, scores, core=('ARG0','ARG1','ARG2')):
spans,scores=validate(n,predicate,spans,scores,core)
bits={role:1<<i for i,role in enumerate(core)};states=1<<len(core)
starts=[[] for _ in range(n)]
for index,(start,end,role) in enumerate(spans): starts[start].append((index,end,bits.get(role,0)))
def edges(position,mask):
yield position+1,mask,0.,-1
for index,end,bit in starts[position]:
if not mask & bit: yield end,mask|bit,float(scores[index]),index
alpha=np.full((n+1,states),-np.inf);best=alpha.copy();alpha[0,0]=best[0,0]=0.
previous={}
for position in range(n):
for mask in range(states):
if not np.isfinite(alpha[position,mask]): continue
for end,next_mask,score,index in edges(position,mask):
alpha[end,next_mask]=np.logaddexp(alpha[end,next_mask],alpha[position,mask]+score)
value=best[position,mask]+score
if value > best[end,next_mask]:
best[end,next_mask]=value;previous[end,next_mask]=(position,mask,index)
logz=float(np.logaddexp.reduce(alpha[n]));final=int(np.argmax(best[n]));best_score=float(best[n,final])
selected=[];position=n;mask=final
while position:
position,mask,index=previous[position,mask]
if index>=0:selected.append(index)
selected.reverse()
beta=np.full_like(alpha,-np.inf);beta[n,:]=0.
for position in range(n-1,-1,-1):
for mask in range(states):
for end,next_mask,score,index in edges(position,mask):
beta[position,mask]=np.logaddexp(beta[position,mask],score+beta[end,next_mask])
marginals=np.zeros(len(spans))
for position in range(n):
for mask in range(states):
if not np.isfinite(alpha[position,mask]):continue
for end,next_mask,score,index in edges(position,mask):
if index>=0:marginals[index]+=math.exp(float(alpha[position,mask]+score+beta[end,next_mask]-logz))
return {'log_partition':logz,'best_score':best_score,'selected':selected,'marginals':marginals.tolist()}
def loss_gradient(n,predicate,spans,features,weights,gold,core=('ARG0','ARG1','ARG2')):
x=np.asarray(features,dtype=float);w=np.asarray(weights,dtype=float)
if w.ndim!=1 or not 1<=len(w)<=64 or x.shape!=(len(spans),len(w)):
raise ValueError('feature/weight shapes')
if not np.isfinite(x).all() or not np.isfinite(w).all():raise ValueError('finite parameters required')
result=infer(n,predicate,spans,x@w,core)
if any(type(i) is not int or not 0<=i<len(spans) for i in gold) or len(set(gold))!=len(gold):
raise ValueError('invalid gold indices')
chosen=sorted((spans[i] for i in gold),key=lambda s:s[0]);used=[]
for k,(start,end,role) in enumerate(chosen):
if k and start<chosen[k-1][1]:raise ValueError('overlapping gold arguments')
if role in core:
if role in used:raise ValueError('repeated gold core role')
used.append(role)
indicator=np.zeros(len(spans));indicator[list(gold)]=1
loss=result['log_partition']-float(indicator@(x@w))
gradient=x.T@(np.asarray(result['marginals'])-indicator)
return loss,gradient,result
def fit(example,steps=50):
if type(steps) is not int or not 0<=steps<=1000:raise ValueError('steps must be 0..1000')
w=np.array([1.,0.,0.]);trace=[]
args=(example['n'],example['predicate'],example['spans'],example['features'])
for step in range(steps+1):
loss,gradient,_=loss_gradient(*args,w,example['gold']);trace.append(loss)
if step==steps:break
rate=1.
for _ in range(40):
candidate=w-rate*gradient;new,_,_=loss_gradient(*args,candidate,example['gold'])
if new<=loss-1e-4*rate*float(gradient@gradient):w=candidate;break
rate*=.5
else:raise ArithmeticError('line search did not accept a step')
return w,trace
def demo():
spans=[(0,1,'ARG0'),(2,3,'ARG0'),(2,3,'ARG2'),(3,5,'ARG1'),(3,5,'ARG2'),(2,5,'ARG1'),(5,7,'ARGM-TMP')]
example={'tokens':['Mina','handed','Jo','a','map','on','Monday'],'n':7,'predicate':1,'spans':spans,
'features':[[4,1,0],[5,0,1],[3.5,1,0],[3,1,0],[3.8,0,1],[5,0,1],[1,1,0]],'gold':[0,2,3,6]}
initial=infer(7,1,spans,np.asarray(example['features'])@np.array([1.,0.,0.]))
weights,trace=fit(example);final=infer(7,1,spans,np.asarray(example['features'])@weights)
hand=infer(2,None,[(0,1,'ARG0'),(1,2,'ARG0'),(1,2,'ARG1')],np.log([2.,3.,5.]))
return {'example':example,'initial':initial,'final':final,'weights':weights.tolist(),'loss_trace':trace,
'hand':hand,'scope':'Given predicate and candidates; original linear constrained toy fit, not an automatic parser or corpus benchmark.'}
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
代码限制词元不超过80、候选不超过2,000、唯一角色不超过8种。它拒绝重复标注候选、覆盖谓词的区间、重叠金标、非有限分数及重复金标核心角色;允许重复修饰语及空答案。每步训练最多尝试40个步长,这个上限不保证收敛。
解码合法,仍然可能认错事件
候选列表遗漏a map时,任何分数都找不回它的精确边界。谓词检测、谓词词义选择、候选生成和语言表示分别会引入误差。断续论元、延续/指称标签、隐含参与者和允许重叠的标注规范,需要更丰富的输出空间。不能悄悄删掉这些评测样本,再把结果叫作一般SRL能力。
语义上说得通,也不证明事件真的发生了。角色可以描述否定、假设或引述的事件,下游信息抽取必须保留这些区别。PropBank的一般标注标签包含否定与模态;本文程序没有实现它们的解释。ArgM类别,§3
固定谓词身份后,精确的带角色区间评测会把“边界正确、角色错误”也判错。微平均精确率和召回率先合并计数,再求比例。报告时应说明谓词和边界是否给定、标签集是什么、如何划分测试集。
零分母的处理必须明确。给定候选上的分类准确率不能代替端到端的带标签区间F1。
先预测,再计算、修改与评测
- 在前面的主动句与被动句中,ARG0必须变成新的语法主语吗?
答案:不必。按本文传递框架,Mina仍然是给予者;语法主语变成地图,只认主语的规则会出错。角色编号要服从框架定义。
- 在三个候选的手算例中,取消ARG0唯一性,但保留不重叠约束,会改变什么?
答案:{a,b}变成合法集合,增加质量6,所以Z变成27。旧约束下它的概率严格为0。原金标集合的损失是log(21/10),放宽模型后改为log(27/10)。
- 在初始七词元例子中,只提高Jo a map/ARG1的分数。它何时胜过分别选择Jo/ARG2与a map/ARG1?
答案:两个短区间合计3.5+3=6.5。长区间超过6.5时赢得这项比较;等于6.5时并列,程序按确定性的平局规则选一个。Mina和时间区间对两种方案贡献相同。这种改动会让接收者角色消失,却不违反约束。
- 金标有四个带角色区间;系统也输出四个,其中三个完全正确,一个边界错误。F1是多少,还没有测到什么?
答案:TP=3、FP=1、FN=1,因此P=R=F1=0.75。这不能证明谓词检测能力、域外表现或所描述事件的真实性。
从句法线索到学习表示
Gildea和Jurafsky的2002年研究明确区分特征流程与论元边界假设;PropBank的2005年论文则说明标注规范和frameset为何是问题本身的一部分。它们分别支持本文的不同论点,都不是本文自定义角色掩码解码器的来源。统计特征 标注方案
扩展这个算例时,可以保持输出约定,把给定数值特征换成上下文编码器的表示,再把候选召回与标签选择分开评测。成分句法分析提供短语结构,依存句法分析提供词间关系;二者本身都没有完整指定谁承担了语义角色。信息抽取主题会进一步处理如何把语句变成结构化记录。
先判断,再看解释
两个不重叠候选都获得ARG0。本文解码器还要求什么?
学习目标
- 区分谓词词义、论元边界与语义角色。
- 推导相容标注区间上的归一化分布。
- 计算全局解码、区间边缘概率和线性打分梯度。
- 说明给定候选与精确区间评测的边界。
先修与延伸
查看知识关联图 →参考文献
- Automatic Labeling of Semantic Roles
Daniel Gildea and Daniel Jurafsky · 2002 - The Proposition Bank: An Annotated Corpus of Semantic Roles
Martha Palmer, Daniel Gildea and Paul Kingsbury · 2005
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-12 · Single AI author checked eight paired equations and four explained exercises against scoped Gildea/Jurafsky and PropBank passages. Given predicates and spans; optional unique core roles, repeated modifiers, non-overlap and predicate exclusion. Independent subset enumeration validates partition, marginals, maximum set and all linear-score gradients. Hand Z=21, marginals12/21,3/21,15/21 and alternative threshold6.5 checked. Toy training is not automatic full SRL or a corpus result.
- 单AI作者核对八组公式和四解释练习:限定Gildea/Jurafsky及PropBank段落;给定谓词区间、核心角色可选但唯一、修饰角色可重复、不重叠且排除谓词。独立集合枚举核分区函数、边缘、最优集合及全部梯度;核Z=21、三边缘和6.5切换阈值。玩具训练不冒充完整SRL或语料成绩。
- 四张原创计算SVG绑定双语MDX;十一项图检查、36组独立语言/宽度组合和四备用字体通过;本AI作者实际查看六张桌面/手机截图。完整页面验收另记,不称人工同行审校。
- 冻结后显示纠错:Astro实际预渲染失败后,转义正文集合边界;冻结原件、失败与前后补丁保存在editorial/corrections/011a-literal-sets,程序、公式和论述未变。修正后的渲染验收另记。
核对的来源位置:
- Automatic Labeling of Semantic Roles · Scoped text144–215,414–456,727–788: frame roles, supplied boundaries, phrase/position/voice/head features and split opening. Not full estimator, experiments or history.
- The Proposition Bank: An Annotated Corpus of Semantic Roles · Scoped §3 text231–355, rolesets/framesets and ArgM table; physical page5 (printed75) visually inspected. Verb-specific numbering; no full annotation or corpus reproduction.
相关主题