Text classification
Text classification routes, tags and monitors messages at scale. A TF-IDF pipeline is the fast, cheap baseline every text project should start with.
Learning objectives
- Explain TF-IDF weighting
- Train and evaluate a text classifier in a pipeline
- Inspect which words drive predictions
- Analyse errors and spot label problems
- Compare a text classifier with a baseline using cross-validation
- Judge how many labelled examples are enough
Setup: the data and models from earlier modules (runs automatically when you press Run on any cell)
Python · setupimport random
import re
import numpy as np
import pandas as pd
random.seed(7)
templates = {
"delivery": ["My parcel arrived {d} days late and the box was crushed",
"Delivery took {d} days and the courier left it in the rain",
"Still waiting for my order after {d} days, no update",
"The tracking link never updated and delivery was {d} days late"],
"product": ["The {p} broke after a week",
"Love the {p}, great quality and well made",
"The {p} is much smaller than the photos suggest",
"Excellent {p}, works perfectly"],
"billing": ["I was charged twice for order {o}",
"Refund for order {o} still not received",
"The discount code did not apply at checkout",
"Invoice for order {o} shows the wrong amount"],
}
products = ["chopping board", "kettle", "desk lamp", "backpack", "water bottle"]
rows = []
for i in range(400):
cat = random.choice(list(templates))
msg = random.choice(templates[cat]).format(
d=random.randint(2, 9), p=random.choice(products), o="GFY-%05d" % random.randint(10000, 99999))
label = cat if random.random() > 0.08 else random.choice(list(templates)) # ~8% noisy labels
rows.append({"text": msg, "category": label})
messages = pd.DataFrame(rows)2.1 TF-IDF: weighting words that matter
Raw counts over-reward words that appear everywhere. TF-IDF (term frequency × inverse document frequency) raises the weight of words frequent in this message but rare across the collection, and lowers words that appear in almost every message.
from sklearn.feature_extraction.text import TfidfVectorizer
tfidf = TfidfVectorizer(ngram_range=(1, 2), min_df=2, sublinear_tf=True)
X_tfidf = tfidf.fit_transform(messages["text"])
print(X_tfidf.shape)
# The weights for one message: rarer, more telling words score higher
row = X_tfidf[0]
weights = pd.Series(row.data, index=tfidf.get_feature_names_out()[row.indices])
print(messages["text"].iloc[0])
print(weights.sort_values(ascending=False).head(5).round(2))
2.2 A text classifier in a pipeline
Put the vectoriser and model in one pipeline so the vocabulary is learned only from training data — the same leakage protection you met in Data Quality, Module 5.
Python · TF-IDF + logistic regressionfrom sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
X_train, X_test, y_train, y_test = train_test_split(
messages["text"], messages["category"], test_size=0.25, random_state=0, stratify=messages["category"])
clf = make_pipeline(TfidfVectorizer(ngram_range=(1, 2), min_df=2, sublinear_tf=True),
LogisticRegression(max_iter=1000))
clf.fit(X_train, y_train)
print(classification_report(y_test, clf.predict(X_test), digits=3))
Expect high but not perfect scores: the 8% of noisy labels cap how well any model can appear to do. Look at the errors before assuming the model is wrong — sometimes the label is.
2.3 What did the model learn?
vec = clf.named_steps["tfidfvectorizer"]
lr = clf.named_steps["logisticregression"]
words = vec.get_feature_names_out()
for i, cat in enumerate(lr.classes_):
top = np.argsort(lr.coef_[i])[-6:][::-1]
print(f"{cat:9}", ", ".join(words[top]))
Inspecting the strongest words is a fast sanity check. If a "billing" model relies on a customer's name or a date format, it has learned a shortcut that won't generalise.
2.4 Reading the errors
test = pd.DataFrame({"text": X_test, "actual": y_test, "predicted": clf.predict(X_test)})
errors = test[test["actual"] != test["predicted"]]
print(len(errors), "errors")
print(errors.head(8).to_string())
Sort errors into buckets: wrong label, genuinely ambiguous message, or model mistake. Only the last bucket is fixed by a better model; the first is fixed by better labels (see Data Quality, Module 4).
Read the rows above with that in mind. In almost every one, the message is plainly about one topic and the label says another: these are the deliberately wrong labels, and the model is right. On this dataset the model's reported accuracy understates how good it is.
2.5 Sentiment analysis
Sentiment is just classification with labels like positive, negative and neutral. The same pipeline works if you have labelled examples. Without them, an LLM can label a sample for you to check (Module 5) — or you can use an off-the-shelf sentiment model. Watch for sarcasm, negation and domain words ("sick" can be praise).
To see why negation is hard, here is the oldest approach of all: count positive words and subtract negative ones.
Python · a word-counting sentiment scorer, and where it failsPOSITIVE = {"love", "great", "excellent", "perfect", "good", "happy"}
NEGATIVE = {"broke", "broken", "late", "bad", "terrible", "wrong", "crushed"}
def score(text):
words = re.findall(r"[a-z']+", text.lower())
return sum(w in POSITIVE for w in words) - sum(w in NEGATIVE for w in words)
for review in ["Love the kettle, great quality",
"The lamp broke and the parcel was late",
"Not good at all",
"Oh great, another broken kettle. Perfect."]:
print(f"{score(review):+d} {review}")
The first two come out right. "Not good at all" scores as positive because the scorer never sees that "not" changes "good". The sarcastic last review also scores positive. A trained classifier with word pairs handles "not good"; sarcasm defeats most methods short of a large language model, and sometimes those too.
2.6 Is the model better than guessing?
As in any machine learning project, compare with a baseline, and don't trust a single split. Cross-validation gives a steadier estimate (see Machine Learning Fundamentals, Module 4).
Python · baseline and cross-validationfrom sklearn.dummy import DummyClassifier
from sklearn.model_selection import cross_val_score
baseline = DummyClassifier(strategy="most_frequent")
for name, model in [("always the commonest category", baseline), ("TF-IDF + logistic regression", clf)]:
scores = cross_val_score(model, messages["text"], messages["category"], cv=5)
print(f"{name:30} accuracy {scores.mean():.2f} ± {scores.std():.2f}")
2.7 How many labelled examples do you need?
Labelling is the expensive part of a text classifier. Before paying for thousands of labels, check how quickly the model improves with the ones you have.
Python · accuracy as the training set growsfor n in [10, 20, 50, 100, 300]:
small_text, small_labels = X_train.iloc[:n], y_train.iloc[:n]
model = make_pipeline(TfidfVectorizer(), LogisticRegression(max_iter=1000)).fit(small_text, small_labels)
print(f"{n:4} labelled messages test accuracy {model.score(X_test, y_test):.2f}")
With clear-cut messages like these, a few dozen examples already get close to the ceiling set by the noisy labels. Real messages are more varied and need more, but the shape is typical: fast gains at first, then a plateau. When you hit the plateau, more labels of the same kind won't help; cleaner labels or better guidelines will.
Use clf to classify three messages you write yourself — one clearly about each category, plus one that mixes two. Print each prediction with its probability (predict_proba).
Your turn# Write your code here, then press RunShow a solution
new = ["My kettle stopped working", "Charged twice, please refund", "Courier lost my parcel",
"The lamp arrived late and I was billed twice"]
for text, probs in zip(new, clf.predict_proba(new)):
best = probs.argmax()
print(f"{clf.classes_[best]:9} {probs[best]:.2f} {text}")
# Short or mixed messages get a lower top probability: good candidates for human review.A model can help clean its own training data. Using clf.predict_proba on all of messages, list the messages where the model is at least 80% confident of a category that differs from the label. How many are there, and do they look like labelling mistakes?
Your turn# Write your code here, then press RunShow a solution
probs = clf.predict_proba(messages["text"])
check = messages.assign(model=clf.classes_[probs.argmax(axis=1)], confidence=probs.max(axis=1).round(2))
suspects = check[(check["model"] != check["category"]) & (check["confidence"] >= 0.8)]
print(len(suspects), "likely label errors")
print(suspects.head(8).to_string())
# These go to a person to confirm. Don't relabel automatically: the model can be confidently wrong too.Key takeaways
- TF-IDF up-weights distinctive words and down-weights ubiquitous ones.
- Fit the vectoriser inside a pipeline to avoid leakage.
- Check the strongest words for shortcuts.
- Some 'errors' are wrong labels — read them.
- Sentiment is classification with care for negation and sarcasm.
- Counting positive and negative words fails on negation and sarcasm.
- Accuracy rises fast with the first labels, then plateaus; past that, improve label quality.