Python Master Course V2 — 153. Text Classification and Leakage-Safe Evaluation
Purpose and learning outcomes
A classifier is only as convincing as its evaluation split. If two lightly edited copies of one support ticket appear on opposite sides of the split, a high score may measure memorization of that ticket. You will build a TF-IDF classifier whose split follows source families and whose report exposes class-specific errors. The included messages are educational examples, not evidence of real customer-support performance.
- Train a simple text classifier with a vectorizer pipeline
- Detect duplicates, source overlap and label leakage
- Inspect class-specific errors rather than only aggregate accuracy
Prerequisites
- 134–136: classification and validation
- 151–152: text features
Environment and execution
Use a project-specific virtual environment with a currently supported Python 3 release compatible with the packages below. Python 3.11 or 3.12 is a practical starting point. Run shell commands in a terminal, then run the Python blocks in order in one script or notebook kernel. They use only included data and local CPU computation. No account, API key, camera, or external dataset is required. Record the installed package versions with python -m pip freeze when you save your results; a random seed does not guarantee identical numerical behavior across library versions.
python -m venv .venv
# macOS/Linux: source .venv/bin/activate
# Windows PowerShell: .venv\Scripts\Activate.ps1
python -m pip install numpy scikit-learnUnderstand the model and its assumptions
Supervised text classification learns a mapping from text features to supplied category labels. Logistic regression produces a score for each class using weighted features. It is a useful baseline because it is fast and compatible with sparse TF-IDF matrices. The label definition matters: billing and delivery must be mutually interpretable, and genuinely mixed requests need a documented policy instead of arbitrary labeling.
Leakage can enter through preprocessing, duplicate documents, correlated sources, or the text itself. A subject line containing the final queue name may expose the answer. A template ID can let the model identify its source rather than its meaning. A vectorizer fitted before splitting learns vocabulary and document frequencies from the evaluation corpus. A Pipeline keeps vectorization inside model fitting, including cross-validation folds.
The split unit should match the deployment question. Here each group contains two variants of one authored intent. Holding out entire groups asks whether the classifier handles a new phrasing family. We deliberately include both categories in both partitions because an evaluation missing one category cannot measure its recall. For larger data, use a suitable group-aware splitter and inspect class coverage; do not assume random group selection preserves it.
Accuracy is the fraction of correct predictions, while class recall describes how many true members of that class were found. Precision asks how often a predicted category was right. A confusion matrix makes the two error directions visible. With only four held-out messages, one changed prediction moves accuracy by twenty-five percentage points, so numerical precision should not be mistaken for statistical certainty.
Worked example: build it in stages
Create records with text, label, and group stored separately. Split by a declared group list, assert no group overlap, and fit a vectorizer-classifier pipeline on training text. The dummy classifier establishes what can be achieved without reading the message. Print each held-out prediction alongside the report so that a small aggregate score cannot conceal a systematic failure.
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.dummy import DummyClassifier
from sklearn.metrics import classification_report, confusion_matrix
families = [
("b1", "billing", ["invoice total is wrong", "wrong total on my invoice"]),
("b2", "billing", ["payment was charged twice", "two payment charges appeared"]),
("b3", "billing", ["need a copy of my invoice", "please provide an invoice copy"]),
("d1", "delivery", ["parcel tracking has stopped", "tracking shows no parcel movement"]),
("d2", "delivery", ["delivery is later than expected", "late delivery has not arrived"]),
("d3", "delivery", ["where is the delivery parcel", "my parcel delivery is missing"]),
]
rows = [(g, label, text) for g, label, variants in families for text in variants]
held_out = {"b3", "d3"}
train = [r for r in rows if r[0] not in held_out]
test = [r for r in rows if r[0] in held_out]
assert {r[0] for r in train}.isdisjoint({r[0] for r in test})
X_train, y_train = [r[2] for r in train], [r[1] for r in train]
X_test, y_test = [r[2] for r in test], [r[1] for r in test]
model = make_pipeline(TfidfVectorizer(), LogisticRegression(max_iter=500))
model.fit(X_train, y_train)
prediction = model.predict(X_test)
labels = ["billing", "delivery"]
print(confusion_matrix(y_test, prediction, labels=labels))
print(classification_report(y_test, prediction, labels=labels, zero_division=0))
for text, truth, predicted in zip(X_test, y_test, prediction):
print(truth, predicted, text)
baseline = DummyClassifier(strategy="most_frequent")
baseline.fit(np.zeros((len(train), 1)), y_train)
print("dummy accuracy:", baseline.score(np.zeros((len(test), 1)), y_test))What the output means
The dummy accuracy is 0.5 because the test set is balanced and the baseline always selects one category. The learned classifier prints a 2-by-2 confusion matrix and measured class scores; do not copy an expected accuracy into your report. Rows follow true labels and columns predicted labels in the declared order. An error on a familiar word is a prompt to inspect the whole representation and label policy, not to relabel the example after seeing its prediction.
Guided lab and acceptance checks
Add a new family for each category, then reserve those families as a final test set. Use only the remaining families for selecting unigram versus bigram features. Include an ambiguous message such as “My delayed parcel invoice is wrong” in a separate challenge set and explain the expected routing policy.
Acceptance requires a source-group manifest, a duplicate check, a label-leakage review, and a report containing support counts for each class. Keep the original group split even if it lowers accuracy. If you change the category definitions after error analysis, explicitly version the dataset and repeat evaluation with fresh held-out examples.
Common mistakes and repairs
Randomly splitting the expanded variants defeats the purpose of grouping. Removing only exact duplicates does not remove near-duplicate templates. A classifier's top probability is not automatically calibrated confidence. Finally, repeatedly rewriting test messages until they pass converts the test set into training feedback. Fix code using development examples and preserve independent evidence.
Questions and answers
Why keep related paraphrases in the same partition?
They share an underlying source and often distinctive wording. Separating them lets the model exploit family-specific clues. A group split better approximates new-ticket families, although it still cannot reproduce the variety of a real deployment population.
Does Pipeline eliminate every leakage risk?
No. It prevents fitting its transformations on held-out rows when used correctly, but it cannot repair mislabeled splits, copied documents, future information in features, or a target encoded in a filename. Data provenance remains an independent responsibility.
Why report a dummy baseline?
A model can look impressive on an imbalanced dataset by predicting the common category. The baseline reveals performance available without text understanding. Beating it is a necessary comparison, not a guarantee that the classifier is useful.
What does zero_division=0 mean in the report?
It defines a display value when a metric denominator is zero, such as when no examples are predicted for one class. It prevents an undefined ratio from interrupting the report; it does not turn missing evidence into a good result.
Can this small dataset establish production accuracy?
No. It is too small and too authored to represent customer language, changing policies, and uncertain labels. Use it to verify mechanics. A production claim requires representative collection, adequate support, and evaluation aligned with the intended workflow.
Exercises
1. Implement a conservative normalized exact-duplicate check across the split. 2. Inspect whether a term occurring only in the held-out messages is absent from the fitted vocabulary. 3. Explain why the absence check does not prove that near-duplicate leakage is impossible.
Worked solutions and reasoning
Normalization catches identical content with harmless formatting changes. It cannot identify every paraphrase or shared template, so provenance-based grouping remains necessary. The vocabulary assertion is a focused regression check that the vectorizer was fitted only on training text.
import unicodedata
def fingerprint(text):
return " ".join(unicodedata.normalize("NFC", text).casefold().split())
train_keys = {fingerprint(t) for t in X_train}
test_keys = {fingerprint(t) for t in X_test}
assert train_keys.isdisjoint(test_keys)
vocabulary = model.named_steps["tfidfvectorizer"].vocabulary_
assert "provide" not in vocabularyRecap
A leakage-safe baseline combines a meaningful split unit, training-only feature learning, and transparent error inspection. Treat the group manifest and label policy as model artifacts. The score describes this evaluation design and dataset; it cannot answer a broader deployment question by itself.
Official references
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.