Sub topic 1
The task: assigning labels to documents
Text classification takes a piece of text and assigns it one label from a fixed set. A spam filter, a support-ticket router, a sentiment tagger, and a news-topic sorter all have this shape. This tutorial builds one such system with TF-IDF features and logistic regression. This chapter sets up the problem: what the inputs and outputs are, how the data should be organized, and what a first honest baseline looks like. The later chapters cover the feature extraction and the model.
Prerequisites
This chapter assumes you have the following:
- Basic Python, including lists, loops, and importing libraries.
- The core supervised learning vocabulary: features, labels, training set, test set, and overfitting.
- Basic NumPy and pandas. The examples use NumPy arrays and scikit-learn datasets.
- Comfort reading simple probability notation such as P(y | x). Logarithms matter later, when we reach TF-IDF.
You need scikit-learn and numpy installed. The fetch_20newsgroups function downloads a dataset the first time it runs, so you need an internet connection for that call.
What the task looks like
Text classification is supervised learning. You have a collection of documents, each paired with a label chosen by a person or a trusted process. You want a function that predicts the label of a document it has never seen.
In notation:
- A document is a string of text, written x.
- A label is one element of a fixed set of classes, written y.
- The training data is a list of pairs (x₁, y₁), (x₂, y₂), …, (xₙ, yₙ).
- The goal is a function f such that f(x) is usually equal to the true label of x.
The word "document" is used loosely. It can be a tweet, an email, a product review, a support ticket, a paragraph, or a whole article. What counts as one document is a design decision that you make before any modelling. It fixes what one row of your data is, and it fixes what the model's prediction applies to.
A classical text classifier never reads text directly. Its pipeline has two stages:
- A vectorizer turns each string into a row of numbers. The next chapters build this part with tokenization, bag-of-words counts, and TF-IDF weighting.
- A classifier takes that row of numbers and outputs a label. Here the classifier is logistic regression.
Kinds of classification problems
The shape of the label set determines which model setup and which metrics you use. Three cases are common.
| Problem type | Labels per document | Example | Typical setup |
|---|---|---|---|
| Binary | Exactly one of two | Spam or not spam | One probability, P(spam) |
| Multiclass | Exactly one of K > 2 | Newsgroup topic | One score per class, pick the largest |
| Multilabel | Zero or more of K | Tags on a blog post | One independent binary decision per tag |
This tutorial focuses on multiclass classification, and binary classification is the K = 2 special case. Multilabel problems need a different setup, because the classes are not mutually exclusive. In scikit-learn they are usually handled by fitting one binary classifier per label.
A frequent early mistake is to treat a multilabel problem as multiclass. If a document can legitimately carry two tags, forcing a single label throws information away. It also makes the labels look inconsistent, because annotators will disagree about which tag is "the" one.
Where labels come from
The model can only learn what the labels encode. Before you pick features, ask three questions about your labels:
- Who assigned them? Human annotators, a rule, a user action such as clicking "report spam", or a different model. Each source has its own noise and bias.
- Are they consistent? If two annotators disagree on 20% of documents, no classifier can reliably beat that ceiling on those documents.
- Do they match the decision you need to make? Product reviews labelled by star rating are a proxy for sentiment. A one-star review that says "arrived fast, but the colour was wrong" is a mixed case that the rating compresses.
Labels derived from a source that will not exist at prediction time cause a particular kind of failure. Suppose a "priority" label was set by a person who read the whole ticket, including the resolution notes. If you train on text that includes those notes, the model looks excellent in testing and fails in production, where the notes do not exist yet. Include only text that will be available when the prediction is needed.
A concrete dataset
We use the 20 Newsgroups corpus that ships with scikit-learn. It is a set of Usenet posts, each labelled with the newsgroup it was posted to. To keep outputs small we use three groups that differ in topic: space, cars, and politics.
The remove argument strips the headers, signature footers, and quoted replies. This matters. Headers contain the newsgroup name and the posting host, which are shortcuts that make the task artificially easy and do not generalize to other text. Removing them makes the task more realistic.
import numpy as np
from sklearn.datasets import fetch_20newsgroups
categories = ["sci.space", "rec.autos", "talk.politics.misc"]
remove = ("headers", "footers", "quotes")
train = fetch_20newsgroups(subset="train", categories=categories, remove=remove)
test = fetch_20newsgroups(subset="test", categories=categories, remove=remove)
print("train documents:", len(train.data))
print("test documents:", len(test.data))
print("classes:", train.target_names)
counts = np.bincount(train.target)
for name, count in zip(train.target_names, counts):
print(f"{name:20s} {count}")
print("\nFirst training document (first 300 characters):")
print(train.data[0][:300])
print("label:", train.target_names[train.target[0]])The returned object has three fields you will use throughout:
datais a list of raw strings, one per document.targetis an array of integers, one per document, indexing into the class list.target_namesmaps each integer to its class name.
The split is predefined. subset="train" and subset="test" come from a date-based split made by the dataset's authors, so the test posts were written after the training posts. This is a better test of generalization than a random split, because real deployment also predicts on future text.
Always compute a baseline first
Before building anything, find out what a model that ignores the text achieves. The simplest baseline always predicts the most frequent class. If your classes are balanced across three groups, this gives about one third accuracy. If one class makes up 90% of the data, it gives 90%, which is why accuracy alone can mislead you on skewed data. Chapter 12 returns to that problem.
import numpy as np
from sklearn.datasets import fetch_20newsgroups
from sklearn.dummy import DummyClassifier
from sklearn.metrics import accuracy_score
categories = ["sci.space", "rec.autos", "talk.politics.misc"]
remove = ("headers", "footers", "quotes")
train = fetch_20newsgroups(subset="train", categories=categories, remove=remove)
test = fetch_20newsgroups(subset="test", categories=categories, remove=remove)
# DummyClassifier ignores the features, so placeholder columns are enough.
X_train = np.zeros((len(train.data), 1))
X_test = np.zeros((len(test.data), 1))
baseline = DummyClassifier(strategy="most_frequent")
baseline.fit(X_train, train.target)
pred = baseline.predict(X_test)
print("majority-class accuracy:", round(accuracy_score(test.target, pred), 3))Write this number down. Every later result in the tutorial is meaningful only relative to it. A classifier that scores 0.85 where the baseline scores 0.35 has learned a lot. One that scores 0.85 where the baseline scores 0.83 has learned very little.
Splitting data correctly
You need data the model has never touched to estimate how it will behave on new documents. The standard layout has three parts:
- Training set. The model's parameters and the vectorizer's vocabulary are fitted here.
- Validation data. Used to compare settings such as n-gram range or regularization strength. Chapter 10 does this with cross-validation, which rotates the validation role across slices of the training set.
- Test set. Touched once, at the end, to report a final number.
The most common error in text work is leaking information from the test set into training. It happens subtly. If you build a vocabulary or compute IDF weights on the full corpus before splitting, test documents have influenced the features. The model then sees test-set word frequencies that it would not have in production. The remedy is to fit every learned step only on training data. Chapter 8 shows how a scikit-learn Pipeline enforces this automatically.
A second leak is duplication. Many real corpora contain near-identical documents, such as forwarded emails, reposted articles, or template-generated tickets. If copies land on both sides of a random split, the model scores well by memorizing. When the data has a time order or a source (author, customer, thread), prefer a split that respects it.
Common errors at the framing stage
These mistakes happen before any model is trained, and later tuning cannot repair them.
- Labels that leak the answer. Headers, usernames, file paths, or boilerplate that correlates with the label but would not exist, or would not be informative, in deployment.
- An undefined unit of prediction. Classifying whole threads in training but single messages in production.
- Ignoring the class balance. Reporting accuracy without checking what the majority-class baseline achieves.
- Too few examples per class. Rare classes with a handful of documents give unstable estimates. You can only measure their performance with wide error bars.
- An unstable label set. If categories are added or redefined over time, the old training data may no longer match the new definitions.
Why a linear model on word features is a good start
For many labelling problems, the class is mostly decided by which words appear. Space posts mention "orbit" and "launch". Car posts mention "engine" and "dealer". A model that sees only word weights discards word order and context, but it keeps the strongest signal at very low cost. It trains in seconds on laptops, scales to hundreds of thousands of features, and, as chapter 11 shows, its learned weights can be read directly. Even teams that end up using neural models usually keep a TF-IDF and logistic regression baseline to compare against.
The rest of the tutorial builds this baseline step by step. The next chapter turns raw strings into tokens, the units that all later features are counted from.
Exercise
You are building a classifier to route customer emails into the categories "billing", "technical", and "other". In your data, 70% of emails are "other". A model that always predicts "other" is correct on 70% of test emails. Your first TF-IDF model scores 72% accuracy. Is it a good model? Name two things you would check next.
Show answer
The 72% is barely above the 70% majority-class baseline, so the model has learned very little, and accuracy alone hides this. Two checks: first, look at per-class precision and recall (especially for "billing" and "technical"), since a model that mostly predicts "other" can have high accuracy and near-zero recall on the classes you care about. Second, check for framing problems such as too few examples in the smaller classes, inconsistent labels, or a split that does not match deployment. Confusion matrices and macro-averaged F1 give a fairer picture than accuracy on skewed data.
Exercise
A teammate computes TF-IDF weights on all 10,000 documents and then splits them 80/20 into train and test sets. What is wrong with this order, and how should it be done instead?
Show answer
IDF values and the vocabulary are learned from the data. Computing them on all documents lets the test set influence the features, which is leakage and makes the test score optimistic. Split first, fit the vectorizer on the training portion only, and then apply it with transform to the test portion. A scikit-learn Pipeline does this automatically.