AI Wiki中文/EN

Natural language processing: define the task before fitting the model

自然语言处理任务

Compare language-task contracts, derive a representation ceiling and run a complete small classifier that exposes contrast and negation failures.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

What exactly should the system return?

Consider a deliberately invented review: the room is good but bad. Suppose our small annotation rule says that the final clause determines the label. Now reverse the adjectives: the room is bad but good. The words and their counts are unchanged, but the required answer changes. Before selecting a larger model, ask whether its input representation even preserves the evidence needed for this decision.

Natural language processing (NLP) builds computational procedures for tasks involving language. A task needs more than a name such as “understanding”: specify its input, allowed output, annotation rule and failure cost. The broader field includes classification, language modeling, translation, retrieval, dialogue and linguistic structure. The SLP roadmap provides routes through these branches; this article uses one small classifier to make task design inspectable. SLP introduction, roadmap

The sentence above is a synthetic test, not a claim about how real people rate rooms. In natural reviews, the relation between clauses can be more complicated. A declared rule is useful here because it lets us isolate a precise failure without pretending to have solved sentiment analysis.

Accuracy of the same fitted classifier under plain, contrast and negation conditions, plus the finite representation ceiling.
Original synthetic English: 24 training rows and 16 test rows per condition. Both policies fail all negation probes; the contrast ceiling refers only to these fixed feature groups.

From a language problem to a measurable contract

Outputs change the question

The following are illustrative contracts we could give a system, not an exhaustive taxonomy:

Task shapeExample inputRequired outputA concrete failure
ClassificationOne reviewA label from an agreed setAssigning a negative review to the positive class
Token labelingText with fixed token boundariesOne tag per tokenA name boundary or tag is wrong
Span extractionA document and a questionStart/end positions, or an explicit abstentionThe span points into the wrong representation
Structural analysisOne sentenceA tree or graph under an annotation schemeA modifier is attached to the wrong head
RetrievalA query and document collectionRanked document identifiersRelevant evidence is absent from the returned set
Conditional generationA source text or instructionA new sequence of tokensA translation changes a negation, despite fluent wording
Dialogue/actionConversation plus permitted tools/stateA response or allowed actionA correct-looking response triggers the wrong action

Some tasks share a model architecture while keeping different outputs and scoring rules. Conversely, rules, statistical models and neural networks can compete on the same task. GLUE, for example, evaluates several sentence and sentence-pair problems while leaving model architecture open. That is a benchmark design choice, not a definition of all NLP. GLUE v3, introduction

For a supervised task, write a predictor as a function of a representation φ(x):

y^=fθ(ϕ(x)).\hat y=f_\theta(\phi(x)).

x is the supplied language input, φ is preprocessing or feature construction, and θ contains the fitted parameters. The desired quantity is error under the intended use distribution P, not just the training rows:

RP(f)=E(x,y)∼P[ℓ(f(ϕ(x)),y)].R_P(f)=\mathbb E_{(x,y)\sim P}\left[\ell\bigl(f(\phi(x)),y\bigr)\right].

A held-out test estimates a declared use condition only to the extent that its sampling and labels support that interpretation. A test made entirely from a sentence template can isolate a mechanism; it cannot establish performance on real messages from a city, age group or language.

Language modeling has a different immediate output: a distribution for the next token given its context. A conditional sequence model factors a sequence probability into successive predictions:

pθ(y1,…,yT∣x)=∏t=1Tpθ(yt∣x,y<t).p_\theta(y_1,\ldots,y_T\mid x)=\prod_{t=1}^{T}p_\theta(y_t\mid x,y_{<t}).

Here a declared end token may be included in the sequence. This factorization follows the probability chain rule. Sampling or choosing high-probability tokens is an additional procedure; a fluent sequence alone does not establish the correctness of an extracted fact or an external action. See Transformer for that architecture. SLP introduction, §1.1

A lost distinction creates a hard ceiling

A bag of words keeps each word’s count and discards order. It maps the two invented reviews to the same feature vector. For any deterministic classifier over those vectors, both examples must receive the same label. No amount of fitting can give different answers to identical representations.

Partition a finite labeled test into groups G_z with the same features z. Let n_zc be the number of examples in group z with label c. The best possible deterministic accuracy on those fixed representations is:

Amax⁡=1N∑zmax⁡cnzc.A_{\max}=\frac1N\sum_z\max_c n_{zc}.

To derive it, note that one predicted label can earn at most the largest class count in each group. Choosing that majority label independently for each group attains the sum. This is a ceiling on the finite supplied set, not a claim about unseen data or what a training algorithm will discover.

Our 16 contrast examples form eight bag-of-words groups. Each has one label of each kind, so the ceiling is 8/16=0.5. A deliberately restricted alternative keeps only the tokens after the last but. It produces eight groups whose labels are consistent, giving a ceiling of 1. The second representation is allowed to use order; it still does not handle general syntax or negation.

A small fitted baseline, not an unexplained API call

We use multinomial naive Bayes so the source of each score is visible. Let V be the training vocabulary, N_c the number of class-c documents, and C_cw the count of word w among those documents. With positive additive smoothing α:

p^(c)=NcNtrain,p^(w∣c)=Ccw+α∑v∈VCcv+α∣V∣.\hat p(c)=\frac{N_c}{N_{\rm train}},\qquad \hat p(w\mid c)=\frac{C_{cw}+\alpha}{\sum_{v\in V}C_{cv}+\alpha|V|}.

At prediction time, n_w(x) counts retained occurrences. The implementation scores:

sc(x)=log⁡p^(c)+∑w∈Vnw(x)log⁡p^(w∣c),y^=arg⁡max⁡csc(x).s_c(x)=\log\hat p(c)+\sum_{w\in V}n_w(x)\log\hat p(w\mid c),\qquad \hat y=\arg\max_c s_c(x).

This is the multinomial text model with a conditional independence assumption about token occurrences given the class. Taking logs turns a product into a sum without changing the maximizing class. Unknown words are ignored in this particular implementation; exact ties choose class zero. These conventions are part of its contract, not universal rules for NLP. IR book, Naive Bayes text classification

For a hand check, train class zero on red red and class one on blue, with α=1. The priors are both 1/2. Class zero gives red probability 3/4 and blue 1/4; class one gives red 1/3 and blue 2/3. For red blue, compare 3/32 with 1/9: class one wins. These unnormalized class scores are not calibration evidence. The broader derivation belongs in naive Bayes.

Accuracy and macro-F1 answer different questions

The program’s confusion matrix has true labels on rows and predictions on columns. For each of the fixed two classes, define precision, recall and F1 as:

Pc=TPcTPc+FPc,Rc=TPcTPc+FNc,F1,c=2TPc2TPc+FPc+FNc.P_c=\frac{TP_c}{TP_c+FP_c},\quad R_c=\frac{TP_c}{TP_c+FN_c},\quad F_{1,c}=\frac{2TP_c}{2TP_c+FP_c+FN_c}.

A zero denominator gives zero for that metric in this program. Then:

Accuracy⁡=∑cTPcN,MacroF1⁡=12(F1,0+F1,1).\operatorname{Accuracy}=\frac{\sum_cTP_c}{N},\qquad \operatorname{MacroF1}=\frac12(F_{1,0}+F_{1,1}).

An always-zero classifier on 97 zeros and three ones has accuracy 0.97, but macro-F1 is 97/197, about 0.4924. Even if an input set contains only zeros and all are correct, our fixed-two-class macro-F1 is 0.5: the absent class stays in the average. Report that convention rather than silently comparing it with a metric that drops absent classes.

Three conditions, one trained model

Save the complete program as nlp_tasks.py and run python3 nlp_tasks.py. It uses only the standard library; this edition’s run used Python 3.12.4. No corpus download or network service is required.

Training contains 24 invented sentences from the source names meal, service and film. Each source uses four positive/negative adjective pairs. Test sources are room and delivery, with 16 rows per condition: plain, contrast and negation. The labels for contrast follow the final adjective; negation labels are explicitly assigned probes. Both feature policies are declared before evaluation, and both use the same fitted model without retuning on test rows.

"""Original task-contract experiment; synthetic ASCII English, no external data.

Fits multinomial naive Bayes from training sources only. Compares a bag of words
with an explicitly limited last-clause policy, then retains a negation failure.
"""
import json
import math
import re
from collections import Counter


def tokens(text):
    if not isinstance(text,str) or not text.isascii():raise ValueError('This teaching tokenizer accepts ASCII strings only')
    return re.findall(r'[a-z]+',text.lower())


def checked_rows(rows):
    rows=list(rows)
    if not rows:raise ValueError('At least one labeled row required')
    ids=set()
    for row in rows:
        if not isinstance(row,dict) or set(row)!={'id','source','text','label'}:raise ValueError('Explicit id, source, text and label required')
        if type(row['label']) is not int or row['label'] not in (0,1):raise ValueError('Binary integer labels required')
        if any(not isinstance(row[k],str) or not row[k] for k in ['id','source']):raise ValueError('Nonempty identifiers required')
        if row['id'] in ids:raise ValueError('Duplicate row identifier')
        ids.add(row['id']);tokens(row['text'])
    return rows


def disjoint_sources(train,test):
    train=checked_rows(train);test=checked_rows(test)
    shared={r['source'] for r in train}&{r['source'] for r in test}
    if shared:raise ValueError('Source groups overlap: '+str(sorted(shared)))
    if {r['id'] for r in train}&{r['id'] for r in test}:raise ValueError('Row identifiers overlap')
    return True


def fit(rows,alpha=1.):
    rows=checked_rows(rows)
    if not isinstance(alpha,(int,float)) or isinstance(alpha,bool) or not math.isfinite(alpha) or alpha<=0:raise ValueError('Positive finite smoothing required')
    counts=[Counter(),Counter()];documents=[0,0]
    for row in rows:
        label=row['label'];documents[label]+=1;counts[label].update(tokens(row['text']))
    vocabulary=sorted(set(counts[0])|set(counts[1]))
    if not all(documents) or not vocabulary:raise ValueError('Both classes and a nonempty training vocabulary required')
    probabilities=[]
    for c in [0,1]:
        denominator=sum(counts[c].values())+alpha*len(vocabulary)
        probabilities.append({word:(counts[c][word]+alpha)/denominator for word in vocabulary})
    return {'vocabulary':vocabulary,'prior':[n/len(rows) for n in documents],
            'probability':probabilities,'alpha':float(alpha),'training_sources':sorted({r['source'] for r in rows})}


def features(text,policy='bag'):
    words=tokens(text)
    if policy=='last-clause' and 'but' in words:words=words[len(words)-words[::-1].index('but'):]
    elif policy not in ['bag','last-clause']:raise ValueError('Unknown feature policy')
    return Counter(words)


def scores(text,model,policy='bag'):
    counts=features(text,policy)
    # Sorted keys make equal count vectors follow the same floating-point order.
    terms=sorted((word,n) for word,n in counts.items() if word in model['probability'][0])
    return [math.log(model['prior'][c])+math.fsum(n*math.log(model['probability'][c][w]) for w,n in terms) for c in [0,1]]


def predict(text,model,policy='bag'):
    values=scores(text,model,policy)
    return int(values[1]>values[0])  # Exact ties select class zero.


def metrics(truth,predicted):
    truth=list(truth);predicted=list(predicted)
    if not truth or len(truth)!=len(predicted):raise ValueError('Equal nonempty label sequences required')
    if any(type(v) is not int or v not in [0,1] for v in truth+predicted):raise ValueError('Binary integer labels required')
    matrix=[[0,0],[0,0]]
    for y,p in zip(truth,predicted):matrix[y][p]+=1
    per_class=[]
    for c in [0,1]:
        tp=matrix[c][c];fp=matrix[1-c][c];fn=matrix[c][1-c]
        precision=tp/(tp+fp) if tp+fp else 0.;recall=tp/(tp+fn) if tp+fn else 0.
        f1=2*tp/(2*tp+fp+fn) if 2*tp+fp+fn else 0.
        per_class.append({'precision':precision,'recall':recall,'f1':f1})
    return {'n':len(truth),'confusion_true_rows':matrix,'accuracy':sum(matrix[c][c] for c in [0,1])/len(truth),
            'macro_f1':sum(v['f1'] for v in per_class)/2,'per_class':per_class}


def corpus(domains,kind):
    if kind not in ['train','plain','contrast','negation']:raise ValueError('Unknown synthetic condition')
    pairs=[('good','bad'),('pleasant','awful'),('excellent','terrible'),('helpful','useless')];rows=[]
    for domain in domains:
        for pair_index,(positive,negative) in enumerate(pairs):
            for label in [0,1]:
                chosen=positive if label else negative;opposite=negative if label else positive
                text=f'the {domain} was {chosen}' if kind=='train' else f'the {domain} is {chosen}'
                if kind=='contrast':text=f'the {domain} is {opposite} but {chosen}'
                if kind=='negation':text=f'the {domain} is not {opposite}'
                rows.append({'id':f'{kind}:{domain}:{pair_index}:{label}','source':domain,'text':text,'label':label})
    return checked_rows(rows)


def evaluate(rows,model,policy):
    rows=checked_rows(rows);truth=[r['label'] for r in rows];predictions=[predict(r['text'],model,policy) for r in rows]
    return metrics(truth,predictions)


def representation_bound(rows,policy):
    """Best possible empirical accuracy for any deterministic map of these features."""
    groups={}
    for row in checked_rows(rows):
        key=tuple(sorted(features(row['text'],policy).items()));groups.setdefault(key,[0,0])[row['label']]+=1
    return {'groups':len(groups),'best_deterministic_accuracy':sum(max(v) for v in groups.values())/sum(sum(v) for v in groups.values())}


def demo():
    train=corpus(['meal','service','film'],'train');model=fit(train)
    tests={kind:corpus(['room','delivery'],kind) for kind in ['plain','contrast','negation']}
    for rows in tests.values():disjoint_sources(train,rows)
    results={policy:{kind:evaluate(rows,model,policy) for kind,rows in tests.items()} for policy in ['bag','last-clause']}
    pair=tests['contrast'][:2]
    return {'training_rows':len(train),'training_sources':model['training_sources'],'test_sources':['room','delivery'],
            'vocabulary_size':len(model['vocabulary']),'alpha':model['alpha'],'results':results,
            'contrast_bounds':{policy:representation_bound(tests['contrast'],policy) for policy in ['bag','last-clause']},
            'minimal_pair':[r['text'] for r in pair],'bag_pair_same_counts':features(pair[0]['text'])==features(pair[1]['text']),
            'scope':'Original synthetic English rubric: final contrast clause determines its label; negation labels are declared probes. Not a real-review benchmark, a full NLP pipeline or calibrated-probability claim.'}


if __name__=='__main__':print(json.dumps(demo(),indent=2))

The tokenizer accepts ASCII strings only and keeps lowercase alphabetic runs. It therefore excludes Chinese input, ignores digits and punctuation, and does not claim to segment general English. The training vocabulary has 13 words; test-source words plus is, but and not are absent. A source-disjoint split has not made the unknown-word policy disappear.

PolicyPlain accuracy / macro-F1Contrast accuracy / macro-F1Negation accuracy / macro-F1
Bag of words1 / 10.5 / 1/30 / 0
Last clause after but1 / 11 / 10 / 0

The contrast failure is explainable before running: both adjectives contribute equal opposing evidence, and the bag cannot preserve their order. Last-clause selection keeps the adjective chosen by our label rule, so it passes that condition. In negation sentences, neither policy models not; the opposite adjective remains the decisive known feature, so every answer is wrong. A successful targeted repair has not become general language understanding.

The program rejects overlapping source groups and duplicate row identifiers, uses training-only vocabulary and probabilities, and reports complete confusion matrices. Fifteen focused tests cover hand probabilities, log/product agreement, word-order invariance, an exhaustive small representation ceiling, metric denominators, invalid inputs and retained negation failure. Draft-specific checks also execute the program extracted from MDX; prototype success alone does not establish article correctness.

Training token counting is O(M) for M extracted occurrences, followed by vocabulary sorting O(V log V) and two probability tables of size V. For a prediction with u distinct tokens, feature sorting costs O(u log u) and two class scores cost O(u), in addition to reading/tokenizing the string. Memory contains the two vocabulary tables and the current count vector. This describes the implemented teaching baseline, not a Transformer inference cost.

Which claim has the experiment earned?

GLUE distinguishes its broad benchmark from a hand-chosen diagnostic collection. Its authors caution that diagnostic performance should not be treated as the natural distribution of downstream applications. Our conditions are more restricted still: they are original synthetic examples, not GLUE data or a reproduction of its systems. GLUE v3, §4 Intended Use

To move toward a real classifier, first define whose texts it will see and what labels mean. Preserve document and author/source identifiers, agree on ambiguous cases, and split according to the intended deployment question. A future-time split tests a different issue from a new-source split. Keep the initial baseline and examine errors by condition before choosing additional features or a different model. See train/validation/test splits and model evaluation.

Rules can be transparent and useful for a narrow format; sparse statistical models provide inexpensive fitted baselines; neural sequence models can condition on richer context. Each still needs the same task and evidence contract. Returning labels through a chat interface does not remove label definitions, evaluation or failure costs.

This example contains no real multilingual corpus, annotator disagreement, calibrated confidence, production latency or user study. Those are additional measurements. A balanced toy set does not justify using accuracy alone when missed cases and false alarms have different consequences.

Find the claim that goes too far

  1. Basic understanding. Two reviews have the same word counts and opposite labels. Can a deterministic classifier that receives only those counts answer both correctly?

    Answer: No. It receives the same representation twice and must return the same label. Change the representation or accept at least one error; adjusting parameters alone cannot separate the pair.

  2. Hand calculation. For truth [0,0,0,1] and predictions [0,1,1,1], find the true-row confusion matrix, accuracy and macro-F1 under our convention.

    Answer: The matrix is [[1,2],[0,1]]. Accuracy is 2/4. Class zero has TP=1, FP=0, FN=2, and class one has TP=1, FP=2, FN=0; both F1 values are 1/2, so macro-F1 is also 1/2.

  3. Counterexample. The last-clause policy reaches 1.0 contrast accuracy. Why does the room is not bad expose a different problem, and what does the demonstration predict for it?

    Answer: There is no but, so the whole word count is retained. not is outside the training vocabulary, while bad supports class zero. The declared positive probe label is missed. A last-clause rule does not implement negation.

  4. Transfer. A real review classifier is meant for new hotels, but training and testing use different sentences from the same hotels. What comparison and evidence should be added before claiming new-hotel performance?

    Answer: Hold out the relevant source groups, document the grouping and label policy, keep a simple baseline, and report scores plus representative failures on those held-out groups. If choices are tuned there, reserve a separate final test. This addresses the stated generalization question; the synthetic room/delivery split alone is not evidence about hotels.

Follow the task, then follow the model

SLP supplies the broad task map and language-model entry point. The IR book supplies the multinomial scoring model. GLUE supplies a concrete example of separating aggregate task scores from targeted diagnostic analysis. Here the representation ceiling, sentence templates, probabilities, metrics and failures are inspectable original computations, not copied benchmark examples or reported model rankings.

Continue with linguistic structure to study competing analyses of the same sentence, and text normalization to inspect information lost before feature extraction. This article does not repeat later parsing, translation or large-language-model algorithms; it supplies the questions those implementations must answer.

Make a prediction, then check

What follows from two examples having identical word counts but different labels?

Choose one answer

Learning objectives

  • Specify input, output, annotation and evaluation for a language task.
  • Derive the finite accuracy ceiling imposed by a representation.
  • Run a training-only multinomial baseline and retain its failures.
  • Distinguish diagnostic success from application evidence.

Prerequisites & connections

Explore related knowledge →

References

  1. Speech and Language Processing, introduction, August 19 2026 draft
    Daniel Jurafsky; James H. Martin · 2026
  2. Introduction to Information Retrieval — Naive Bayes text classification
    Christopher D. Manning; Prabhakar Raghavan; Hinrich Schütze · 2008
  3. GLUE: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding (v3)
    Alex Wang; Amanpreet Singh; Julian Michael; Felix Hill; Omer Levy; Samuel R. Bowman · 2019

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-08 · Codex single-AI-author technical check: scoped task, multinomial-model and diagnostic-evaluation sources; eight paired equations, finite representation ceiling, training-only probabilities, fixed-class metric denominators, original contrast/negation failures, four explained exercises and computed SVGs. Formal checks execute production MDX; full article browser acceptance recorded separately. Not human peer review or real-corpus performance evidence.

  • Compared both manuscripts: task input/output and annotation contracts, expected-risk versus empirical evidence, chain-rule sequence factorization, deterministic representation ceiling, multinomial smoothing/log scores, fixed two-class F1 including absent labels, four explained exercises.
  • Fifteen independent prototype tests are embedded in the standalone production suite, plus six publication checks. Hand probabilities, permutation invariance, exhaustive finite classifier ceiling, leakage boundaries, unknown words and denominator conventions.
  • 24 synthetic ASCII-English training rows, source-disjoint16-row conditions, unchanged fitted model and predefined policies. Bag contrast accuracy0.5 versus last-clause1; both negation accuracies0. Diagnostic data and a fixed source split do not establish real review understanding.
  • Four original SVGs bind actual output and raw data. Final isolated bilingual, three-width/four-font validation passed and desktop/mobile screenshots were inspected. Full article acceptance is recorded separately. Single-AI-author technical check, not independent human review; no upstream code copied or executed.

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.