Sub topic 3
Classification and regression targets
This chapter assumes you can read basic Python and NumPy, know what a pandas DataFrame is, and understand that supervised learning maps features X to labels y. The type of y decides which kind of problem you are solving, and that choice determines which scikit-learn estimators, metrics, and splitting options are appropriate.
Two kinds of target
A classification target holds discrete categories. Examples are the iris species, spam or not spam, and a digit from 0 to 9. A regression target holds a continuous number, such as a house price or a temperature.
The question to ask is whether the distance between two values means something. Predicting 4.1 when the truth is 4.0 is a small error. Predicting class 2 when the truth is class 1 is simply wrong, and the numbers 1 and 2 are only names.
| Aspect | Classification | Regression |
|---|---|---|
| Target values | A finite set of classes | Real numbers |
| Typical dtype of `y` | int, str, bool | float |
| Example estimator | `LogisticRegression` | `LinearRegression` |
| Default `score` | Accuracy | R² |
| Extra prediction method | `predict_proba` | None |
Inspecting your target
Check y before you choose an estimator. Integer labels are easy to mistake for numbers.
import numpy as np
from sklearn.datasets import load_iris, load_diabetes
X_c, y_c = load_iris(return_X_y=True)
X_r, y_r = load_diabetes(return_X_y=True)
print(y_c.dtype, np.unique(y_c)) # int64 [0 1 2]
print(y_r.dtype, y_r[:3]) # float64 [151. 75. 141.]
print(len(np.unique(y_r))) # many distinct valuesThe iris target has three distinct values, and each one is a class. The diabetes target has many distinct values, and each one is a measurement. A quick check is len(np.unique(y)). A small count suggests classification, and a count close to the number of samples suggests regression.
Scikit-learn also offers sklearn.utils.multiclass.type_of_target, which returns strings such as "binary", "multiclass", and "continuous".
Same API, different behavior
Both kinds of estimator use fit and predict. What differs is what predict returns and what score measures.
from sklearn.datasets import load_iris, load_diabetes
from sklearn.linear_model import LogisticRegression, LinearRegression
from sklearn.model_selection import train_test_split
X, y = load_iris(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, random_state=0, stratify=y)
clf = LogisticRegression(max_iter=200).fit(X_tr, y_tr)
print(clf.predict(X_te[:3])) # class labels
print(clf.predict_proba(X_te[:3]).round(2)) # one probability per class
print(clf.score(X_te, y_te)) # accuracy
X, y = load_diabetes(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, random_state=0)
reg = LinearRegression().fit(X_tr, y_tr)
print(reg.predict(X_te[:3])) # continuous values
print(reg.score(X_te, y_te)) # R squaredThe classifier returns labels and per-class probabilities. The regressor returns numbers on the scale of the target. Accuracy is a fraction of correct predictions, with 1.0 as the best value. R² compares your model to one that always predicts the mean. It is 1.0 for a perfect fit, 0.0 for the mean baseline, and negative when the model is worse than that baseline.
The stratify=y argument in the classification split keeps the class proportions the same in the training and test sets. It only makes sense for classification, because regression targets have no classes to balance.
Common errors
- Using a classifier on a continuous target.
LogisticRegression().fit(X, y)with float values such as 151.0 raises aValueErrorsaying the target type is "continuous". Use a regressor, or bin the target on purpose. - Treating class codes as numbers. If categories are stored as 1, 2, 3, a regressor will fit without complaint and treat class 3 as three times class 1. The code runs, but the result is meaningless.
- Reading accuracy as the only measure. On a dataset with 95% of one class, always predicting that class scores 0.95.
Task decision flow
Exercise
A dataset stores customer satisfaction as the integers 1, 2, 3, 4, 5, and you want to predict it. Which estimator type could you use, and what do you need to decide first?
Show answer
Either type can work, depending on meaning. If the ratings are ordered and a difference of one point matters, regression is reasonable. If you only care about which rating a customer picks and treat them as separate categories, use classification. Decide this first, because it changes the estimator, the score method, and how you read errors.