文本分类:先训练流程,再检验决策
Text classification
仅用训练集拟合计数,在验证集选平滑参数,比较多数预测、全体准确率与拒答。
text-classification收件箱里的标签,是一项工作流决策
设想把虚构客服工单分给账务、技术或配送支持。invoice payment像账务问题,login password像技术问题;charge error却可能对应不止一种流程,空工单更没有词语线索。选择分类器之前,应先定义标签究竟表示什么。
单标签任务从固定集合中选一类;多标签任务可能选多类,通常需要不同的输出与评分约定。还有文档可能不属于任何已知类。IR教材区分这些分类情形,也解释类别不均衡为何让accuracy不足以单独评价系统。评测与标签范围
本文完整算例对已经分词的合成工单做单标签分类。多数类基线、多项式朴素贝叶斯及可拒答版本使用同一批测试记录;重点是在朴素贝叶斯模型基础上看清整个流程和证据。
预处理也要在训练集里拟合
只统计训练数据
用训练文档建立词表。最小文档频率过滤统计一个词出现在多少篇文档,不是它在某篇里重复多少次。词表固定后,再分类别累积词元出现次数。
令N_c为类别c的训练文档数,N为总文档数,T_cw为类别c中保留词w的出现次数,V为词表。正平滑参数alpha给出:
类别先验数文档,词分布数出现次数;混淆分母会改变模型。教材的加一平滑就是alpha=1。参数估计
文档计数向量为x时,用对数先验加上保留词元的证据给每类打分:
重复词重复贡献。位置共享与条件独立是很强的近似,单词计数表示没有建模顺序和否定。对类别分数做平移后的softmax,得到可以检查的已知类别后验:
这些概率以保留的表示和模型假设为条件,不会自动成为真实工单上的校准正确率。本文明确忽略未知词,并在输出中统计它们;空文档或全未知词文档退化为类别先验。
手算一个小后验
类别a只有训练文档x x y,类别b只有y,alpha=1。于是theta_a=(3/5,2/5)、theta_b=(1/3,2/3),类别先验相等。一个x与两个x提供不同证据:
这不是伯努利出现模型。若希望重复一个词不改变特征,应另行定义并训练该模型,不能在预测一半时突然丢掉计数。
分开拟合、选择与测试
对每个候选alpha,只用训练数据拟合,再在验证数据上评测。按验证集macroF1选择,并声明并列时的次序;测试集不是选择函数的参数:
组ID用来阻止有关联记录跨集合。在真实任务里,组可能是客户、来源文档或近重复家族,应反映具体泄漏机制;仅仅换了行ID,并不能保证隔离。
运行整条小型分类流程
使用Python3.12与NumPy1.26。文件直接列出六张训练、三张验证和六张测试工单;词元和意图标签给定,没有藏在依赖里的外部语料或分词器。alpha网格为[0.25,1,4],三者验证macroF1都为1,按声明的首项优先规则选0.25。
"""Original train/validation/test text-classification pipeline with abstention."""
from collections import Counter
import json,math
import numpy as np
def checked(rows,labels=True):
if not isinstance(rows,list) or len(rows)>1000:raise ValueError('at most1000 document records required')
for row in rows:
if not isinstance(row,dict) or not isinstance(row.get('group'),str) or not row['group']:raise ValueError('group id required')
tokens=row.get('tokens')
if not isinstance(tokens,list) or len(tokens)>200 or any(not isinstance(t,str) or not t for t in tokens):raise ValueError('at most200 nonempty string tokens per document')
if labels and (not isinstance(row.get('label'),str) or not row['label']):raise ValueError('label required')
return rows
def check_splits(*splits):
seen=set()
for split in splits:
groups={r['group'] for r in checked(split)}
if seen&groups:raise ValueError('group leakage across splits')
seen|=groups
def fit(rows,alpha=1.,min_df=1):
checked(rows)
if not rows:raise ValueError('training set cannot be empty')
if type(alpha) not in (int,float) or not math.isfinite(alpha) or not 0<alpha<=1e100:raise ValueError('bounded positive smoothing required')
if type(min_df) is not int or not 1<=min_df<=len(rows):raise ValueError('invalid document frequency threshold')
df=Counter(t for r in rows for t in set(r['tokens']));vocab=sorted(t for t,count in df.items() if count>=min_df)
classes=sorted({r['label'] for r in rows});index={t:i for i,t in enumerate(vocab)};ci={c:i for i,c in enumerate(classes)}
counts=np.zeros((len(classes),len(vocab)));doc_counts=np.zeros(len(classes))
for row in rows:
c=ci[row['label']];doc_counts[c]+=1
for word in row['tokens']:
if word in index:counts[c,index[word]]+=1
log_prior=np.log(doc_counts)-math.log(len(rows))
# Log differences retain very small positive smoothing without dividing to0.
log_terms=np.log(counts+alpha)-np.log(counts.sum(axis=1,keepdims=True)+alpha*len(vocab)) if vocab else counts.copy()
return {'classes':classes,'vocabulary':vocab,'log_prior':log_prior,'log_terms':log_terms,'alpha':alpha,'min_df':min_df}
def predict(model,rows,threshold=0.):
checked(rows,labels=False)
if type(threshold) not in (int,float) or not math.isfinite(threshold) or not 0<=threshold<=1:raise ValueError('threshold must be0..1')
vocab={t:i for i,t in enumerate(model['vocabulary'])};results=[]
for row in rows:
counts=Counter(t for t in row['tokens'] if t in vocab);scores=model['log_prior'].copy()
for term,n in counts.items():scores+=n*model['log_terms'][:,vocab[term]]
shifted=scores-scores.max();logp=shifted-math.log(float(np.exp(shifted).sum()));p=np.exp(logp);best=int(np.argmax(p))
results.append({'label':model['classes'][best] if p[best]>=threshold else None,'top_label':model['classes'][best],
'probabilities':p.tolist(),'log_probabilities':logp.tolist(),'known_tokens':sum(counts.values()),
'total_tokens':len(row['tokens']),'ignored_tokens':[t for t in row['tokens'] if t not in vocab]})
return results
def metrics(gold,predicted,classes):
if not classes or len(set(classes))!=len(classes) or len(gold)!=len(predicted) or any(y not in classes for y in gold) or any(y is not None and y not in classes for y in predicted):
raise ValueError('aligned gold, predicted and declared classes required')
result={}
for c in classes:
tp=sum(a==b==c for a,b in zip(gold,predicted));g=gold.count(c);p=predicted.count(c)
result[c]={'tp':tp,'fp':p-tp,'fn':g-tp,'f1':2*tp/(g+p) if g+p else 0.}
accepted=sum(y is not None for y in predicted);correct=sum(a==b for a,b in zip(gold,predicted))
return {'classes':result,'macro_f1':sum(c['f1'] for c in result.values())/len(classes),
'coverage':accepted/len(gold) if gold else 0.,'accuracy_all':correct/len(gold) if gold else 0.,
'accuracy_accepted':correct/accepted if accepted else 0.}
def select_alpha(train,validation,grid=(.25,1.,4.)):
check_splits(train,validation)
if not validation or not grid:raise ValueError('nonempty validation and grid required')
best=None;trials=[]
for alpha in grid:
model=fit(train,alpha);pred=[r['label'] for r in predict(model,validation)]
score=metrics([r['label'] for r in validation],pred,model['classes'])['macro_f1'];trials.append({'alpha':alpha,'macro_f1':score})
if best is None or score>best[0]:best=(score,model)
return best[1],trials
def row(group,text,label):return {'group':group,'tokens':text.split(),'label':label}
def demo():
train=[row('t1','invoice charge payment','billing'),row('t2','refund charge invoice','billing'),
row('t3','login password error','technical'),row('t4','password reset login','technical'),
row('t5','parcel shipment late','delivery'),row('t6','delivery parcel tracking','delivery')]
validation=[row('v1','invoice refund','billing'),row('v2','login reset','technical'),row('v3','late parcel','delivery')]
test=[row('q1','invoice payment','billing'),row('q2','login password','technical'),row('q3','parcel tracking','delivery'),
row('q4','charge error','technical'),row('q5','unseen jargon','delivery'),row('q6','','billing')]
check_splits(train,validation,test);model,trials=select_alpha(train,validation)
automatic=predict(model,test);selective=predict(model,test,threshold=.7);gold=[r['label'] for r in test]
majority=Counter(r['label'] for r in train);baseline=max(sorted(majority),key=majority.get)
return {'train':train,'validation':validation,'test':test,'vocabulary':model['vocabulary'],'classes':model['classes'],
'alpha':model['alpha'],'validation_trials':trials,'automatic':automatic,'selective':selective,
'automatic_metrics':metrics(gold,[r['label'] for r in automatic],model['classes']),
'selective_metrics':metrics(gold,[r['label'] for r in selective],model['classes']),
'majority_metrics':metrics(gold,[baseline]*len(test),model['classes']),
'scope':'Original single-label synthetic tickets; vocabulary/priors fitted on training only, smoothing selected on validation only. Threshold0.7 is illustrative, not a calibrated guarantee; fixed intended label on ambiguous charge error.'}
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
程序检查组隔离,建立训练词表,拟合全部候选模型,选择alpha,预测测试标签并报告基线;还返回忽略的词和稳定对数概率。正平滑计算使用对数之差,在核对的小例子中,即使采用binary64最小正平滑值,也不会先把概率除到0。
模糊工单charge error被明确赋予技术问题的意图标签,模型却选账务;unseen jargon没有训练词,只能遵循先验。空工单碰巧通过确定性并列规则获得其示例设定的billing标签,这个正确计数不表示理解了空消息。
多数类基线accuracy为1/3、macroF1为1/6;自动NB的accuracy和macroF1均为2/3。使用教学阈值0.7后,六张工单接受三张,三张都正确:覆盖率1/2、全体准确率1/2、接受部分准确率1,macroF1仍为2/3。该阈值没有被优化成精确率保证。
接受部分更准,也可能只是决定做得更少
解释可拒答系统之前,先定义分母。本文拒答不算全体分类正确,并对其金标类别贡献假阴性:
零分母记0。覆盖率降低时,接受部分准确率可能上升,因此不能用它代替全体结果或待检查工作量;看似自信的模型,也可能在陌生语言上判断错误。
MacroF1对每个声明类别同等加权,该类分母为0时记0;micro则先汇集决策再计算指标。IR教材解释了类别失衡时二者为何可能差很大。关注类别的评测
模型保存O(|C||V|)个词参数;训练读取保留词元并初始化稠密表。在这个直接实现中,L个输入词元、u个不同保留词时,预测需要O(L+|C|(u+1))时间,计入空文档也要处理的先验与softmax。类别与词表乘积很大时,应采用稀疏或其他合适存储。代码限制记录数及每文档词元数,但这些上限不是内存性能认证。
适合相应语言的分词、词/字符n-gram、搭配合适分类器的TF-IDF、上下文编码器、多标签输出及未知类别处理,都需要新实验。不能把TF-IDF直接塞进这个计数估计器,就宣称仍是同一生成模型。词表选择、预处理统计和超参数选择都必须留在训练/验证协议之内。
检查计数,也检查分母
- 一个词在一篇训练文档重复十次,其他训练文档都没有。它的文档频率是多少?验证集出现一次,能改变已拟合词表吗?
答案:文档频率是1;如果保留,重复出现仍会影响类别词元计数。验证集出现不能改变用训练集拟合的词表。
- 两类手算例中,重复x为何把9/14变成81/106?
答案:多项式证据使用重复次数。相等先验抵消,似然比(3/5)/(1/3)=9/5在两次出现时平方,所以后验为81/(81+25)。只看是否出现是另一种假设。
- 六张进入系统的工单接受三张,接受标签都正确。覆盖率、接受部分准确率及全体准确率各是多少?
答案:覆盖率3/6=1/2,接受部分准确率3/3=1,全体准确率3/6=1/2,遵循已声明的拒答政策。只报告接受部分100%准确,会隐藏一半工作量。
- 看见测试中的charge error错误后,为它加一条专门规则,还能把同一测试成绩当成没有被开发触碰的留出证据吗?
答案:不能。测试已经影响开发,应保留原结果、记录改动,再获取新评测数据或明确修改协议;也不能为了让模型显得正确而改掉预期标签。
分类质量属于整条流程
IR教材把计数模型、训练估计与评测约定逐项说清;Pang等人2002年的情感研究用相关分类工具处理另一种标签任务,其探索性词表基线也说明查看测试数据会改变实验地位。本文借鉴的是这些方法判断,不是他们的语料性能数字。NB估计 评测 情感任务与探索基线
词袋与TF-IDF讨论表示,工程评测讨论更广的实验控制;情感分析还要问标签描述谁对哪个对象的意见。可以投入使用的分类器,需要把这些决定一起说清。
先判断,再看解释
分类器接受六张工单中的三张,接受部分全部正确。接受部分准确率与覆盖率各是多少?
学习目标
- 定义单标签/多标签任务及多数类基线。
- 仅用训练数据拟合词表、类别先验和词概率。
- 在验证集选择平滑参数,保护按组隔离的测试数据。
- 比较全体准确率、接受部分准确率、覆盖率及宏平均F1。
先修与延伸
查看知识关联图 →参考文献
- Introduction to Information Retrieval: Naive Bayes text classification
Christopher D. Manning, Prabhakar Raghavan and Hinrich Schütze · 2008 - Introduction to Information Retrieval: Evaluation of text classification
Christopher D. Manning, Prabhakar Raghavan and Hinrich Schütze · 2008 - Thumbs up? Sentiment Classification using Machine Learning Techniques
Bo Pang, Lillian Lee and Shivakumar Vaithyanathan · 2002
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-12 · Single AI author checked seven paired equations and four explained exercises against scoped IIR multinomial NB/evaluation and Pang2002. Training-only document-frequency vocabulary and priors, repeated token counts, stable smoothing, OOV/empty prior-only inference and group-separated validation selection checked. Hand posteriors9/14 and81/106, majority baseline, unknown words, ambiguous error and six-ticket abstention denominators are explicit:3/6 coverage and all-ticket accuracy versus3/3 accepted accuracy. Prediction cost includes input scanning and empty-document class scoring. Synthetic threshold .7 is illustrative and uncalibrated.
- 单AI作者核七组公式及四解释练习,引用限定IIR多项式朴素贝叶斯/评测和Pang2002。核训练文档频率词表与先验、重复词计数、稳定平滑、未见/空文本先验推断及分组验证选择。手算后验9/14、81/106,多数基线、歧义错误和六工单拒答分母明确:覆盖及全体准确率3/6,已答准确率3/3。复杂度包含输入扫描及空文档类别打分;阈值.7未经校准。
- 四张原创计算SVG绑定双语MDX;十一项图检查、36组独立语言/宽度组合和四备用字体通过;本AI作者实际查看六张桌面/手机截图。完整页面验收另记,不称人工同行审校。
核对的来源位置:
- Introduction to Information Retrieval: Naive Bayes text classification · Online chapter13, lines4–40: in-vocabulary tokens, repeated counts, shared term probabilities, log scoring, document class priors and add-one smoothing. Not later worked examples or full derivation.
- Introduction to Information Retrieval: Evaluation of text classification · Online chapter13, lines3–22: label multiplicity, imbalance, accuracy limitations and macro/micro averaging. No historical benchmark rankings adopted or Reuters reproduction.
- Thumbs up? Sentiment Classification using Machine Learning Techniques · Scoped text116–149,154–217: movie-review labels, word-list baselines, test-data use in third list, bag features and NB add-one estimation. Not full ME/SVM methods or complete comparative experiments.
相关主题