Velamuvi AIAcademy

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
In this lesson you will learn
  • 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.

RegressionClassification
LabelA number on a scaleA category from a fixed list
PredictionA number, such as 32.7 minutesA class, such as "late", usually with a probability
How wrong?By how much (distance matters)Right or wrong, and how confident
Typical metricsMAE, RMSEAccuracy, precision, recall
scikit-learn modelsLinearRegression, ...RegressorLogisticRegression, ...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.

203040502.557.51012.515(8.7, 38)(11, 39)(9.4, 36)(8.6, 36)(6.9, 30)(10, 33)(7.1, 22)(13.5, 41)(14.5, 43)(6.4, 22)(12.1, 41)(8.4, 30)(9, 37)(14, 48)(2, 21)(2.2, 18)Distance (km)Delivery time (minutes)
r = 0.92best line: y = 13.53 + 2.215xR² = 0.84
Regression: a line that turns a distance into a predicted 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.
Try it yourselfPython
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))
Output
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:

Try it yourselfPython
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}")
Output
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:

Try it yourselfPython
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})")
Output
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.

ProblemFramingWhy
Price of a flatRegressionA quantity where close counts
Is this transaction fraud?Binary classificationTwo categories
Which department should get this email?Multi-class classificationOne of several categories
Star rating (1 to 5) of a reviewEitherOrdered categories: regression respects the order, classification ignores it
Number of items a shop will sell tomorrowRegressionA count is still a quantity
Will delivery take over 30 minutes?EitherPredicting 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

Practice exercise

A classifier gave these class probabilities for three photos. Turn each row into a prediction: print the most likely class and its probability.

Your solutionPython
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
Knowledge check

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 predict and a probability for every class with predict_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.