语义解析:答案正确,也可能来自错误程序
Semantic parsing
实现有界组合语法和类型执行器,推导从答案学习的目标,并揭示只监督答案留下的歧义。
semantic-parsing数对物体之前,先要选定问题的含义
一个虚构目录记录物体的颜色、形状、大小和重量。问“How many light objects?”,light既可能指重量轻,也可能指颜色浅。假定本任务的标注约定要求重量含义。如果目录碰巧有两个轻物体、两个浅色物体,两种解释都返回2;一个直接返回常数2的程序,也能通过这道测试。
语义解析(semantic parsing)把话语映射成机器可解释的意义表示,例如逻辑式、数据库查询或其他带类型程序。在给定世界中执行表示,就得到答案。句法分析描述语言结构;可执行解释还必须把词语连接到谓词、论元和运算。任务定义
对于范围很小的目录,带明确字段的受控表单是有用基线。语义解析器的价值在于让用户用语言组合请求,但要说明输入覆盖与歧义处理约定。本程序接受一种很小的类英语查询语法,保留词义候选并执行带类型表达式,不学习不受限的语言编码器。
Liang、Jordan与Klein研究以逻辑式为潜变量、从问题—答案对学习;Dong与Lapata研究用成对意义表示,学习从话语到逻辑式序列或树的神经映射。两种监督提供的证据不同:一个目标程序,比某个数据库里的一次答案透露更多结构。潜在逻辑式 成对意义表示
分开解析、执行和监督信号
设x为话语,z为候选程序,w为给定世界。带类型执行器确定它的指称,也就是计算得到的意义:
本例表达式先筛选物体ID集合,用交、并、补组合,再按需计数或判断非空。集合、整数和布尔值是不同输出类型。不能因为某种编程语言把true与整数1比较为相等,就在答案监督中把它们混为一谈。
受控语法规定not优先于and,and优先于or,括号可以改变顺序。例如pale or red and square选择浅色物体,以及同时红色且方形的物体;(pale or red) and square则只保留方形。词表为light保留两个谓词解释,不悄悄替用户选一个。
给定有限候选集合C(x),为每个程序分配特征向量,再用参数theta评分:
候选生成已经依赖输入。本例特征统计特定谓词选择、故意加入的常数和逻辑运算符,是一个小型共享评分模型,不是从原句学习的表示。DCS论文对自己的逻辑式使用log-linear分布;本例借鉴学习问题,却采用不同语法和精确枚举。模型与学习,印刷596页
若只知道答案y,就收集执行结果与它类型、数值都一致的候选,得到答案监督损失:
它奖励分配给任一可接受执行结果的概率,不一定奖励预期推理。如果没有候选返回答案,有限模型赋给这个答案的概率就是零。本实现明确报错,便于调查候选缺失或标注问题,不悄悄把样例算成已经学会。
对两个log-sum-exp项求导。令q只在可接受候选上重新归一化同一组分数:
梯度比较全部候选和答案相容候选下的特征期望。对于总在训练数据上得到相同答案的程序,它无法直接加以区分。若有完整逻辑式监督,则可以选定标注程序,优化该程序的概率。
世界A中,两种light谓词和可选常数程序都返回2,G等于整个候选集合:
所有参数设置都能拟合这道答案,包括强烈偏好常数的设置。世界B中,轻物体只有一个,浅色物体仍有两个;按照已声明的预期词义,正确答案变为1,常数和浅色解释都失败。把B及其答案加入训练,才提供了区分约束;加入之后,B就不再是留出评测数据。
预测还有一个选择:最佳单个程序,不一定给出按指称汇总后概率最大的答案:
若轻物体计数、浅色计数和常数2的概率为[3/7,2/7,2/7],最佳程序在B中回答1;后两个程序却共同给答案2贡献4/7概率,因此边缘答案预测返回2。DCS论文描述了对潜在逻辑式求和的预测方式,比较时必须说明采用哪条决策规则。训练后的预测
解析受控表达式,逐个检查候选
完整原创程序使用Python 3.12和NumPy 1.26.4。输入以which、how many或are any开头,后接受支持的形容词表达式及objects。这是声明的命令语法,不代表理解任意英语问题。未知字符、词语和不完整表达式会被拒绝,而不是悄悄丢掉。
"""Original bounded grammar, typed executor and denotation-supervised parser.
English toy queries use a supplied lexicon. No neural encoder, SQL service or
reproduction of DCS/SEQ2TREE. Optional constant programs expose spurious fits.
"""
import json
import re
import numpy as np
FIELDS=('color','shape','size','weight')
LEXICON={'red':[('color','red')],'blue':[('color','blue')],'pale':[('color','pale')],
'light':[('weight','light'),('color','pale')],'heavy':[('weight','heavy')],
'round':[('shape','circle')],'square':[('shape','square')],
'small':[('size','small')],'large':[('size','large')]}
FEATURES=('color:pale','weight:light','literal','other','and','or','not')
def programs(query,constants=False):
if not isinstance(query,str) or len(query)>500 or not re.fullmatch(r'[A-Za-z ()]+\??',query):raise ValueError('Use the declared English query grammar')
words=re.findall(r'[a-z]+|[()]',query.lower())
if len(words)>40:raise ValueError('Query token cap exceeded')
if words[:2]==['how','many']:kind='count';words=words[2:]
elif words[:1]==['which']:kind='select';words=words[1:]
elif words[:2]==['are','any']:kind='exists';words=words[2:]
else:raise ValueError('Unknown question form')
if not words or words[-1]!='objects':raise ValueError('Queries must end in objects')
words=words[:-1];position=0
def combine(op,left,right):
result=[(op,a,b) for a in left for b in right]
if len(result)>64:raise ValueError('Ambiguity cap exceeded')
return result
def atom(depth):
nonlocal position
if depth>12 or position>=len(words):raise ValueError('Incomplete or excessively nested expression')
word=words[position];position+=1
if word=='not':return [('not',x) for x in atom(depth+1)]
if word=='(':
result=expression(depth+1)
if position>=len(words) or words[position]!=')':raise ValueError('Unclosed parenthesis')
position+=1;return result
if word not in LEXICON:raise ValueError('Unknown adjective')
return [('eq',field,value) for field,value in LEXICON[word]]
def term(depth):
nonlocal position
left=atom(depth)
while position<len(words) and words[position]=='and':
position+=1;left=combine('and',left,atom(depth))
return left
def expression(depth):
nonlocal position
left=term(depth)
while position<len(words) and words[position]=='or':
position+=1;left=combine('or',left,term(depth))
return left
forms=expression(0)
if position!=len(words):raise ValueError('Unexpected trailing tokens')
result=[(kind,p) for p in forms]
if constants:
if kind!='count':raise ValueError('Spurious integer constants are only defined for count questions')
result.append(('literal',2))
return result
def world(rows):
rows=[dict(r) for r in rows]
if not 1<=len(rows)<=32:raise ValueError('Use 1..32 invented objects')
if any(set(r)!=set(FIELDS)|{'id'} or any(not isinstance(v,str) or not v or len(v)>40 for v in r.values()) for r in rows):raise ValueError('Complete short string-valued records required')
if len({r['id'] for r in rows})!=len(rows):raise ValueError('Object IDs must be unique')
return rows
def result_type(p,depth=0):
if not isinstance(p,tuple) or not p or depth>20:raise ValueError('Invalid bounded logical form')
op=p[0]
if op=='eq' and len(p)==3 and p[1] in FIELDS and isinstance(p[2],str):return 'set'
if op=='literal' and len(p)==2 and type(p[1]) is int and 0<=p[1]<=32:return 'int'
if op in ('not','select','count','exists') and len(p)==2 and result_type(p[1],depth+1)=='set':
return {'not':'set','select':'set','count':'int','exists':'bool'}[op]
if op in ('and','or') and len(p)==3 and result_type(p[1],depth+1)==result_type(p[2],depth+1)=='set':return 'set'
raise ValueError('Ill-typed or unsupported logical form')
def execute(p,rows):
rows=world(rows);result_type(p);universe=frozenset(r['id'] for r in rows)
def visit(p):
op=p[0]
if op=='eq':return frozenset(r['id'] for r in rows if r[p[1]]==p[2])
if op=='literal':return p[1]
if op=='not':return universe-visit(p[1])
if op=='and':return visit(p[1])&visit(p[2])
if op=='or':return visit(p[1])|visit(p[2])
if op=='select':return visit(p[1])
if op=='count':return len(visit(p[1]))
return bool(visit(p[1]))
return visit(p)
def features(forms):
def visit(p,x):
if p[0]=='eq':key=p[1]+':'+p[2];x[FEATURES.index(key) if key in FEATURES else 3]+=1
elif p[0]=='literal':x[2]+=1
else:
if p[0] in FEATURES:x[FEATURES.index(p[0])]+=1
for child in p[1:]:visit(child,x)
rows=[]
for p in forms:
result_type(p);x=np.zeros(len(FEATURES));visit(p,x);rows.append(x)
if not 1<=len(rows)<=65:raise ValueError('Use a bounded nonempty candidate list')
return np.array(rows)
def distribution(theta,forms):
theta=np.asarray(theta,float)
if theta.shape!=(len(FEATURES),) or not np.isfinite(theta).all() or (np.abs(theta)>100).any():raise ValueError('Bounded feature weights required')
x=features(forms);scores=x@theta;shift=scores.max();weights=np.exp(scores-shift);z=weights.sum()
return dict(features=x,probabilities=weights/z,log_partition=float(shift+np.log(z)),scores=scores)
def equal(a,b):return type(a) is type(b) and a==b
def loss_grad(theta,forms,rows,answer):
d=distribution(theta,forms);mask=np.array([equal(execute(p,rows),answer) for p in forms])
if not mask.any():raise ValueError('The candidate set contains no correct typed denotation')
selected=d['scores'][mask];maximum=selected.max();w=np.exp(selected-maximum);posterior=w/w.sum()
gradient=d['probabilities']@d['features']-posterior@d['features'][mask]
return dict(loss=float(d['log_partition']-maximum-np.log(w.sum())),gradient=gradient,correct_candidates=np.flatnonzero(mask).tolist())
def predict(theta,forms,rows):
d=distribution(theta,forms);index=int(np.argmax(d['scores']));groups={}
for p,prob in zip(forms,d['probabilities']):
value=execute(p,rows);key=(type(value).__name__,tuple(sorted(value)) if isinstance(value,frozenset) else value)
groups[key]=groups.get(key,0.)+float(prob)
answers=[dict(type=key[0],answer=list(key[1]) if key[0]=='frozenset' else key[1],probability=value) for key,value in groups.items()]
best=max(answers,key=lambda x:x['probability'])
value=execute(forms[index],rows)
return dict(best_program=forms[index],program_answer=sorted(value) if isinstance(value,frozenset) else value,
marginal_answer=best['answer'],answer_distribution=answers,probabilities=d['probabilities'].tolist())
def demo():
a=world([dict(id='a',color='pale',shape='circle',size='small',weight='light'),
dict(id='b',color='pale',shape='square',size='large',weight='light'),
dict(id='c',color='red',shape='circle',size='large',weight='heavy')])
b=[dict(x) for x in a];b[1]['weight']='heavy'
forms=programs('how many light objects?',constants=True);initial=np.array([1.,0.,2.,0.,0.,0.,0.])
before=loss_grad(initial,forms,a,2);theta=initial.copy();curve=[]
for step in range(101):
first=loss_grad(theta,forms,a,2);second=loss_grad(theta,forms,b,1)
curve.append((first['loss']+second['loss'])/2)
if step<100:theta-=.4*(first['gradient']+second['gradient'])/2
marginal=np.zeros(7);marginal[1]=np.log(1.5)
return dict(query='how many light objects?',forms=forms,world_a=a,world_b=b,
initial_weights=initial.tolist(),initial_training_loss=before['loss'],initial_training_gradient=before['gradient'].tolist(),
initial_on_a=predict(initial,forms,a),initial_on_b=predict(initial,forms,b),
training_loss=curve,trained_weights=theta.tolist(),trained_on_b=predict(theta,forms,b),
marginal_vs_program=predict(marginal,forms,b),
conditions='Handwritten lexical candidates; an optional constant2 is deliberately spurious. World B becomes training data in the second experiment, not a held-out generalization claim.')
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
带类型执行器不会运行用户提供的Python,也不会向服务发送SQL,只读取有界内存目录。额外常数候选只在计数问题中加入,用来展示碰巧答对的拟合,不把它说成话语的合理语义解释。
初始特征权重偏好常数2。在A上的训练损失和梯度都为零,同一个程序却在B上给出不符合预期含义的答案。第二个实验用A和B共同训练100次更新,在B上选中重量解释。输出保留两个实验,以及单独的边缘答案/最佳程序比较,明确展示监督信号发生了变化。
独立检查覆盖运算优先级、否定与括号、集合/整数/布尔的严格区分、全部特征参数的中心差分、正确候选缺失和候选顺序变化。改变浮点求和顺序可能影响末尾几位,因此概率比较使用明确容差,答案身份仍精确比较。
候选生成会随词义歧义和组合而增长。本程序把普通候选限制为64个,最多另加一个常数;查询最多40词,解析深度12,世界最多32个物体。若候选数C、树大小K、记录数R,简单集合执行器约为O(CKR),F个特征的构造与评分另需O(C(K+F))。这些边界描述的是本枚举器,不是DCS或神经树解码器。
执行成功,弱于语义泛化
程序类型正确,仍可能绑定错误关系、选择错误词义或遗漏条件。类型检查能排除部分非法组合,却不能提供用户的真实意图。同样,在一个世界中精确答对,也可能接受常数或其他偶然解。
评测时同时说明输出约定和监督方式。程序精确匹配可能拒绝语义等价的表达式;执行准确率可能接受只在当前数据库碰巧相同的程序。改变记录的反事实世界有助于暴露后者,但新增训练世界必须与泛化评测世界分开。
数据划分还要考虑模板、模式和实体重合。随机拆话语,可能把几乎一样的程序放在两边;组合泛化或新模式划分提出的是更难的问题。说明候选生成或调参期间能否看到实体、数据模式、可执行环境和示例。本例的目录模式及词义候选全部事先给定。
神经序列或树解码器可以扩大语言覆盖,也会引入搜索、语法和事实对应方面的错误。历史lang2logic实现提供具体的序列/树与注意力配置,可用于了解那条研究路线;它不是本程序的依赖。神经表示映射 固定版本实现
检查含义,不只检查答案字符串
-
为什么执行器必须区分整数答案1和布尔true?
答案:它们回答不同类型的问题:计数与存在判断。互相接受会让错误类型的程序看起来正确,本例同时比较类型和值。
-
世界A中三个候选都返回2。只用答案似然,能学到哪个才是预期程序吗?
答案:单凭这条样例不能。任意参数下,可接受候选的总概率都为1,损失和梯度都为零。需要能区分的世界、程序标注或其他监督。
-
候选概率为[3/7,2/7,2/7],答案分别为[1,2,2]。最佳程序和边缘答案预测各返回什么?
答案:最佳程序返回1;边缘答案返回2,因为后两个程序合计贡献4/7。比较准确率前应声明预测规则。
-
用世界B及答案1重新训练后,在B上答对能证明留出泛化吗?
答案:不能,B已经提供训练证据。应把它报告为拟合改善,再用未接触的新世界或新组合评测,否则测试已经成为学习过程的一部分。
观察到逻辑式以后,学习问题改变了什么?
DCS工作使用潜在表示和答案监督,在自身语义形式中近似搜索候选;神经注意力工作从成对意义表示学习序列或树输出。应把表示、监督和解码假设一起读,不能因为都报告答案分数,就把任务设置视为等价。DCS学习与预测 神经注意力
本篇受控语法、特征模型、执行器和世界用精确小计算拆开这些区别。扩展到真实问题,需要更好的覆盖与解释证据,同时保留合法程序、正确执行和预期含义之间的区分。
先判断,再看解释
训练世界中所有候选都返回2,只用答案似然能确定什么?
学习目标
- 追踪受控话语、逻辑式与带类型执行。
- 推导答案监督边缘损失及特征梯度。
- 解释正确指称为何仍不能识别程序。
- 区分最佳程序和边缘答案预测。
先修与延伸
查看知识关联图 →参考文献
- Learning Dependency-Based Compositional Semantics
Percy Liang, Michael I. Jordan, Dan Klein · 2011 - Language to Logical Form with Neural Attention
Li Dong, Mirella Lapata · 2016 - Language to Logical Form: pinned implementation README and MIT license
Li Dong · 2019
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-13 · Single AI author checked a controlled grammar and typed execution against scoped Liang answer marginalization and Dong neural semantic parsing context. Six paired equations and four explained exercises: program normalization, denotation marginal likelihood, expected-feature gradient, finite differences, spurious constants and program versus answer MAP. A and B are both training worlds after fitting; this is not DCS or neural parsing reproduction.
- 检查布尔与整数类型区分、有限语法限制、运算优先级、伪程序答案监督、独立特征梯度差分与答案边缘化。原概率精确比较及后续零损失断言修正保留,程序不改。
- 四张计算SVG绑定真实双语程序;本组九项数值/编码检查、24组语言/宽度及四字体检查通过,AI作者实际查看八张截图。冻结前检查普通正文AST;完整文章页面验收另记,不称人工同行审校。
核对的来源位置:
- Learning Dependency-Based Compositional Semantics · Abstract and visually read PDF page7, printed596: type filtering, log-linear forms, marginal answer supervision, approximate candidate search and answer marginal prediction. Original finite grammar here, not DCS replication.
- Language to Logical Form with Neural Attention · Title/authors, abstract and opening introduction layout12–37: attention encoder-decoder with sequence/tree meaning outputs; official code link291–292. Detailed decoder and experiments not reproduced.
- Language to Logical Form: pinned implementation README and MIT license · Commit 2019-11-09; README 1–25 and visible mode lines 41–74, full MIT license read. Historical Torch7 sequence/tree modes; no environment changes or upstream execution.
相关主题