04 / 28 · Text Foundations
Corpora and evaluation
Training and evaluation boundaries, group leakage, confusion metrics, strict spans, and the limits of a twelve-message constructed corpus.
On this page 7
A routing rule recognizes the word broken. It catches “lamp broken after pickup” and misses “lamp sparks at switch.” Before replacing it with a more complex model, we need a collection that tells us which error matters and an evaluation that does not accidentally give the model the answer.
A corpus is a collection of language observations assembled under some selection process. It may contain messages, documents, conversations, or aligned inputs and outputs. Its usefulness depends on that process and the task definition. A large pile of text is not automatically a representative test set.
Three splits and what each is for#
Training data fits parameters, vocabulary statistics, and other learned components. Validation data supports choices such as preprocessing, hyperparameters, and thresholds. A test set estimates the performance of the selected procedure under a specified evaluation design. Once test outcomes guide repeated changes, the set is participating in selection and no longer plays the same role.
The distinction is about information flow. Computing document frequencies on the entire corpus and then training a classifier on only the training rows still allows test texts to influence the representation. A tokenizer fitted on all messages has the same issue. Fixed operations such as a specified Unicode normalization are different: they apply a rule without learning corpus frequencies.
The split unit should match the intended generalization. If deployment means new conversations, place complete conversations together. If it means future requests from familiar users, a time-based split may answer the relevant question. If it means unfamiliar users or organizations, hold out those groups. There is no random split that simultaneously answers every one of these questions.
The scikit-learn cross-validation guide describes group-based splitting precisely: a group does not occur in both training and evaluation partitions. This controls one source of dependence; it does not guarantee identical distributions or remove every shared template. Keep a separate record of the prediction time and which fields are available then.
For a real corpus, document why messages were collected, the languages and time range represented, the annotation instructions, and the permitted uses. Datasheets for Datasets motivates this documentation boundary. Its existence is not permission to reuse a dataset; source rights, personal information, and distribution terms need their own checks. Our worked collection is newly invented and contains no user records.
Leakage: when the split is not a split#
Consider six underlying equipment issues, each represented by two almost identical message copies. If the first copy of every issue goes into training and the second into evaluation, all six issue identities cross the boundary. A memorizing system can recognize issue-specific wording without solving the intended problem on new issues.
In the constructed split check, there are twelve rows. The row-based policy leaves six shared group identities. Holding the first four complete issues for training and the remaining two for evaluation leaves zero shared identities. These counts verify the split rule. They do not establish a particular model’s accuracy, because no classifier is run in this split demonstration.
Exact duplicates are only the easiest case. A copied message with changed punctuation, a quoted earlier message, or several summaries of one conversation may preserve enough information to leak. Conversely, two independent requests can contain the same short phrase. Deduplication should use the intended observation identity; deleting every repeated sentence can distort natural prevalence.
Another leak comes from fields created after the decision. An eventual queue name, a resolution note, or a future equipment status may correlate almost perfectly with the label. If those fields are not available when routing the initial message, they cannot be valid input features. A chronological split alone does not repair a feature assembled using future information.
Apply fitted preprocessing separately inside each validation fold. Otherwise information from the fold being evaluated can affect vocabulary selection or feature thresholds before the model is trained. A reproducible pipeline makes this ordering explicit and packages the fitted transformation with the estimator.
Accuracy, and when it lies#
For a fixed collection of labeled observations, accuracy is the number of correct predicted labels divided by . It answers an understandable question, but it weights each observation equally and does not distinguish error types.
Our toy annotation rule marks a report of an equipment fault needing inspection as positive. Requests about carrying cases, booking administration, and seal policy are negative under this deliberately narrow definition. The definition is part of the constructed example, not an operational safety policy.
There are twelve invented tickets, four positive and eight negative. A classifier that always predicts negative gets accuracy while finding no positive case. That score is not mathematically wrong. It is incomplete for a task whose purpose includes finding faults. Before optimizing accuracy, specify the relative cost or required recall of the relevant cases.
Even the label can be uncertain. “The lamp behaves strangely” may need clarification rather than a forced binary target. Annotation instructions should state how such cases are resolved, whether annotators saw extra context, and whether disagreement is retained. A model cannot reproduce information available to the annotator but absent from its input without relying on indirect correlations.
Precision, recall and F1#
Let count correctly predicted positive cases, negative cases predicted positive, positive cases missed, and correctly predicted negative cases. Precision divides by predicted positives; recall divides by actual positives:
The denominators refer to different populations. High precision means that many flagged cases belong to the positive class. High recall means that many actual positive cases are flagged. A system can increase recall by flagging more cases and introduce additional false positives in the process.
For nonzero denominators, the harmonic mean of precision and recall simplifies to
Substituting the two fractions and cancelling the common denominator gives the count form. It is often easier to audit directly. If a denominator is zero, state the reporting convention rather than silently dropping the class. The metric definitions also distinguish class averaging from averaging the underlying counts.
Worked example#
The classifier flags a ticket exactly when the whitespace-tokenized English text contains broken. The supplied messages and labels are:
| Message | Actual inspection | Rule flags |
|---|---|---|
lamp broken after pickup | 1 | 1 |
tripod broken at hinge | 1 | 1 |
microphone broken cable | 1 | 1 |
lamp sparks at switch | 1 | 0 |
replace broken carrying case | 0 | 1 |
is a broken seal acceptable | 0 | 1 |
extend the tripod booking | 0 | 0 |
return microphone tomorrow | 0 | 0 |
where is the pickup desk | 0 | 0 |
reserve a spare lamp | 0 | 0 |
change my collection time | 0 | 0 |
confirm the return receipt | 0 | 0 |
The confusion counts are , , , and . Therefore accuracy is , precision is , recall is , and positive-class F1 is . Every number can be recovered from the table.
For the negative class, roles reverse: its true positives are the six correctly rejected cases. Its F1 is . Macro F1 averages the two class scores, giving . Computing one F1 from averaged precision and recall is a different operation. For single-label classification with every class included, micro precision, recall, and F1 coincide with accuracy; this does not hold for every multilabel or partial-label evaluation.
This collection is a counterexample for a lexical rule, not a measured benchmark. The labels and wording were designed to make specific failure types visible. We would need independently collected and appropriately sampled data to estimate generalization.
Spans rather than tokens#
Extraction needs a matching rule. Take the exact string lamp ready on Friday. Its gold spans are (0,4,ITEM) and (14,20,DATE) in half-open code-point coordinates. A prediction of (0,4,ITEM) and (15,20,DATE) finds one exact span and misses the first character of Friday in the other.
Under strict matching of both boundaries and type, there is one true positive, one false positive, and one false negative. Span F1 is . A high token-level accuracy could hide that boundary mistake because most positions are outside entities. Partial-overlap scoring can answer another question, but it should not be reported as exact extraction.
Keep the coordinate system aligned with preprocessing. Gold spans in original code points and predictions in normalized bytes cannot be compared directly. A mismatch in evaluation coordinates can look like a modeling failure.
Intrinsic and downstream evaluation#
An intrinsic measure evaluates a component in isolation: token prediction loss, a representation similarity score, or exact span extraction. A downstream evaluation measures the result of using the component in the target workflow. Improving one does not logically imply improving the other.
A representation might lower language-model loss while leaving urgent-message routing unchanged. A search system might improve the rank of the correct instruction while a response generator still contradicts it. To locate the bottleneck, retain component measures and an end-to-end task measure with an explicit success condition.
For generated text, a single reference answer may not describe every valid response. Exact string agreement can penalize harmless wording changes, while surface overlap can reward an unsupported statement that shares many words. The evaluation contract needs to distinguish factual support, required content, format, and any human judgment procedure. Later task-specific topics develop these measures; they should not be replaced by an unexplained universal score.
Pitfalls that survive a correct split#
Repeatedly trying many models on one validation set selects partly for its particular noise. A final untouched test set helps estimate the selected procedure; it does not make an unrepresentative population representative. Record how much model and threshold selection used each partition.
An aggregate score can conceal poor performance for a language, equipment category, or message length. Slice results need denominators: one error among two observations is different evidence from one error among two thousand. Correlated messages from one issue also do not provide the same independent information as unrelated issues. Uncertainty calculations must respect the sampling unit; resampling individual rows can be misleading when groups are the independent units.
Threshold choice is another fitted decision. A threshold chosen to meet recall on the validation set should be evaluated unchanged on the test set. Choosing a fresh threshold after seeing test labels changes the experiment. A requirement on a population rate also needs uncertainty analysis; a rate observed on twelve constructed tickets cannot certify it.
Limitations#
The complete toy inputs make arithmetic auditable and isolate leakage mechanisms. They do not represent real message prevalence, annotation disagreement, languages, or deployment drift. No significance claim is made from their metric differences. A trustworthy real evaluation needs documented sampling and permission for the actual observations.
What you should remember#
Split according to the generalization question. Fit vocabulary and other learned transformations only on allowed training data. Record label and span definitions, denominators, averaging conventions, and threshold selection. Distinguish an exact calculation on a constructed example from evidence about a deployed system.
Reproducible example#
- The
evaluationcase in the standalone script contains all twelve invented messages. It computes confusion counts and metrics with rational arithmetic, checks group overlap for both split policies, and checks strict span F1. Saved results expose every prediction; there is no external dataset or pretrained model.
Next#
With a fixed evaluation boundary, we can build an inspectable model representation. Bag of words and TF-IDF turns token occurrences into vectors and shows what those vectors preserve and lose.
References#
- Scikit-learn developers. Cross-validation, version 1.9, grouped observations and group folds. The split examples here are independently specified.
- Scikit-learn developers. Precision, recall and F-measures, version 1.9, binary definitions and multiclass averaging. No manual data or code is reproduced.
- Timnit Gebru, Jamie Morgenstern, Briana Vecchione, Jennifer Wortman Vaughan, Hanna Wallach, Hal Daumé III, Kate Crawford. Datasheets for Datasets, 2021, abstract: documenting motivation, composition, collection, and recommended uses. This is a conceptual reference; its questionnaire is not reproduced.