n-gram语言模型:计数要记住多长的历史?
N-gram language models
建立条件计数,推导MLE与加性平滑,辨别零概率、句末计分和不可比的困惑度。
ngram-models记得更长,反而让熟悉的句子变得不可能?
使用四句已经切好词元的虚构训练语料:
red birds sing
blue birds fly
red birds fly
blue fish swim
birds之后,fly出现两次,sing一次。bigram模型只记住前一个词元,因此即使完整句子blue birds sing从未出现,也能给它正概率。trigram模型记住前两个词元,只见过blue birds之后跟fly,于是没有平滑的估计会把下一词sing的概率设为0。
更多上下文能区分情况,也会减少每种情况分到的观测。这个例子小到可以手算。它不是基准语料,后面三个命名评测条件只是诊断构造,不是对真实语言性能的独立估计。
先读条件概率。词元化决定单位是什么;本程序直接接收词元列表,不改变大小写,也不负责发现词边界。
从完整历史到短历史计数表
精确恒等式与模型限制不同
对于预测事件序列x_1到x_T,概率链式法则精确成立。n阶模型则用至多前n−1个词元构成的历史h_t替代完整过去:
第二个式子定义另一种模型;链式法则本身不能证明遗忘上下文合理。unigram的历史为空,bigram留一个词元,trigram留两个。这种近似通常称为Markov假设。SLP3,§3.1.1
每句前面加n−1个开始标记BOS,写作<s>;每句恰好预测一个结束标记EOS,写作</s>。BOS只作上下文,不是预测目标,也不属于预测词表V。EOS和未知词类UNK都在V里。因此一条含m个普通词元的句子贡献m+1个预测事件,m为0时也如此。四句训练语料贡献16个事件;不合并低频词时,V有9项。
EOS让模型能够停止,并给完整变长句子分配概率。但下一词概率表归一化,并不自动证明任意模型最终都会停;如果存在到不了EOS的封闭循环,就需要另行处理。对于下面正的加性平滑模型,历史空间有限且EOS概率处处为正,因此每步停止概率有一个正下界,永不停止的概率为0。生成长度上限仍是计算限制;达到上限不等于产生EOS。SLP3,边界标记讨论
推导计数估计
固定历史h,令C(h,w)统计训练中在h之后预测w的次数,C(h)是这些目标计数的和。定义h时使用与评分一致的填充和句界。最大化条件对数似然,并要求概率表归一化:
对正计数项,拉格朗日乘子条件为C(h,w)/q(w|h)=λ。求和得到λ=C(h),因此在C(h)>0时,最大似然估计是:
零计数项得到0。若C(h)=0,这个除法没有定义条件分布;直接查询未见过的MLE历史时,程序明确报错。这与“历史见过,但给某个目标分配0概率”是两种情况。SLP3,§3.1.2 NLTK MLE公式
本例q(fly|birds)=2/3,q(sing|birds)=1/3;句首red与blue各为1/2。bigram模型下,完整句子red birds fly的概率要计入EOS:
trigram中,red birds后面sing、fly各出现一次,因此同一句的概率是1/4。即使整体训练拟合可能更好,trigram也不是每条句子的似然都必然改善。
补上正概率,也要算出代价
加性平滑也称Lidstone基线,给每个目标计数都加α,包括EOS和UNK:
分子求和就是分母,因此分布归一化。未见历史会得到V上的均匀分布。α=1是加一,本文使用α=0.5;核读的NLTK实现也采用“计数加常数”的分子和按词表大小增加的分母。NLTK Lidstone
历史blue birds只观测过一个目标fly。V=9、α=0.5时,分母为5.5;fly得到3/11,另外八个目标各得1/11。原来不可能的sing现在可能出现,但观测过的fly也损失了概率。平滑有取舍,不是无代价的改善;α无限增大时趋向均匀分布。超参数应在开发数据上选择,不要反复针对最终测试结果调优。
词表构造也是概率空间的一部分
程序只用训练频率建立词表。低于min_count的词在训练时映为UNK,评测时词表之外的词也映到该类。评分green birds fly不会扩张V。阈值为1时,UNK虽然在V里,却没有观测目标;仅给它留位置,不会凭空产生正的MLE概率。
阈值改为2,sing、fish、swim合并为UNK:三个训练目标改变,V从9缩到6。此时困惑度衡量更粗的事件预测,不能直接拿它与完整词表的分数比较,就声称对原词预测更好。改变词元化或大小写政策,也会遇到同样的问题。
不把许多小数直接相乘
一句话的数学概率可以为正,浮点乘积却下溢成0。先相加自然对数概率。对于M条评测句子,令T_j包含恰好一个EOS,总事件数T为各句事件数之和:
这是以nat为单位的经验平均负对数似然,其指数为困惑度:
也可以用底2对数,再用2的平均值次方还原;核读的NLTK API遵循这种约定。但它的分母针对调用者传入的n-gram,本文明确每句计入一次EOS,不能暗中假定两个管线的事件集一样。SLP3,§3.3 NLTK API
bigram评分red birds fly时,T=4,PP=3^(1/4),约为1.316074。直接平均各句困惑度通常不对,应先汇总对数损失与事件数。真正的零概率事件会使损失和困惑度为无穷;严格JSON输出用null配合zero_probability状态表达这种情况。若对数概率仍有限、只是乘积下溢,则状态保持有限,并用下溢标记解释零乘积。有限但极大的H取指数还可能上溢,另有对应标记。这些诊断不能混为一谈。
用同一个已声明的模型拟合、评分和采样
把完整标准库程序保存为ngram_models.py,运行python3 ngram_models.py。它接受1—4阶、非空的已分词句子集合及有限非负α。单条句子可以为空;输入词元必须是非空字符串,不含代理码点或保留标记,大小写原样保留。程序不下载数据,也不在评测输入上拟合词表。
"""Original finite-context language model with an explicit event convention.
Input is pretokenized, case-preserving sentences. Training-only vocabulary,
order-1 BOS pads and exactly one predicted EOS per sentence. Supports MLE and a
declared additive baseline; no advanced smoothing or external model dependency.
"""
import json
import math
import random
from collections import Counter,defaultdict
BOS='<s>';EOS='</s>';UNK='<unk>';SPECIAL={BOS,EOS,UNK}
def checked_sentence(sentence):
if not isinstance(sentence,(list,tuple)):raise ValueError('A pretokenized list or tuple is required')
for token in sentence:
if not isinstance(token,str) or not token or token in SPECIAL or any(0xD800<=ord(c)<=0xDFFF for c in token):
raise ValueError('Nonempty Unicode tokens without reserved markers or surrogates required')
return list(sentence)
def fit(sentences,order=2,alpha=0.,min_count=1):
if type(order) is not int or not 1<=order<=4:raise ValueError('Teaching orders are1–4')
if type(min_count) is not int or min_count<1:raise ValueError('Positive integer frequency threshold required')
if isinstance(alpha,bool) or not isinstance(alpha,(int,float)) or not math.isfinite(alpha) or alpha<0:
raise ValueError('Finite nonnegative additive smoothing required')
if not isinstance(sentences,(list,tuple)) or not sentences:raise ValueError('Nonempty sentence collection required')
sentences=[checked_sentence(s) for s in sentences];frequency=Counter(word for s in sentences for word in s)
kept={w for w,count in frequency.items() if count>=min_count};vocabulary=sorted(kept|{EOS,UNK})
if not math.isfinite(alpha*len(vocabulary)):raise ValueError('Smoothing mass overflow')
counts=defaultdict(Counter);unknown=0;events=0
for sentence in sentences:
mapped=[word if word in kept else UNK for word in sentence];unknown+=mapped.count(UNK)
padded=[BOS]*(order-1)+mapped+[EOS]
for i in range(order-1,len(padded)):
history=tuple(padded[i-order+1:i]) if order>1 else ()
counts[history][padded[i]]+=1;events+=1
return {'order':order,'alpha':float(alpha),'min_count':min_count,'vocabulary':vocabulary,
'counts':dict(counts),'frequency':dict(frequency),'training_sentences':len(sentences),
'training_prediction_events':events,'observed_unk_targets':unknown}
def mapped_tokens(model,sentence):
sentence=checked_sentence(sentence);vocabulary=set(model['vocabulary'])
return [word if word in vocabulary else UNK for word in sentence]
def context_key(model,history):
if not isinstance(history,(list,tuple)):raise ValueError('A token-history sequence is required')
mapped=[];seen_word=False;vocabulary=set(model['vocabulary'])
for token in history:
if not isinstance(token,str) or not token or token==EOS or any(0xD800<=ord(c)<=0xDFFF for c in token):raise ValueError('A valid token history before EOS is required')
if token==BOS:
if seen_word:raise ValueError('BOS is a prefix marker, not a token in the middle')
mapped.append(BOS)
else:seen_word=True;mapped.append(token if token in vocabulary else UNK)
k=model['order']-1
return tuple(([BOS]*k+mapped)[-k:]) if k else ()
def conditional_logs(model,history):
context=context_key(model,history);counts=model['counts'].get(context,{})
denominator=sum(counts.values())+model['alpha']*len(model['vocabulary'])
if not math.isfinite(denominator):raise ValueError('Conditional normalizer overflow')
if denominator==0:raise ValueError('Unseen history has no MLE conditional distribution')
result={}
for token in model['vocabulary']:
numerator=counts.get(token,0)+model['alpha']
result[token]=math.log(numerator)-math.log(denominator) if numerator else None
return result
def distribution(model,history):
return {word:(math.exp(value) if value is not None else 0.) for word,value in conditional_logs(model,history).items()}
def sequence_score(model,sentence):
mapped=mapped_tokens(model,sentence);history=[BOS]*(model['order']-1);terms=[];events=len(mapped)+1
for index,token in enumerate(mapped+[EOS]):
value=conditional_logs(model,history)[token]
if value is None:
return {'status':'zero_probability','mapped_tokens':mapped,'prediction_events':events,
'first_zero_event':index,'log_probability':None,'probability':0.,'mean_nll_nats':None,
'perplexity':None,'log_terms_before_zero':terms,'note':'Null NLL/perplexity represents positive infinity; EOS is included.'}
terms.append(value);history=(history+[token])[-(model['order']-1):] if model['order']>1 else []
logp=math.fsum(terms);mean_nll=-logp/events;probability=math.exp(logp)
try:perplexity=math.exp(mean_nll)
except OverflowError:perplexity=None
return {'status':'finite_log_probability','mapped_tokens':mapped,'prediction_events':events,
'log_probability':logp,'probability':probability,'probability_underflow':probability==0.,
'mean_nll_nats':mean_nll,'perplexity':perplexity,'perplexity_overflow':perplexity is None,'log_terms':terms}
def evaluate(model,sentences):
if not isinstance(sentences,(list,tuple)) or not sentences:raise ValueError('A nonempty evaluation collection is required')
scores=[sequence_score(model,s) for s in sentences];events=sum(s['prediction_events'] for s in scores)
impossible=sum(s['status']=='zero_probability' for s in scores)
mean_nll=None if impossible else -math.fsum(s['log_probability'] for s in scores)/events
try:perplexity=math.exp(mean_nll) if mean_nll is not None else None
except OverflowError:perplexity=None
return {'sentences':len(scores),'prediction_events':events,'zero_probability_sentences':impossible,
'mean_nll_nats':mean_nll,'perplexity':perplexity,
'null_scope':'Null means mathematically infinite after a zero event, or numeric exp overflow; inspect zero_probability_sentences and mean_nll_nats.'}
def generate(model,seed=7,max_new_tokens=20,prefix=()):
if type(seed) is not int or type(max_new_tokens) is not int or max_new_tokens<0:raise ValueError('Integer seed and nonnegative generation cap required')
prefix=mapped_tokens(model,prefix);history=list(context_key(model,prefix));rng=random.Random(seed);generated=[];ended=False
for _ in range(max_new_tokens):
probabilities=distribution(model,history);positive=[(w,p) for w,p in probabilities.items() if p>0]
threshold=rng.random()*math.fsum(p for _,p in positive);cumulative=0.;chosen=positive[-1][0]
for word,probability in positive:
cumulative+=probability
if threshold<cumulative:chosen=word;break
if chosen==EOS:ended=True;break
generated.append(chosen);history=(history+[chosen])[-(model['order']-1):] if model['order']>1 else []
return {'mapped_prefix':prefix,'generated':generated,'ended_with_eos':ended,
'stop_reason':'EOS' if ended else 'length_cap','prediction_draws':len(generated)+int(ended),
'seed':seed,'max_new_tokens':max_new_tokens}
def demo():
train=[['red','birds','sing'],['blue','birds','fly'],['red','birds','fly'],['blue','fish','swim']]
tests={'seen':['red','birds','fly'],'recombined':['blue','birds','sing'],'unknown':['green','birds','fly']}
configurations=[('unigram_mle',1,0.),('bigram_mle',2,0.),('trigram_mle',3,0.),('trigram_add_half',3,.5)]
models={name:fit(train,order,alpha) for name,order,alpha in configurations};results={}
for name,model in models.items():
results[name]={'order':model['order'],'alpha':model['alpha'],'vocabulary':model['vocabulary'],
'training':evaluate(model,train),'test_scores':{key:sequence_score(model,s) for key,s in tests.items()},
'sample':generate(model),'contexts':len(model['counts'])}
coarse=fit(train,2,.5,min_count=2)
return {'training_sentences':train,'training_prediction_events':16,'conditions':tests,'results':results,
'bigram_birds_distribution':distribution(models['bigram_mle'],['birds']),
'vocabulary_change':{'vocabulary':coarse['vocabulary'],'observed_unk_targets':coarse['observed_unk_targets'],
'mapped_training':[mapped_tokens(coarse,s) for s in train],
'scores':{name:sequence_score(coarse,s) for name,s in tests.items()},
'comparable_to_full_vocabulary':False},
'scope':'Original tiny pretokenized corpus, training-only vocabulary and one scored EOS per sentence. Add-half is a baseline, not advanced smoothing. Perplexity compares the same events/vocabulary convention; no real-language benchmark.'}
if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=False,indent=2,allow_nan=False))
三个诊断句子的实际概率如下:
| 模型 | red birds fly | blue birds sing | green birds fly |
|---|---|---|---|
| Bigram MLE | 1/3 | 1/12 | 0 |
| Trigram MLE | 1/4 | 0 | 0 |
| Trigram加半 | 0.0100404295 | 0.0016828092 | 0.0002793140 |
每项都包含EOS,green会映成UNK。先比较两个MLE行,再看平滑。重组句子的trigram概率为0,是缺少对应条件事件,不是分词失败或数值下溢。采样使用局部的固定种子随机生成器,并记录是遇到EOS还是到达上限。
若训练有E个预测事件、阶数n固定,在词元哈希及比较为固定代价、忽略读取字符成本的假设下,计数构造期望需O(En)时间,词表排序另需O(|V|log|V|)。稀疏计数存储最坏为O(En+|V|)。为方便观察,本评分器每个事件都构造完整的|V|项分布,故T个事件的评分时间为O(T(|V|+n)),对数轨迹及临时表另外占O(T+|V|+n)空间;没有建立|V|^n大小的稠密张量。生产评分器可以直接查目标概率、缓存历史总计数并避免构造全表,但本程序没有这项优化。
配套测试手算计数和EOS,检查归一化、概率乘积、固定词表、事件加权困惑度、极端平滑、真正零事件与下溢之别,以及生成上限。这些检查不证明模型能在真实数据上生成有用语言。
计数表记不住什么?
固定的短历史无法区分最后n−1个词元相同的两个上下文。增大n可以拆开它们,却增加可能历史的数量,使数据稀疏。加性平滑向所有目标均匀补质量,没有利用相近历史的结构。回退、插值和更细致的平滑方法另有专题;神经语言模型则使用学习到的表示,不依赖这里的显式计数表。
困惑度衡量某套事件约定下的预测,不等于事实正确、每条样本都合语法,或对读者有用。四句虚构训练语料刻意让条件差异看得见。真实评测需要记录数据来源、固定词元化与词表映射、留出文本和未经改进的基线。分别报告训练和评测损失,不要用一条短而流畅的样本证明底层分布覆盖充分。
把容易漏掉的事件也数进去
- 四条各含三个词元的训练句子,为什么贡献16个事件,不是12或20?
答案:每句预测三个普通目标加一个EOS,共4×4=16。BOS提供历史,不被预测;即使trigram有两个BOS,也不增加预测事件。
- 计算
blue birds sing的bigram概率和困惑度。
答案:计入EOS后为(1/2)×(1/2)×(1/3)×1=1/12。四个预测事件得到PP=12^(1/4),约1.861210。完整句子没有出现过,但所需的各个bigram都出现过,因此概率为正。
- 历史
blue birds后,sing的加半概率是多少?为什么仅给UNK留位置不能解决MLE零概率?
答案:分母为1+0.5×9=5.5,sing的分子为0.5,所以是1/11。未平滑MLE中,留了位置却从未观测的UNK计数仍为0。属于词表与分配到多少概率,是两项不同决定。
- 一句有2个预测事件,总负对数似然2 nat;另一句有8个事件,总损失16 nat。整体困惑度是多少?可以直接与另一套UNK词表比较吗?
答案:总损失18除以10事件,H=1.8,PP=e^1.8,约6.049647。平均句子困惑度或等权平均各句平均损失,都得不到这个值。改变UNK政策会改变预测事件,因此不能仅凭这种比较证明对同一组原词的模型更好。
概率模型与评分约定要一起记录
2026年8月19日版SLP3章节提供了本题核读的Markov、MLE、边界标记与困惑度段落,固定NLTK文件明确了加性公式及底2接口约定。语料、完整实现、对数域诊断和算例均为原创;没有复现高级平滑基准,也没有运行上游库。扩展数据的下一步仍应明确概率空间和评测协议。
先判断,再看解释
把更多词替成UNK后困惑度降低,能证明语言模型更好吗?
学习目标
- 从概率链式法则推导有限历史条件模型。
- 只用训练数据建立计数与词表。
- 解释加性平滑、零事件与对数域评分。
- 在明确EOS与词表约定下计算事件加权困惑度。
先修与延伸
查看知识关联图 →参考文献
- Speech and Language Processing, chapter3: N-gram Language Models (August19,2026)
Daniel Jurafsky; James H. Martin · 2026 - NLTK 3.9.2 MLE and Lidstone formulas
NLTK contributors · 2025 - NLTK 3.9.2 language-model logscore, entropy and perplexity
NLTK contributors · 2025
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-08 · Codex single-AI-author technical check: scoped SLP3 August19,2026 Markov/MLE/EOS/perplexity and pinned NLTK formulas; seven paired equations, MLE derivation, additive denominator, training-only vocabulary, one EOS per sentence, event-weighted log likelihood, true zeros versus underflow/exp overflow, four explained exercises and computed SVGs. Original four-sentence corpus; not real-language performance or human peer review.
- 逐节对照两语:链式法则与有限历史假设、受约束MLE推导、条件计数分母、BOS不作目标且恰好一次EOS、加性质量及有限状态停止条件、训练限定UNK、事件加权困惑度、对数与数值零区别、复杂度;七公式及四解释习题。
- 正式测试含17项独立计数/评分/生成检查,另核手算概率/汇总及6项出版检查。四句虚构语料、16目标、V9;阈值2改变3目标为V6。bigram重组为正、未平滑trigram为零、加半均有限;这是诊断输入,不是留出自然语言基准。
- 四张原创SVG绑定真实输出与原数据;最终隔离双语、三宽/四字体验证通过,实际查看桌面/手机截图。完整文章验收另记。单AI作者技术检查,不是独立人工审校;无上游代码复制或执行。
- 登记后纠错:无效schema类型algorithm改为concept。正文、程序、公式、引用及原六文件冻结逐字保留;修正正式测试模块被局部变量遮蔽的问题。保留明确差异,重新通过正式、内容、构建检查后才确认出版验收。
核对的来源位置:
- Speech and Language Processing, chapter3: N-gram Language Models (August19,2026) · Version header and scoped Markov/MLE/BOS/EOS/perplexity passages; downloaded PDF SHA recorded. Not a whole-chapter reading or advanced-smoothing reproduction.
- NLTK 3.9.2 MLE and Lidstone formulas · Lines14–55: conditional frequency and additive numerator/normalizer. No upstream execution or advanced smoothing review.
- NLTK 3.9.2 language-model logscore, entropy and perplexity · Lines144–195: base2 logs and mean over caller-supplied n-grams; this article declares its own one-EOS event scope.
相关主题