Sub topic 3
Classification and Regression Targets
This chapter assumes you can read basic Python and NumPy, know what a feature matrix X and a label vector y are, and have seen fit, predict, and score once. The goal is to separate the two main kinds of target and to see how the kind of y changes the estimator you pick, the metric score reports, and what predict returns.
Two kinds of target
A supervised model learns a mapping from X to y. What kind of values y holds decides the task.
- Classification predicts a category. The values in
ycome from a fixed, finite set of classes, such as"spam"and"ham", or0,1, and2. - Regression predicts a quantity on a continuous scale, such as a price, a temperature, or a duration. Values can fall anywhere in a range.
The distinction depends on the meaning of the target, not on its Python type. A column of integers can be either one. House prices in whole dollars are still a regression target. Zip codes stored as integers are class labels, because the difference between 90210 and 90211 is not a quantity.
A practical test: ask whether averaging two target values makes sense. The average of 200 000 and 300 000 is a meaningful price. The average of class 0 and class 2 is not a meaningful class.
Classification targets
Classification comes in a few forms, and scikit-learn handles each of them.
| Form | Description | Example `y` |
|---|---|---|
| Binary | Two classes | `[0, 1, 1, 0]` |
| Multiclass | Three or more classes, exactly one per sample | `["setosa", "virginica", "versicolor"]` |
| Multilabel | Several yes/no labels per sample | A 2D indicator array with one column per label |
Binary and multiclass targets are 1D arrays. This chapter focuses on those. Multilabel targets are 2D, so they follow the shape rules for multioutput targets described below.
Labels can be integers or strings. Estimators accept both and store the distinct values they saw in the classes_ attribute, sorted. Predictions come back as values drawn from classes_.
from sklearn.linear_model import LogisticRegression
X = [[0.0], [1.0], [2.0], [3.0], [4.0], [5.0]]
y = ["low", "low", "low", "high", "high", "high"]
model = LogisticRegression().fit(X, y)
print(model.classes_) # ['high' 'low']
print(model.predict([[0.5], [4.5]]))
print(model.predict_proba([[0.5], [4.5]]).round(2))Note the order of classes_. It is alphabetical ('high' before 'low'), not the order in which the labels first appear. The columns of predict_proba follow classes_, so the first column is the probability of 'high'. Reading probabilities without checking classes_ is a common source of inverted results.
Class balance
Because classification works with discrete classes, you should check how often each one appears.
import numpy as np
from sklearn.datasets import load_iris
_, y = load_iris(return_X_y=True)
values, counts = np.unique(y, return_counts=True)
print(dict(zip(values, counts))) # {0: 50, 1: 50, 2: 50}Iris is balanced. Many real datasets are not. If 98% of samples belong to one class, a model that always predicts that class reaches 98% accuracy and learns nothing useful. Imbalance affects how you split data (the stratify argument covered in the train/test chapter) and which metric you trust.
Regression targets
A regression target is a 1D array of floats, or of integers that stand for quantities.
from sklearn.datasets import make_regression
from sklearn.linear_model import LinearRegression
X, y = make_regression(n_samples=100, n_features=3, noise=5.0, random_state=0)
print(y.dtype, y.shape) # float64 (100,)
reg = LinearRegression().fit(X, y)
print(reg.predict(X[:3]).round(1))
print(round(reg.score(X, y), 3))predict returns floats, usually values that never appeared in the training labels. A regressor produces estimates along a continuous scale. It does not choose among known values.
What changes with the task
The kind of target affects three things.
- The estimator. Most model families have a classifier and a regressor version. Their names follow a convention:
LogisticRegression(despite its name, a classifier),RandomForestClassifierandRandomForestRegressor,SVCandSVR,KNeighborsClassifierandKNeighborsRegressor. - The meaning of
score. Classifiers report mean accuracy, the fraction of correct predictions. Regressors report R², the coefficient of determination. Both are "higher is better" and both are at most 1.0, but they measure different things. - The extra methods available. Many classifiers provide
predict_probaanddecision_function. Regressors do not.
| Aspect | Classifier | Regressor |
|---|---|---|
| Target `y` | Discrete classes | Continuous values |
| `predict` returns | A class label | A number |
| Default `score` | Accuracy | R² |
| Learned `classes_` | Yes | No |
| `predict_proba` | Often | No |
R² can be negative. It compares your model against a baseline that always predicts the mean of y. A negative value means the model does worse than that baseline, which usually points to a bad fit or a test set that differs from the training data.
scikit-learn marks an estimator's task through its tags and through helper functions. You can check what kind of target an array looks like with type_of_target.
from sklearn.utils.multiclass import type_of_target
print(type_of_target([0, 1, 1, 0])) # binary
print(type_of_target([0, 1, 2, 1])) # multiclass
print(type_of_target([0.5, 1.7, 2.2])) # continuous
print(type_of_target([[1, 0], [0, 1]])) # multilabel-indicatorEstimators use this function internally to validate y.
Common errors
Passing a continuous target to a classifier
A classifier treats every distinct value as its own class. Give it floats that are really measurements, and it raises an error.
from sklearn.linear_model import LogisticRegression
X = [[1], [2], [3], [4]]
y = [0.5, 1.7, 2.2, 3.1]
try:
LogisticRegression().fit(X, y)
except ValueError as e:
print(e) # Unknown label type: continuous...The message names the label type. The fix is to use a regressor, or to turn the target into classes on purpose, for example by thresholding.
Integer-coded regression targets treated as classes
The opposite problem is quieter. If a measured quantity is stored as integers, type_of_target may report multiclass. A classifier then accepts it without complaint and treats each integer as a separate category. It will never predict a value it did not see in training, and nearby values are no more related than distant ones. Check that the estimator matches the meaning of the target, not only that fit runs.
Wrong shape for `y`
Most estimators expect y with shape (n_samples,). A column vector with shape (n_samples, 1) triggers a DataConversionWarning and is flattened for you. Fix it at the source with y.ravel() or by selecting a pandas Series instead of a one-column DataFrame.
import numpy as np
y_col = np.array([[0], [1], [1], [0]])
print(y_col.shape) # (4, 1)
print(y_col.ravel().shape) # (4,)Multioutput estimators are the exception. When a model predicts several targets at once, y has shape (n_samples, n_targets) on purpose.
Reading probabilities in the wrong order
As shown earlier, predict_proba columns follow classes_. Always index with the class you mean, for example by finding its position in classes_.
Trusting accuracy on imbalanced classes
Accuracy rewards always predicting the majority class. For imbalanced problems, compare against a baseline such as DummyClassifier and consider metrics like precision, recall, or F1.
Turning one task into another
Sometimes you can choose the framing. Predicting a price is regression. Predicting "expensive" or "cheap" from the same price is classification. Binning discards information, so it needs a reason, such as a decision that really is yes or no. The same data can support both, and each framing needs its own estimator and its own metric.
import numpy as np
prices = np.array([120_000, 340_000, 95_000, 410_000])
is_expensive = (prices > 200_000).astype(int)
print(is_expensive) # [0 1 0 1]Exercise
A dataset has a column "rating" with integer values 1 to 5 given by users. You fit a RandomForestClassifier and then a RandomForestRegressor on it. What does each model's predict return, what does each score report, and what is one reason to prefer the regressor here?
Show answer
The classifier returns one of the labels 1 to 5 and its score is accuracy. The regressor returns floats such as 3.7 and its score is R². The regressor is a reasonable choice because ratings are ordered, so predicting 4 when the truth is 5 is closer than predicting 1. The classifier treats the ratings as unrelated categories and ignores that order. The classifier is preferable if you need to predict exactly one of the five ratings.
Exercise
You fit LogisticRegression on string labels ["no", "yes", ...] and call predict_proba on one sample. The output is [[0.2, 0.8]]. Which class has probability 0.8, and how do you confirm it in code?
Show answer
Columns follow model.classes, which is sorted alphabetically: ['no' 'yes']. So 0.8 belongs to "yes". Confirm by printing model.classes, or by using list(model.classes_).index("yes") to find the column.