Sub topic 9
Predicting on New Text
This chapter assumes that you have Python, a saved fine-tuned checkpoint, and basic knowledge of tokenization and classification. The example uses the DistilBERT model trained on the IMDB sentiment dataset in the previous chapters.
How inference works
Inference is the process of using a trained model to predict labels for text that was not part of training. The inference path repeats the same important preprocessing steps used during training:
- The tokenizer converts text into token IDs.
- The tokenizer truncates text that is longer than the model's maximum length.
- The model converts the tokens into logits, which are raw scores for each label.
- A softmax function converts logits into scores that add up to 1.
- The pipeline returns the predicted label and its score.
The input must use the same tokenizer and label mapping as the fine-tuned model. Using a different tokenizer can produce incompatible inputs.
flowchart TD
A[New text] --> B[Tokenizer]
B --> C[Token IDs with truncation]
C --> D[Fine-tuned encoder]
D --> E[Classification head]
E --> F[Label scores]
F --> G[Predicted label]Using a text-classification pipeline
A Hugging Face pipeline combines tokenization, model execution, and output formatting. Load the model directory saved after training:
from transformers import pipeline
classifier = pipeline(
"text-classification",
model="imdb-distilbert",
tokenizer="imdb-distilbert",
truncation=True,
max_length=256,
)
texts = [
"A warm, funny film with a great cast.",
"Two hours I will never get back.",
]
predictions = classifier(texts)
for text, candidates in zip(texts, predictions):
prediction = candidates[0]
print(
f"{prediction['label']}: "
f"{prediction['score']:.3f} | {text}"
)With the label mapping from training, the output might resemble this:
POSITIVE: 0.998 | A warm, funny film with a great cast.
NEGATIVE: 0.997 | Two hours I will never get back.The score is the model's softmax score for the selected label. Treat it as a confidence-like score, not as a guaranteed probability. A model can assign a high score to an incorrect prediction.
The truncation=True argument makes long inputs fit within the chosen maximum length. In this example, text beyond 256 tokens is removed. Truncation can remove important information, so inspect the length distribution of your production inputs before choosing max_length.
Batch inference and labels
Batching sends several examples through the model together. It usually improves throughput because hardware can process multiple inputs in parallel. The pipeline handles the padding needed for each batch.
For a larger collection, process manageable batches rather than placing every document in one call:
def classify_in_batches(classifier, texts, batch_size=32):
results = []
for start in range(0, len(texts), batch_size):
batch = texts[start:start + batch_size]
results.extend(classifier(batch))
return results
texts = [
"The story was clever and the acting was excellent.",
"The plot made no sense and the ending was rushed.",
"An average movie with a few good scenes.",
]
results = classify_in_batches(classifier, texts)
for text, candidates in zip(texts, results):
best = candidates[0]
print({"text": text, "label": best["label"], "score": best["score"]})| Inference concern | Practical choice |
|---|---|
| Long documents | Truncate, split into sections, or use a model with a longer context |
| Many inputs | Use batches and measure memory use |
| Unbalanced labels | Review per-class metrics and consider a decision threshold |
| High-stakes predictions | Add human review and calibrate scores |
When the input does not fit
A classifier trained on short reviews may perform poorly on a long report. Truncating the report to its first 256 tokens may hide the evidence needed for the prediction. A common alternative is chunking:
- Split the document into overlapping sections.
- Classify each section.
- Combine the section predictions using a documented rule, such as mean logits or majority voting.
Chunking changes the meaning of the prediction. It produces a document-level result from several segment-level results, so validate the aggregation rule on held-out documents.
A model also sees only patterns represented in its training data. Sarcasm, domain-specific language, spelling errors, and distribution changes can cause confident mistakes. Store the input, predicted label, score, model version, and preprocessing settings when predictions need to be audited.
Exercise
Why should a long document not simply be truncated without checking the task requirements?
Show answer
Truncation can remove the evidence needed for classification, causing a prediction based only on an incomplete part of the document. Splitting and validating an aggregation method may be safer.