AI Wiki中文/EN

Text classification: train the pipeline, then test the decision

文本分类

Fit train-only counts, select smoothing on validation, and compare majority prediction, full-set accuracy and abstention.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

An inbox label is a workflow decision

Imagine routing invented support tickets to billing, technical help or delivery support. invoice payment suggests billing; login password suggests technical help. But charge error can belong to more than one workflow, and an empty ticket supplies no words at all. Before choosing a classifier, define what the labels are supposed to mean.

A single-label task selects one class from a fixed set. A multi-label task may select several; it generally needs a different output and scoring contract. Some documents may also fall outside every known class. The IR textbook distinguishes these classification settings and explains why class imbalance makes accuracy alone inadequate. Evaluation and label scope

Our complete example is single-label classification of already-tokenized synthetic tickets. A majority-class baseline, a multinomial Naive Bayes model and an abstaining version share the same test records. This article focuses on the pipeline and its evidence, building on the Naive Bayes model.

A selective classifier answers three of six tickets correctly and abstains on the rest. Its accepted-answer accuracy is 100%, but its coverage and all-ticket accuracy are both 50%.
A selective classifier answers three of six tickets correctly and abstains on the rest. Its accepted-answer accuracy is 100%, but its coverage and all-ticket accuracy are both 50%.

Train the preprocessing too

Count only training data

Fit a vocabulary from training documents. A minimum document-frequency filter counts whether a word appears in each document, not how often it repeats there. Once the vocabulary is fixed, accumulate token occurrences separately for each class.

Let N_c be the number of training documents in class c, N the total, T_cw the number of retained occurrences of word w in class c, and V the vocabulary. A positive smoothing parameter alpha gives:

π^c=NcN,θ^cw=Tcw+α∑v∈VTcv+α∣V∣.\hat\pi_c=\frac{N_c}{N},\qquad \hat\theta_{cw}=\frac{T_{cw}+\alpha}{\sum_{v\in V}T_{cv}+\alpha|V|}.

Class priors count documents; word distributions count occurrences. Mixing those denominators changes the model. The textbook’s add-one case is alpha=1. Parameter estimation

For document count vector x, score each class with the log prior plus retained-token evidence:

zc=log⁡π^c+∑w∈Vxwlog⁡θ^cw.z_c=\log\hat\pi_c+\sum_{w\in V}x_w\log\hat\theta_{cw}.

Repeated words contribute repeatedly. The positional and conditional-independence assumptions are strong approximations; word order and negation are not modeled by this unigram count representation. Normalize class scores with a shifted softmax for an inspectable posterior over the model’s known classes:

p(c∣x)=ezc−max⁡jzj∑kezk−max⁡jzj.p(c\mid x)=\frac{e^{z_c-\max_j z_j}}{\sum_k e^{z_k-\max_j z_j}}.

These probabilities are conditional on the retained representation and model assumptions. They are not automatically calibrated correctness probabilities for real tickets. Unknown tokens are ignored under our explicit policy and counted in the output; an empty or all-unknown document reduces to the class prior.

A small posterior calculation

Train classa onx x yand classb ony, with one document each and alpha=1. Then theta_a=(3/5,2/5), theta_b=(1/3,2/3), and equal class priors. Onexand twoxtokens give different evidence:

p(a∣x)=3/53/5+1/3=914,p(a∣x,x)=(3/5)2(3/5)2+(1/3)2=81106.p(a\mid x)=\frac{3/5}{3/5+1/3}=\frac9{14},\qquad p(a\mid x,x)=\frac{(3/5)^2}{(3/5)^2+(1/3)^2}=\frac{81}{106}.

This is not a Bernoulli presence model. If you want a model in which repeating a word does not change its feature, define and train that model rather than dropping counts halfway through prediction.

Separate fitting, selection and testing

For each candidate alpha, fit only on training data and evaluate on validation data. Select by validation macroF1, with a declared tie order. The test split is not an argument to the selection function:

α∗=arg⁡max⁡α∈GMvalidation(fα,train).\alpha^*=\arg\max_{\alpha\in\mathcal G} M_{validation}(f_{\alpha,train}).

A group ID keeps related records together across splits. In a real task, groups might represent a customer, source document or near-duplicate family; they should reflect the leakage mechanism. Merely using different row IDs does not provide that guarantee.

Run the whole small pipeline

Use Python3.12 and NumPy1.26. Six training tickets, three validation tickets and six test tickets are declared in the file. Tokens and intended labels are supplied; there is no external corpus or tokenizer hidden in a dependency. The alpha grid is[0.25,1,4]. All three tie at validation macroF1=1, so the declared first-grid-entry rule selects0.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))

The file checks group separation, builds the training vocabulary, fits all models, selects alpha, predicts test labels and reports baselines. It also returns ignored words and stable log probabilities. The positive smoothing calculation uses differences of logarithms, allowing even the smallest positive binary64 smoothing value in the checked tiny example without dividing a probability down to0.

The ambiguous test ticketcharge errorhas an explicitly intended technical label, but the model chooses billing. unseen jargoncontains no training words and follows the prior. The empty ticket happens to receive its deliberately assigned billing label through the deterministic tie policy; that correct count does not indicate any understanding of an empty message.

The majority baseline has accuracy1/3 and macroF1=1/6. Automatic NB has accuracy2/3 and macroF1=2/3. With an illustrative confidence threshold0.7, three of six tickets are accepted and all three are correct: coverage1/2, full-set accuracy1/2, accepted accuracy1 and macroF1 still2/3. The threshold was not optimized to guarantee precision.

A better accepted score may mean fewer decisions

Define the denominators before interpreting an abstaining system. In this implementation, abstention is not a correct full-set classification, and it contributes a false negative to its gold class:

coverage=NacceptedN,accuracyall=NcorrectN,accuracyaccepted=NcorrectNaccepted.coverage=\frac{N_{accepted}}N,\qquad accuracy_{all}=\frac{N_{correct}}N,\qquad accuracy_{accepted}=\frac{N_{correct}}{N_{accepted}}.

Zero denominators map to0. Accepted accuracy can increase as coverage falls, so it cannot replace full-set results or review workload. An apparently confident model can also be wrong on unfamiliar language.

MacroF1 gives each declared class equal weight, using0 for an empty class denominator. Microaveraging instead pools decisions before forming a metric. The IR textbook explains why these can differ greatly when classes are unbalanced. Class-sensitive evaluation

Fmacro=1∣C∣∑c∈C2TPc2TPc+FPc+FNc.F_{macro}=\frac1{|\mathcal C|}\sum_{c\in\mathcal C}\frac{2TP_c}{2TP_c+FP_c+FN_c}.

The model stores O(|C||V|) word parameters. Training reads the retained tokens and initializes that dense table; for L input tokens and u distinct retained words, prediction costs O(L+|C|(u+1)), including the prior and softmax even for an empty document. Large class/vocabulary products need sparse or otherwise appropriate storage. The code bounds records and per-document token counts, but those caps are not a memory-performance certification.

Other choices require new experiments: language-appropriate tokenization, word/character n-grams, TF-IDF with a compatible classifier, contextual encoders, multi-label outputs and unknown-class handling. Do not substitute TF-IDF values into this count estimator and claim the same generative model. Vocabulary selection, preprocessing statistics and hyperparameter choice must remain inside the training/validation protocol.

Check the counts and the denominator

  1. A word appears ten times in one training document and nowhere else. What is its document frequency, and may a validation occurrence change the fitted vocabulary?

Answer: Its document frequency is1; repeated occurrences still affect class token counts if retained. A validation occurrence must not change a vocabulary fitted on the training split.

  1. In the two-class hand example, why does repeatingxchange9/14 to81/106?

Answer: Multinomial evidence uses repeated occurrences. Equal priors cancel, and the likelihood ratio(3/5)/(1/3)=9/5 is squared for two occurrences, giving posterior81/(81+25). A presence-only model would be a different assumption.

  1. Three of six incoming tickets are accepted and all accepted labels are correct. Report coverage, accepted accuracy and full-set accuracy.

Answer: Coverage=3/6=1/2, accepted accuracy=3/3=1, and full-set accuracy=3/6=1/2 under the declared abstention policy. Reporting only100% accepted accuracy hides half the workload.

  1. After seeing the test error oncharge error, you add a special rule for that phrase. May the same test score still be presented as untouched held-out evidence?

Answer: No. The test has informed development. Keep the prior result, record the change and obtain fresh evaluation data or an explicitly revised protocol. Do not repair the intended label merely to make the model appear correct.

Classification quality belongs to the entire pipeline

The IR textbook makes the count model, training estimates and evaluation conventions explicit. Pang et al.‘s2002 sentiment study shows a different label task using related text-classification tools; its exploratory word-list baseline also illustrates how looking at test data changes the status of an experiment. We reuse these methodological lessons, not their corpus performance numbers. NB estimation Evaluation Sentiment task and exploratory baselines

Bag of words andTF-IDF describe representations; model evaluation covers broader experimental controls. Sentiment analysis adds the question of whose opinion and which target the class describes. A deployable classifier needs all of these decisions to be explicit.

Make a prediction, then check

A classifier accepts3 of6 tickets and all accepted labels are correct. What are accepted accuracy and coverage?

Choose one answer

Learning objectives

  • Define single-label versus multi-label tasks and a majority baseline.
  • Fit vocabulary, class priors and smoothed word probabilities on training data only.
  • Select smoothing on validation while protecting group-separated test data.
  • Compare full-set accuracy, accepted accuracy, coverage and macroF1.

Prerequisites & connections

Explore related knowledge →

References

  1. Introduction to Information Retrieval: Naive Bayes text classification
    Christopher D. Manning, Prabhakar Raghavan and Hinrich Schütze · 2008
  2. Introduction to Information Retrieval: Evaluation of text classification
    Christopher D. Manning, Prabhakar Raghavan and Hinrich Schütze · 2008
  3. Thumbs up? Sentiment Classification using Machine Learning Techniques
    Bo Pang, Lillian Lee and Shivakumar Vaithyanathan · 2002

Version1 · Editorial status: Recorded technical checks completed

View technical check record (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.

  • 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.
  • Four original computed SVGs bind exact bilingual MDX. Eleven figure checks and36 isolated language/width cases with four fallback fonts passed; six actual desktop/mobile screenshots inspected by this AI author. This is separate from final full-page browser acceptance, with no human peer-review claim.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.