Lesson 2 of 12 · The Setup
Regression vs Classification
Regression predicts numbers, classification predicts categories. Frame one dataset both ways in scikit-learn, read class probabilities and avoid common mix-ups.
- 12 min read
- Intermediate
- Reviewed
- Decide whether a problem is regression or classification by looking at its label
- Frame the same data as both kinds of problem in scikit-learn
- Read a classifier's class predictions and class probabilities
- Tell binary, multi-class and multi-label problems apart
- Avoid the classic mix-ups between regressors and classifiers
The idea in plain words
The kind of label decides the kind of supervised problem:
- Regression: the label is a number on a scale, such as minutes, prices or temperatures. Being close matters: predicting 31 minutes when the truth is 32 is a good answer, and predicting 50 is a bad one.
- Classification: the label is one of a fixed set of categories, such as spam or not spam, or which of three flower species. A predicted class is simply right or wrong, although the model's confidence still tells you something.
You met both words in Introduction to Machine Learning. This lesson is about what actually changes between them: what the model outputs, how you read it, and how to pick the framing when a problem could go either way.
| Regression | Classification | |
|---|---|---|
| Label | A number on a scale | A category from a fixed list |
| Prediction | A number, such as 32.7 minutes | A class, such as "late", usually with a probability |
| How wrong? | By how much (distance matters) | Right or wrong, and how confident |
| Typical metrics | MAE, RMSE | Accuracy, precision, recall |
| scikit-learn models | LinearRegression, ...Regressor | LogisticRegression, ...Classifier |
Regression is often pictured as a line (or curve) drawn through the data. Here are 16 food deliveries: distance on the x-axis and delivery time on the y-axis. The fitted line is a regression model with one feature: for any distance, it predicts a number of minutes.
One dataset, two questions
A food delivery company has 200 past orders: the distance in kilometres, the number of items, and how long delivery took. From the same orders it can ask two different questions:
- How many minutes will this order take? The label is the delivery time: regression.
- Will this order be late (over 30 minutes)? The label is late or not late: classification.
import numpy as np
from sklearn.linear_model import LinearRegression, LogisticRegression
rng = np.random.RandomState(0)
distance = rng.uniform(1, 15, size=200) # km from the restaurant
items = rng.randint(1, 10, size=200) # items in the order
minutes = 10 + 2 * distance + items + rng.normal(0, 4, size=200)
X = np.column_stack([distance, items])
y_minutes = minutes # label 1: a number
y_late = (minutes > 30).astype(int) # label 2: a category (1 = late)
reg = LinearRegression().fit(X, y_minutes)
clf = LogisticRegression().fit(X, y_late)
new_orders = [[3, 2], [9, 5], [12, 6]]
print("Regression, minutes: ", reg.predict(new_orders).round(1))
print("Classification, late?: ", clf.predict(new_orders))
print("Probability of late: ", clf.predict_proba(new_orders)[:, 1].round(2))Regression, minutes: [17.8 32.7 39.8] Classification, late?: [0 1 1] Probability of late: [0.01 0.82 0.99]
The features are identical; only the label changed. The regression model answers with minutes: about 18 for a short order, 33 and 40 for the longer ones. The classifier answers with a class (0 = on time, 1 = late) and, through predict_proba, with a probability for each class. Column 1 holds the probability of class 1, "late".
predict simply picks the most likely class, which for two classes means "late if the probability is at least 0.5". The probabilities carry extra information: 0.82 and 0.99 are both "late", but the model is much more certain about the second order. Handling Imbalanced Classes shows why you sometimes choose a cut-off other than 0.5.
Why not use regression for categories?
The late or not-late label is stored as 0 and 1, which are numbers. So why not fit an ordinary regression model to it? Try it:
import numpy as np
from sklearn.linear_model import LinearRegression, LogisticRegression
rng = np.random.RandomState(0)
distance = rng.uniform(1, 15, size=200)
items = rng.randint(1, 10, size=200)
minutes = 10 + 2 * distance + items + rng.normal(0, 4, size=200)
X = np.column_stack([distance, items])
y_late = (minutes > 30).astype(int) # 0 = on time, 1 = late
wrong = LinearRegression().fit(X, y_late) # a regression model on a 0/1 label
right = LogisticRegression().fit(X, y_late) # a classifier
orders = [[1, 1], [8, 4], [15, 9]]
for order, a, b in zip(orders, wrong.predict(orders), right.predict_proba(orders)[:, 1]):
print(f"order {order}: linear regression says {a:5.2f}, logistic regression says {b:.2f}")order [1, 1]: linear regression says -0.23, logistic regression says 0.00 order [8, 4]: linear regression says 0.53, logistic regression says 0.58 order [15, 9]: linear regression says 1.34, logistic regression says 1.00
Linear regression happily predicts −0.23 and 1.34. If you read those as probabilities of being late, they are impossible: a probability can't be below 0 or above 1. A straight line keeps going forever, while a probability must stay between 0 and 1. Logistic regression, despite the word "regression" in its name, is a classifier: it bends its output into the range 0 to 1 (the Linear Models lesson shows how).
Binary, multi-class and multi-label
Classification problems come in three shapes:
scikit-learn classifiers handle multi-class problems with no extra code: give them a label with three classes and predict_proba returns three probabilities per example. The iris dataset has measurements of 150 flowers from three species:
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
iris = load_iris()
names = iris.target_names.tolist() # ['setosa', 'versicolor', 'virginica']
model = LogisticRegression(max_iter=1000).fit(iris.data, iris.target)
flowers = iris.data[[0, 75, 130]] # three flowers, one of each kind
for row in model.predict_proba(flowers):
shares = " ".join(f"{name} {p:.3f}" for name, p in zip(names, row))
print(f"{shares} -> {names[row.argmax()]} (sum {row.sum():.2f})")setosa 0.982 versicolor 0.018 virginica 0.000 -> setosa (sum 1.00) setosa 0.005 versicolor 0.920 virginica 0.075 -> versicolor (sum 1.00) setosa 0.000 versicolor 0.029 virginica 0.971 -> virginica (sum 1.00)
Each row is one flower, with one probability per species, and each row adds up to 1. The prediction is the species with the largest probability, which argmax finds. (The middle flower is 92% versicolor and 7.5% virginica: those two species look more alike than either does to setosa.)
max_iter=1000 gives the training more steps. With the default of 100, training on this data stops before it has finished and scikit-learn prints a ConvergenceWarning. Multi-label problems need models built for them, such as wrapping a classifier in MultiOutputClassifier; they are less common, and this course sticks to one label per example.
Choosing the framing
Most problems are clear-cut. For the rest, ask what the prediction will be used for.
| Problem | Framing | Why |
|---|---|---|
| Price of a flat | Regression | A quantity where close counts |
| Is this transaction fraud? | Binary classification | Two categories |
| Which department should get this email? | Multi-class classification | One of several categories |
| Star rating (1 to 5) of a review | Either | Ordered categories: regression respects the order, classification ignores it |
| Number of items a shop will sell tomorrow | Regression | A count is still a quantity |
| Will delivery take over 30 minutes? | Either | Predicting minutes keeps more information; you can apply the 30-minute cut-off afterwards |
The last row is worth remembering. If you predict the number and apply the threshold later, you can change the threshold (30 minutes today, 25 next month) without retraining, and you still know whether an order is a little late or very late. Turning a number into categories throws information away, so do it only when the decision really is a yes or no.
Common mistakes
Practice
A classifier gave these class probabilities for three photos. Turn each row into a prediction: print the most likely class and its probability.
classes = ["cat", "dog", "rabbit"]
probabilities = [ # one row per photo, one column per class
[0.20, 0.70, 0.10],
[0.60, 0.30, 0.10],
[0.10, 0.25, 0.65],
]
# For each photo, print the class with the highest probability and that
# probability with two decimals, for example:
# dog (0.70)
for row in probabilities:
pass
A hospital wants to predict how many days each patient will stay. What kind of problem is this?
Summary
- Regression predicts a number on a scale; classification predicts one of a fixed set of categories.
- Classifiers return a class with
predictand a probability for every class withpredict_proba; the probabilities for one example add up to 1. - Don't fit a regression model to class labels: a straight line produces "probabilities" below 0 and above 1. Logistic regression is a classifier.
- Classification can be binary, multi-class or multi-label; scikit-learn classifiers handle multi-class labels automatically.
- When a problem could go either way, predicting the number usually keeps more information than predicting a category.
Next: Loss Functions, the score a model uses to measure its own mistakes.
Finished reading? Tick it off to track your progress.