Sub topic 1
What classification asks of a model
Prerequisites
This chapter assumes you know the following:
- Basic Python and NumPy, including arrays and boolean masks.
- Linear regression and the idea of a loss function.
- Basic probability: events and conditional probability.
- What a train/test split is.
You do not need calculus yet. Later chapters use derivatives and gradients.
The task in one sentence
Classification is supervised learning where the target is a category, not a number. You have examples with features x and a known label y. You want a model that sees a new x and says which category it belongs to.
Typical cases:
- Is this email spam or not spam?
- Is this tumor malignant or benign?
- Will this customer cancel next month?
In this tutorial the first target is binary classification. The label has two values, coded 0 (the negative class) and 1 (the positive class). Which class is "positive" is a choice you make. It usually means the event you care about finding, such as the disease or the fraud.
What the model must produce
A classifier can return three kinds of output. They carry different amounts of information.
| Output | Example | What you can do with it |
|---|---|---|
| Hard label | `1` | Act directly, but you cannot see how sure the model was. |
| Score | `2.3` | Rank examples, but the number has no fixed meaning. |
| Probability | `0.91` | Rank, compare to costs, and judge confidence. |
Logistic regression returns a probability: an estimate of P(y = 1 | x), the chance that the label is 1 given the features. A hard label is then derived from that probability by applying a threshold. The default threshold is 0.5. A later chapter shows why you may want a different one.
Keeping the probability step separate from the label step matters in practice. Two models can give the same labels and very different probabilities. The probabilities are what let you trade off the cost of a missed positive against the cost of a false alarm.
Where the data comes from
The setup assumes that each example is drawn from some unknown distribution over pairs (x, y). The label is allowed to be noisy. Two patients with identical measurements can have different outcomes. So the honest goal is not "predict y exactly". It is "estimate how likely each label is for this x", and that is a conditional probability.
This is also why accuracy on the training data is a weak guide. A model can memorize noise and look perfect on data it has seen. You judge a classifier on held-out data, using a split such as the one in the code below.
A first look at the data
The next example builds a small two-feature dataset with two overlapping groups. It uses the same data-generating idea as the NumPy implementation in a later chapter, so you will see it again.
import numpy as np
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(0)
X = np.vstack([
rng.normal(-1, 1, (100, 2)), # class 0 centered at (-1, -1)
rng.normal(1, 1, (100, 2)), # class 1 centered at (1, 1)
])
y = np.array([0] * 100 + [1] * 100)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=0
)
print("train shape:", X_train.shape)
print("test shape:", X_test.shape)
print("positive rate, train:", y_train.mean())
print("positive rate, test:", y_test.mean())The stratify=y argument keeps the share of positives the same in both splits. With balanced classes this is a minor detail. With rare positives it prevents a test set that has almost none.
The two groups overlap, because their centers are two standard deviations apart on each axis. No rule can separate them perfectly. That overlap is the normal situation, and it is why we need probabilities.
A baseline you must beat
Before fitting anything, compute what a model that ignores the features would score. The simplest one always predicts the majority class.
import numpy as np
y_test = np.array([0] * 25 + [1] * 25)
majority = np.bincount(y_test).argmax()
baseline_pred = np.full_like(y_test, majority)
print("baseline accuracy:", (baseline_pred == y_test).mean())
y_skewed = np.array([0] * 95 + [1] * 5)
majority = np.bincount(y_skewed).argmax()
print("skewed baseline accuracy:", (np.full_like(y_skewed, majority) == y_skewed).mean())On balanced data the baseline scores 0.5. On the skewed labels it scores 0.95 while never finding a single positive. This is the first reason accuracy alone misleads, and a later chapter on metrics builds on it.
Why the problem is harder than it looks
Three properties of classification shape every choice that follows.
- The output is bounded. A probability must lie between 0 and 1. A model that can output any real number needs a way to map its output into that range.
- The labels are categories, not quantities. The numbers 0 and 1 are names. The distance between them is not a measurement, so a loss based on squared distance is not naturally the right one.
- Errors have unequal costs. Missing a malignant tumor is usually worse than a false alarm. The model should expose enough information for you to act on that.
Logistic regression is built to respect all three. It keeps a linear score, which is easy to fit and interpret. It then passes the score through a function that squeezes it into the interval from 0 to 1. The next chapter shows why plain linear regression falls short on the first two points.
The roadmap
The diagram shows how the pieces of the tutorial connect to the task defined here.
Common mistakes at this stage
- Treating labels as ordered numbers. Coding classes
0,1,2for "cat", "dog", "bird" suggests that bird is twice cat. Binary labels avoid this. Multiclass labels need a method that does not assume order, covered later. - Evaluating on training data. Training accuracy overstates how the model behaves on new cases.
- Ignoring the base rate. The share of positives sets what a "good" accuracy is.
- Splitting without stratification on rare classes. A test set with two positives gives a noisy estimate of everything.
Exercise
A dataset has 990 negative examples and 10 positive examples. A model that always predicts negative is evaluated on it. What is its accuracy, and why is that number not useful here? What would you report instead of, or alongside, accuracy?
Show answer
Accuracy is 990 / 1000 = 0.99. The number is not useful because the model never finds a positive, so it has no value for the task, yet it scores almost perfectly. Report measures that look at the positive class, such as recall (here 0 of 10 positives found) and precision, along with the probabilities the model outputs.
Exercise
Why does the chapter prefer a model that outputs P(y = 1 | x) over one that outputs only a 0 or 1 label?
Show answer
A probability shows confidence and lets you choose a threshold that matches the costs of each error type. A hard label hides that information, so you cannot trade a missed positive against a false alarm without refitting.