语言模型平滑:概率分给了谁
Smoothing language models
推导加k、插值、折扣与续接质量,区分归一化似然、未见词支持和回退分数。
smoothing-language-models没见过的词对,不一定是不可能的句子
虚构训练集包含八遍 harbor quay,再加 old route、new route、coastal route 和 old bridge。bigram最大似然模型给 new quay 的概率是零:训练时 new 后面只出现过 route。但两个词都见过,这种缺失组合恰恰可能只是有限样本没有收集到的事件。
平滑在明确模型下重新分配概率,让观测次数为零不必意味着概率为零。它从已见组合中让出部分拟合能力,给其他组合分配支持。如何选择接收概率的分布很关键:quay 出现八次,却始终跟在 harbor 后面;route 只出现三次,却跟过三个不同词。面对新上下文,谁更适合作为续接?
这个问题将我们从加k和插值引向利用续接信息的Kneser-Ney平滑。本文使用能精确核对概率质量的小bigram模型。n-gram语言模型介绍此前的计数和困惑度约定;这里重点讲计数之后怎样改变概率。方法依据是对SLP草稿和Chen–Goodman报告的限定核读。SLP:插值与回退 TR-10-98:平滑定义
分出去的概率,必须先说明从哪里来
声明预测事件和词表
历史h指前一个词元。每句以一个BOS历史开始,以一次EOS预测结束。BOS不作为预测目标,EOS和UNK包含在固定目标词表里。只由训练数据决定的 min_count 控制哪些低频词映射为UNK。默认阈值1时,12句话产生36个预测事件,目标词表V=9,共有12种已见bigram。
令C(h,w)统计转移次数,N_h为该历史下的次数之和,T_h为不同已见后继数,M为总事件数:
N_h>0时,最大似然估计为C(h,w)/N_h。本文unigram基分布p_0(w)为目标总计数C(w)/M,包括EOS事件。每个条件概率模型都必须在同一个目标词表上求和为1。未出现过的历史没有MLE分母,程序会拒绝计算它的MLE分布。
加k为整个词表的正下限付出代价
α>0时,加k平滑在代码中名为 add-k,向每个目标加入相同伪计数:
分子相加得到N_h+αV,因此归一化成立。连未见历史也能得到均匀分布。这里必须固定V,因为改变词表会改变每个分母。本例 old 的N_h=2、T_h=2,后接 route 和 bridge 各一次。α=0.5时分母为6.5,每个已见目标获得3/13,其余七个未见目标各得1/13,总和为1。
α固定时,增大V会加入更多伪计数总量。因此“每项加一”可能把分布显著压平。在声明的有限词表上给出正下限,也不等于给所有词表外拼写分别分配概率;它们仍然映射到UNK。
插值混合完整分布
本实验的Jelinek–Mercer式线性插值使用0到1之间的固定权重λ:
两个分量各自和为1,因此混合后也归一化。已见事件同样能收到低阶质量,并非只有高阶计数为零才查看低阶模型。对已见历史,权重1返回MLE,权重0返回unigram基分布;对从未出现的历史,本文明确规定直接使用基分布。插值权重应通过开发数据选择,而非通过最终报告的测试集选择。SLP:§3.6.3
Witten-Bell用不同已见后继数确定随历史变化的混合权重:
高阶部分总质量为N_h/(N_h+T_h),剩余T_h/(N_h+T_h)交给低阶部分。相对于观测总次数,不同后继越多,基分布所得权重越大。这里使用插值形式和已声明的unigram基分布;未见历史仍按本文政策使用基分布。TR-10-98:§2.5,式14—17
绝对折扣从每种已见词对扣除固定量
对0到1之间的单一折扣D和已见历史:
正计数是至少为1的整数,因此每种已见词对恰好损失D个计数,即D/N_h概率,端点D=1也适用。T_h种词对共让出DT_h/N_h质量,基分布项恰好补回这部分。证明依赖给定折扣范围,任意D>1会使这个简单的扣除质量表达式不再成立。TR-10-98:§2.6,式18—20
old 后D=0.5时,总共让出0.5概率。route 从折扣计数获得1/4,再从unigram基分布得到(1/2)(3/36),合计7/24。未见组合中的 quay 获得(1/2)(8/36)=1/9。此处Witten-Bell恰好相同,因为它的高阶权重也是一半;两公式并非对每张计数表都相等。
Kneser-Ney改变低阶模型数的东西
高频词可能只是反复出现在一个固定上下文。续接分布统计不同前驱种类,而非原始出现次数:
每种已见bigram都为分母贡献一次,也为其目标的分子贡献一次,因此这个分布和为1。本例 quay 有一种不同前驱,route 有三种,续接概率分别为1/12、3/12,正好反转了unigram频率8/36、3/36的排序。
将绝对折扣的基分布换成该续接分布:
old 后D=0.5时,route 得到1/4+(1/2)(3/12)=3/8,quay 得到(1/2)(1/12)=1/24。这是单折扣、插值形式的bigram Kneser-Ney,未见历史回退到续接分布;不是高阶递归实现、原始仅回退形式,也不是采用计数相关折扣的修改版Kneser-Ney。TR-10-98:§2.7,插值式22
还能做一次有用的边缘核对。令H_w为w的不同前驱数,B为bigram总种类数。以N_h/M为权重对已见历史平均,折扣部分贡献[C(w)−D H_w]/M,再分配部分贡献(D B/M)(H_w/B),两者的扣减项抵消。因此:
恒等式使用单一固定D、已声明的边界计数和经验历史权重;不是说每种平滑方法或每个未见上下文都保持这种边缘分布。测试用精确分数检查D=0、0.25、0.5、1时的全部目标词。
回退分数不一定是概率
本文bigram Stupid Backoff对已见词对保留MLE分数,对未见词对使用缩放的unigram分数:
还没加入任何未见项的正分数,已见项就已经和为1。old 后已见目标是 route 与 bridge,它们的unigram质量合计4/36。β=0.4时,全部分数和为1+0.4(32/36)=61/45。历史完全未见时,本文规定的回退分数总质量为0.4。取对数无法让这两个和变成1,因此评估器拒绝用该方法计算概率困惑度。把分数另行归一化,会定义另一个模型。SLP:§3.6.4
Good-Turing不只是向每个计数代入比例
令n_r为恰好出现r次的已见bigram种类数。原始Good-Turing调整计数表达式与未见质量估计为:
本文全局诊断得到n_1=7、n_2=1、n_3=1、n_8=3,所以n_1/M=7/36;r=1、2对应的原始调整计数为2/7、3。r=3或8时,下一频数桶缺失。程序标记这个缺口,不会把高频类型的概率置零。可用估计器还需处理频数的频数噪声、未见类型和条件归一化;该诊断没有补齐这些步骤,不是完整Good-Turing或Katz模型。TR-10-98:§2.2
先核对质量,再计算困惑度
把完整代码存为 smoothing.py,执行 python3 smoothing.py。只依赖标准库,仓库检查使用Python 3.12.4。Fraction 保持小模型计数和概率精确;浮点参数按能往返还原它的十进制写法解释,因此输入0.4表示2/5。对数和打印的小数仍然使用浮点计算。
"""Original exact small-bigram smoothing laboratory.
Count tables share one vocabulary and one EOS per sentence. Fractions keep mass
accounting exact for small examples; this is not an efficient production LM.
Stupid Backoff is exposed as a score and is rejected by probability evaluation.
"""
from collections import Counter, defaultdict
from fractions import Fraction
import json
import math
BOS='<s>';EOS='</s>';UNK='<unk>'
METHODS=('mle','add-k','interpolation','witten-bell','absolute','kneser-ney','stupid-backoff')
def sentence(row):
if not isinstance(row,(list,tuple)) or any(not isinstance(w,str) or not w or w in (BOS,EOS,UNK) or any(0xD800<=ord(c)<=0xDFFF for c in w) for w in row):
raise ValueError('Supply nonempty Unicode tokens without reserved markers or surrogates')
return list(row)
def corpus(rows):
if not isinstance(rows,(list,tuple)) or not rows:raise ValueError('A nonempty sentence collection is required')
return [sentence(row) for row in rows]
def number(value,low=0,high=None,strict_low=False):
if isinstance(value,bool) or not isinstance(value,(int,float)) or (isinstance(value,float) and not math.isfinite(value)):
raise ValueError('Finite numeric parameter required')
if value<low or (strict_low and value==low) or (high is not None and value>high):raise ValueError('Parameter outside declared bounds')
# A supplied float is interpreted by its round-trip decimal spelling.
return Fraction(str(value))
def fit(rows,min_count=1):
rows=corpus(rows)
if type(min_count) is not int or min_count<1:raise ValueError('Positive integer min_count required')
frequency=Counter(w for row in rows for w in row);kept={w for w,c in frequency.items() if c>=min_count}
vocabulary=tuple(sorted(kept|{EOS,UNK}));counts=defaultdict(Counter);unigram=Counter();predecessors=defaultdict(set)
for row in rows:
mapped=[w if w in kept else UNK for w in row];previous=BOS
for word in mapped+[EOS]:
counts[previous][word]+=1;unigram[word]+=1;predecessors[word].add(previous);previous=word
total=sum(unigram.values());types=sum(len(c) for c in counts.values())
return {'vocabulary':vocabulary,'counts':dict(counts),'unigram':dict(unigram),
'predecessor_types':{w:len(predecessors[w]) for w in vocabulary},'bigram_types':types,
'events':total,'sentences':len(rows),'min_count':min_count}
def history_key(model,history):
if history is None or history==BOS:return BOS
if not isinstance(history,str) or not history or history==EOS or any(0xD800<=ord(c)<=0xDFFF for c in history):
raise ValueError('History is one pre-EOS token, or None for BOS')
return history if history in model['vocabulary'] else UNK
def probabilities(model,history,method='kneser-ney',alpha=.5,weight=.5,discount=.5,backoff=.4):
if method not in METHODS:raise ValueError('Unknown smoothing method')
a=number(alpha,strict_low=True);mix=number(weight,high=1);d=number(discount,high=1);factor=number(backoff,high=1)
h=history_key(model,history);row=model['counts'].get(h,{});n=sum(row.values());t=len(row);v=model['vocabulary']
base={w:Fraction(model['unigram'].get(w,0),model['events']) for w in v}
continuation={w:Fraction(model['predecessor_types'][w],model['bigram_types']) for w in v}
if method=='add-k':return {w:(row.get(w,0)+a)/(n+a*len(v)) for w in v}
if not n:
if method=='mle':raise ValueError('No MLE distribution for an unobserved history')
if method=='stupid-backoff':return {w:factor*base[w] for w in v}
return continuation if method=='kneser-ney' else base
high={w:Fraction(row.get(w,0),n) for w in v}
if method=='mle':return high
if method=='interpolation':return {w:mix*high[w]+(1-mix)*base[w] for w in v}
if method=='witten-bell':return {w:Fraction(row.get(w,0),n+t)+Fraction(t,n+t)*base[w] for w in v}
if method=='stupid-backoff':return {w:high[w] if row.get(w,0) else factor*base[w] for w in v}
lower=continuation if method=='kneser-ney' else base
return {w:max(Fraction(row.get(w,0))-d,Fraction(0))/n+d*t/n*lower[w] for w in v}
def inspect(model,history,method,**options):
p=probabilities(model,history,method,**options);mass=sum(p.values());h=history_key(model,history)
return {'history':h,'method':method,'probabilities_or_scores':{w:float(v) for w,v in p.items()},
'exact_values':{w:str(v) for w,v in p.items()},'total_mass':float(mass),'exact_mass':str(mass),
'is_probability_model':method!='stupid-backoff','normalized_at_this_history':mass==1,
'numeric_underflow_targets':[w for w,v in p.items() if v>0 and float(v)==0]}
def evaluate(model,rows,method='kneser-ney',**options):
if method=='stupid-backoff':raise ValueError('Unnormalized Stupid Backoff scores are not probability perplexities')
rows=corpus(rows);terms=[];zero_events=[];events=0
for index,row in enumerate(rows):
mapped=[w if w in model['vocabulary'] else UNK for w in row];events+=len(mapped)+1;h=BOS
for position,w in enumerate(mapped+[EOS]):
p=probabilities(model,h,method,**options)[w]
if p==0:zero_events.append({'sentence':index,'event':position,'reason':'zero_target'});break
terms.append(math.log(p.numerator)-math.log(p.denominator));h=w
if zero_events:return {'status':'zero_probability','events':events,'mean_nll_nats':None,'perplexity':None,'zero_events':zero_events}
loss=-math.fsum(terms)/events
try:pp=math.exp(loss)
except OverflowError:pp=None
return {'status':'finite_log_probability','events':events,'mean_nll_nats':loss,'perplexity':pp,'perplexity_overflow':pp is None}
def tune_interpolation(model,development,grid=(0.,.25,.5,.75,1.)):
development=corpus(development)
if not isinstance(grid,(list,tuple)) or not grid:raise ValueError('Supply a nonempty candidate-weight list')
trials=[]
for weight in grid:
number(weight,high=1);score=evaluate(model,development,'interpolation',weight=weight)
trials.append({'weight':weight,'evaluation':score})
finite=[(t['evaluation']['mean_nll_nats'],i) for i,t in enumerate(trials) if t['evaluation']['status']=='finite_log_probability']
if not finite:raise ValueError('No finite development likelihood on this grid')
_,index=min(finite)
return {'weight':trials[index]['weight'],'trials':trials,'scope':'Finite declared grid, chosen by development event-weighted loss; not a continuous optimizer or test-set selection.'}
def good_turing_diagnostic(model):
buckets=Counter(c for row in model['counts'].values() for c in row.values());entries=[]
for r,nr in sorted(buckets.items()):
following=buckets.get(r+1,0)
entries.append({'count':r,'types':nr,'next_types':following,
'raw_adjusted_count':float(Fraction((r+1)*following,nr)) if following else None,
'status':'raw_ratio' if following else 'next_bucket_missing'})
return {'count_of_counts':entries,'unseen_mass_estimate':float(Fraction(buckets.get(1,0),model['events'])),
'scope':'Global observed-bigram count-of-counts diagnostic only. Missing next buckets are flagged, not assigned zero probability. No smoothed frequency-of-frequency model, unseen-type allocation or complete Katz implementation.'}
def demo():
train=[['harbor','quay'] for _ in range(8)]+[['old','route'],['new','route'],['coastal','route'],['old','bridge']]
development=[['new','quay'],['old','route']];test=[['coastal','bridge']];model=fit(train)
chosen=tune_interpolation(model,development)
rows={method:inspect(model,'old',method) for method in METHODS}
scores={method:{'known':evaluate(model,[['harbor','quay']],method),
'recombined':evaluate(model,[['new','quay']],method),
'oov':evaluate(model,[['novel','route']],method)} for method in METHODS if method!='stupid-backoff'}
rare=fit(train,min_count=2)
return {'training':train,'events':model['events'],'vocabulary':list(model['vocabulary']),'bigram_types':model['bigram_types'],
'unigram_counts':model['unigram'],'predecessor_types':model['predecessor_types'],
'after_old':rows,'scores':scores,'good_turing':good_turing_diagnostic(model),
'development_selection':{'development':development,'selection':chosen,'test':test,
'test_after_selection':evaluate(model,test,'interpolation',weight=chosen['weight'])},
'trained_unk':{'vocabulary':list(rare['vocabulary']),'unk_targets':rare['unigram'].get(UNK,0),
'oov_score':evaluate(rare,[['novel','route']],'kneser-ney')},
'scope':'Original small bigram experiment with exact rational mass accounting. Base is unigram MLE, KN is single-discount interpolated bigram KN, not modified KN. Reserved but unseen UNK can still have zero mass. No benchmark claim.'}
if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=False,indent=2,allow_nan=False))
默认 after_old 输出使用λ=0.5、α=0.5、D=0.5、β=0.4,每行都报告分数形式、小数形式及总和。is_probability_model 区分已声明的概率模型与回退分数;分数即使恰好在一个历史下和为1,也不能据此认证所有历史都形成分布。
已见句子 harbor quay 的MLE概率为(8/12)×1×1=2/3。两个词加EOS共有三个事件,因此困惑度为(3/2)^(1/3)。对成功完成的E个概率预测事件,程序计算:
重新组合的 new quay 具有零MLE概率;在本例非端点参数下,其他五种概率平滑方法都给它正概率。novel route 暴露另一问题:默认词表预留UNK,却没有训练过任何UNK事件,其unigram和续接质量仍为零,因此演示的概率方法中,除加k外都仍给该句零概率。预留符号不等于学到了支持它的概率。
以 min_count=2 重拟合后,三个只出现一次的词 new、coastal、bridge 成为UNK训练目标,产生三个UNK目标,词表缩为六项,陌生句子的KN似然变为正数。这改变了模型词表与计数,不能把不同词元映射政策下的困惑度当作在评分同一组事件,直接横向比较。
真实概率为零时,评估器报告 zero_probability,数值NLL和困惑度字段置为null,不输出非标准JSON无穷大。非零时按log(分子)−log(分母)求分数的对数。正有理数转成显示浮点值可能下溢到零,这种计算却仍能保留有限对数;numeric_underflow_targets 标出二者区别。很大的有限NLL在指数化时仍可能溢出,另有独立标记。
开发集为 new quay、old route,测试集为 coastal bridge。程序只比较λ∈[0,0.25,0.5,0.75,1],选择按预测事件加权的开发损失最小者,并列时按原网格顺序决定。选中λ=0.75后,再按该选择对测试集评分一次。这是有限网格搜索,不是连续最优解;整个过程中训练计数固定。SLP:开发集插值选择
计算范围
输入词元数为T、句子数为S、不同已见bigram数为B时,在词元比较成本有限的假设下,拟合平均需要O(T + S + V log V)工作:计数包括每句一次EOS,词表还需排序,除复制输入外保存O(B+V)计数和类型统计。每次概率调用都构造完整V项基分布、续接分布及输出字典。因此评分E个事件需要O(EV)量级的有理数操作,还包括扫描句子及求选中历史计数之和的成本。诊断输出也会物化分布。这种设计优先方便检查,而非提高吞吐量。
Fraction运算不是常数时间,分子分母的位数影响乘除、约分和对数转换成本。小模型质量精确,不意味着大语料的精确算术高效。生产实现可以缓存分布或仅计算所需目标,处理更高阶及稀疏存储,并验证自己的浮点契约。
有支持与拟合得好,是两件事
归一化分布仍可能给所需事件零概率,全正分布也可能把续接词排序排错。质量和为1或玩具困惑度有限,都不能证明语言质量有用。比较概率损失时,必须固定词表构造、边界政策、语料规模和评估事件。
这里的unigram基分布包括EOS;未知拼写合并为单个符号,不是开放词表模型。常数D的KN例子有明确范围,Good-Turing表也不能代替缺失的平滑、回退分配或修改版KN折扣。应在声明的设置下用留出结果选择方法。本文采用报告中的定义,没有核读或复现其性能排名与语音错误率。
把少掉的概率算清楚
1. 理解:未见词对与未见词
默认词表下,为什么 new quay 可以得到正KN概率,novel route 却仍为零?
答案:quay 是已见目标,续接计数为正,因此折扣可给新的词对组合分配质量。novel 映射到预留UNK,而阈值1时UNK的续接及unigram计数均为零,演示的KN模型没有质量传给该目标。加k通过词表范围的下限赋予质量,把低频词训练成UNK则通过另一机制改变支持范围。
2. 手算:一半质量分到哪里
历史为 old、D=0.5时,用给定计数求绝对折扣和KN的 route、quay 概率。
答案:N_h=T_h=2,低阶模型获得DT_h/N_h=1/2。route 的高阶质量是(1−0.5)/2=1/4。绝对折扣给它1/4+(1/2)(3/36)=7/24,未见 quay 得到(1/2)(8/36)=1/9。KN将低阶质量换成3/12和1/12,得到3/8和1/24。高阶折扣相同,结果差异来自再分配。
3. 反例:对数分数不是对数概率
证明β=0.4的Stupid Backoff在 old 后不归一化。平均负对数分数能修复它吗?Good-Turing下一频数桶缺失又该怎样处理?
答案:已见词对分数和为1,未见目标的基分布质量为32/36,所以总和为1+(2/5)(32/36)=61/45。取对数和平均不会补齐模型归一化。另一方面,Good-Turing缺失下一桶使原始比例估计不可靠,本文诊断将其标记,不把已见类型概率置零。两种问题都不会因为给结果起名“困惑度”而得到修复。
4. 迁移:在同一组事件上比较模型
你在给定开发网格选中λ=0.75,后来发现另一个λ给测试句的分数更好,能否把新选择报告为未碰过测试集的表现?能否不加说明地直接比较UNK阈值2与阈值1的困惑度?
答案:再次根据测试集选择,会把测试集变成选择数据;应另留测试集估计最终表现,或如实说明选择过程。改变UNK阈值会改变词表、计数和评分符号,应记录映射,不能把不同事件空间当作同条件困惑度竞赛。这两项调整都不只是现有模型的数值修正。
分清方法,也分清发表版本
本文使用SLP的2026年8月19日章节草稿,限定阅读覆盖插值、开发集权重,以及Stupid Backoff分数和概率的区别。Chen–Goodman PDF是TR-10-98技术报告,封面写1998年8月,内页标题日期为1998年7月24日,不能用托管出版页面的1996标签给这份PDF重新署年。本文没有核读1996年会议版本和1999年期刊版本。
报告核读覆盖Good-Turing讨论、Witten-Bell、绝对折扣及续接定义,并实际查看第13—17页核对公式;没有核读实验比较或修改版KN章节。小语料、精确有理数实现、数值例子和反例都是原创。若要扩展实验,先明确高阶递归、折扣估计器、未知词政策和共同评测语料,再与另行核验的参考输出比较。
先判断,再看解释
某回退方法在一个历史下的分数之和为61/45,能直接把它们当概率计算困惑度吗?
学习目标
- 推导bigram平滑中扣除及再分配的概率质量。
- 区分unigram频数与续接上下文多样性。
- 判断未知词何时仍然具有零概率。
- 分清开发集选择、归一化似然与回退分数。
先修与延伸
查看知识关联图 →参考文献
- Speech and Language Processing, third-edition draft: interpolation and backoff
Daniel Jurafsky; James H. Martin · 2026 - An Empirical Study of Smoothing Techniques for Language Modeling, TR-10-98
Stanley F. Chen; Joshua Goodman · 1998
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-08 · Codex single-AI-author technical check: scoped SLP August19,2026 and 1998 TR-10-98 definitions, eleven paired equations, add-k/interpolation/Witten-Bell/absolute mass, single-discount interpolated bigram KN continuation and empirical marginal identity, unnormalized backoff rejection, partial Good-Turing diagnostic, UNK support, EOS/event-weighted likelihood, exact-rational versus floating logs, complexity and four explained exercises. Not modified KN, complete Katz, a natural-language benchmark or human peer review.
- 逐节对照双语:一个BOS历史与一个EOS目标、加k及混合质量、固定D扣除质量、前驱种类续接及KN边缘抵消、Stupid Backoff61/45拒绝、Good-Turing缺桶、未训练/已训练UNK、零概率与数值下溢、仅开发集网格选择;十一公式与四解释习题对应。
- 正式测试执行生产MDX:20项原型检查、3项正文手算/边界/恒等检查与6项出版检查。核精确Fraction质量、四折扣KN边缘、事件数、独立分数、极小alpha有限对数及已见句困惑度。训练计入句子/EOS遍历与词表排序,保留有理数位成本说明。
- 四张原创SVG绑定实际MDX结果,七项图检查核数据、算术、条形及双语引用。隔离18种语言/宽度组合、四种备用字体验证通过,保留英文标签修正记录;实际查看桌面/手机截图。完整文章浏览器验收另记,无人工同行审校或上游代码执行。
核对的来源位置:
- Speech and Language Processing, third-edition draft: interpolation and backoff · Cached August 19, 2026 chapter 3, layout-text lines 884–967: interpolation, development-set weights and Stupid Backoff not being a probability distribution. Only this scoped reading.
- An Empirical Study of Smoothing Techniques for Language Modeling, TR-10-98 · 1998 report: cover August, inner title July 24. Layout-text lines 335–408 and 520–761; rendered pages 13–17, Witten-Bell/absolute discount/interpolated KN equations and continuation types. No experiments or modified-KN review; not the 1996 conference or 1999 journal version.
相关主题