The statements below are routinely used to justify the choice between classification and regression. None of them is valid.
| Statement heard | Status | Immediate counter-example |
|---|---|---|
| "It is a medical problem, so it is classification" | False | Predicting blood glucose three months out is regression in a medical setting |
| "I am using a random forest, so it is classification" | False | RandomForestRegressor exists and handles real-valued targets |
| "My input variables are categorical, so it is classification" | False | The type of the inputs is independent of the type of the target |
| "The target is stored as an integer, so it is classification" | False | A count of monthly visits is an integer and belongs to regression |
| "There are only two possible output values, so it is binary regression" | False | Two unordered categories define binary classification |
The single criterion is the mathematical structure of the set in which the target variable takes its values. The application domain, the algorithm you have in mind, the type of the explanatory variables and the storage format play no part in this qualification.
Supervised learning, defined in chapter 004, induces from a labeled sample a function
f : X → Y
where X is the space of explanatory variables and Y is the codomain, that is, the set of values the target variable can take.
Classification and regression share this frame in full. They also share the training sample, the notion of generalization, the train/test separation (chapter 026) and the risk of overfitting (chapter 031). They differ on one point only: the structure of Y.
Rigorous definition
The set Y in which the target function takes its values, considered not as a bare collection of symbols but as an algebraic structure: what matters is the set of relations and operations defined on it — equality, total order, distance, addition, expectation.
In plain terms
The set of all possible answers, together with what you are entitled to do with those answers: can you only say whether two of them are the same or different, can you rank them, can you measure the gap between two of them.
Point of caution
The structure of Y is never visible in the data file. A column holding the values 1, 2, 3 may encode three plant species (nominal structure) or three visits to the workshop (numeric structure). Only domain knowledge settles it. Qualification is an act of analysis, not a type inspection.
Governing statement of the chapter
The problem type is determined by the nature of the target variable. It is determined neither by the business domain, nor by the algorithm under consideration, nor by the type of the explanatory variables.
Rigorous definition
The supervised learning task of inducing, from a sample of labeled observations, a function f : X → Y where the codomain Y = {c₁, c₂, …, } is finite and carries no intrinsic order relation. The elements of Y are called classes, categories or levels. K denotes the number of classes; K = 2 defines binary classification, K > 2 multiclass classification (chapter 011).
Structure of the codomain
The only relation defined on Y is equality. Two classes are either identical or distinct; none is "greater" than another, and no distance is defined between them. The statement "the class dog is closer to the class cat than to the class horse" has no mathematical standing in the standard frame.
In plain terms
Put each case into one of a fixed set of bins, where the bins are not ranked from smallest to largest.
Point of caution
The set of classes is fixed before training and is part of the problem specification. A classification model can never predict a class absent from the training sample. A new category appearing in production is a break in specification, not a prediction error.
| Operation on two target values | Classification | Justification |
|---|---|---|
| Test equality y₁ = y₂ | Legal | Equality is the founding relation of Y |
| Order y₁ < y₂ | Illegal | A nominal set carries no intrinsic order |
| Compute the gap y₁ − y₂ | Illegal | Subtraction is not defined |
| Average the target values | Illegal | The expectation of a nominal variable is meaningless |
| Count the occurrences of a class | Legal | Yields the class distribution (chapter 050) |
Direct consequence: the error of a classification model is not measured by a gap but by a count of disagreements, formalized in the confusion matrix (chapter 052). On a single prediction there is no "small" or "large" error: the prediction is either correct or incorrect.
A classifier in fact produces two distinct outputs, and confusing them is a frequent source of error.
| Output | Nature | scikit-learn method | Codomain |
|---|---|---|---|
| Per-class score or probability | A vector of K reals summing to 1 | predict_proba() | [0, 1]^K |
| Predicted class | One category | predict() | {c₁, …, } |
Moving from the first to the second requires a decision rule — most often a threshold in the binary case (chapter 062), or the argmax in the multiclass case. Producing an intermediate real-valued score does not turn the problem into a regression: the codomain of the problem remains the finite set of classes, and the score is nothing more than an intermediate quantity.
Rigorous definition
The subset of the feature space X that separates the regions associated with different predicted classes. Formally, for a binary classifier built on a score function s(x) and a threshold t, the boundary is the set {x ∈ X : s(x) = t}.
In plain terms
The line, surface or limit beyond which the model changes its mind about which category to assign.
Point of caution
The geometric object learned in classification is a partition of the input space. In regression, the object learned is a response surface defined over the whole input space. This difference in nature explains why some algorithms transfer poorly from one frame to the other.
A sorting center has a fixed number of bins, one per destination region. Every parcel must go into exactly one bin. The sorter cannot invent a bin, and cannot place a parcel "between" two bins.
Choosing the wrong bin is an error with no degree: a parcel bound for Lyon dropped into the Marseille bin and a parcel bound for Lyon dropped into the Lille bin are two equivalent sorting errors, even though the operational consequences differ.
The sorter's hesitation — "this one is probably for Lyon, possibly for Grenoble" — corresponds to the probability score. The final decision to drop it into a bin corresponds to the predicted class.
| Domain | Business question | Codomain | K |
|---|---|---|---|
| Payments | Is this transaction fraudulent? | {fraud, legitimate} | 2 |
| Is this message unsolicited? | {spam, ham} | 2 | |
| Health | Does this patient have the condition? | {positive, negative} | 2 |
| Telecom | Will this customer churn? | {churn, retain} | 2 |
| Botany | Which species is this? | {setosa, versicolor, virginica} | 3 |
| Manufacturing | Which defect affects this part? | {scratch, crack, porosity, none} | 4 |
Rigorous definition
The supervised learning task of inducing, from a sample of labeled observations, a function f : X → Y where the codomain Y is a subset of ℝ — most often ℝ itself, ℝ⁺, or a bounded interval. The codomain therefore carries a total order and a distance, which is what gives meaning to the quantity y − ŷ, called the residual (chapter 066).
Statistical formulation
Regression estimates a feature of the conditional distribution of Y given X. Least-squares regression estimates the conditional expectation E[Y | X = x]; quantile regression estimates a conditional quantile; regression on the absolute deviation estimates the conditional median.
In plain terms
Estimate a quantity, that is, produce a number located on a graduated scale on which it is possible to say by how much you were wrong.
Note on etymology
The term comes from Francis Galton (1886), who observed "regression towards mediocrity" — today regression towards the mean — in the transmission of height across generations. By extension the word now denotes any estimation of a numeric target. It carries no notion of moving backwards.
| Operation on two target values | Regression | Practical consequence |
|---|---|---|
| Test equality y₁ = y₂ | Legal but pointless | Exact equality has probability zero on a continuous variable |
| Order y₁ < y₂ | Legal | Enables rank-based metrics |
| Compute the gap y₁ − y₂ | Legal | Grounds the notion of residual |
| Average the values | Legal | Grounds the "predict the mean" baseline |
| Square the gap | Legal | Grounds MSE and RMSE (chapters 068 and 069) |
Direct consequence: in regression the error is graded. Predicting $248,000 for a property that sold for $250,000 is a good result; predicting $90,000 for the same property is a failure. That distinction cannot even be expressed in the classification frame, where both predictions would be equally "wrong".
| Output | Nature | Use |
|---|---|---|
| Point prediction | One real ŷ | Standard output of predict() |
| Prediction interval | A pair [, ] | Communicating uncertainty |
| Conditional quantiles | Several reals | Asymmetric decisions, inventory management |
A regressor has no equivalent of predict_proba(): there is no "probability of
each possible value" when the codomain is continuous. This asymmetry is
developed in chapter 029.
A pharmacist files boxes into labeled drawers: antibiotics, analgesics, antihistamines. A box is either in the right drawer or in the wrong one. There is no "almost right drawer". That is classification.
The same pharmacist weighs a compounded preparation and aims for 250 mg. The scale reads 248 mg: the gap is 2 mg, it is quantified, and it falls within pharmaceutical tolerance. The scale reads 90 mg: the gap is 160 mg and the preparation is unusable. That is regression.
The drawer admits no degree. The scale does. The entire difference between the two frames lies in that property of the output scale.
The table below places side by side, for one and the same business domain, a target that belongs to classification and a target that belongs to regression. It establishes that the domain determines nothing.
| Domain | Categorical target → classification | Numeric target → regression |
|---|---|---|
| Real estate | Will the property sell within 90 days? | Sale price in dollars |
| Health | Is the patient diabetic? | HbA1c level in percent |
| Energy | Will the peak load be exceeded? | Daily consumption in kWh |
| Meteorology | Will it rain tomorrow? | Maximum temperature in °C |
| Payments | Is the transaction fraudulent? | Loss amount if fraudulent |
| Human resources | Will the candidate accept the offer? | Accepted salary in dollars |
| Manufacturing | Is the part within specification? | Measured dimension in millimeters |
| Marketing | Will the customer subscribe? | Twelve-month revenue |
How to read the table: each row describes a single domain, often a single dataset, with the same explanatory variables. Only the column selected as the target changes, and with it the problem type.
What exactly is to be produced, and what is the nature of the value produced: a category drawn from a fixed list, or a number located on a scale?
Its short form, usable in a scoping meeting:
| Shape of the business question | Problem type |
|---|---|
| "Which category?", "Which one?", "Is it …?", "Yes or no?" | Classification |
| "How many?", "What quantity?", "What amount?", "How long?" | Regression |
Point of caution: the question must bear on the value produced by the model, not on the decision the organization takes afterwards. A model estimating a loss amount (regression) can feed a binary accept-or-refuse decision. The downstream decision does not change the nature of the model output.
When the business question stays ambiguous, the following test settles it mechanically. It applies to the observed values of the target.
| Operation tested | Reading if the result carries business meaning |
|---|---|
| 1. y₁ = y₂ ? | Always true: a minimal condition, it discriminates nothing |
| 2. y₁ < y₂ ? | An order exists: the target is at least ordinal |
| 3. y₁ − y₂ readable as a gap? | A metric exists: the target is numeric |
Reading rule
Applied to a ZIP code: two ZIP codes can be compared for equality; the ordering 33101 < 94110 expresses nothing about the business; the difference 94110 − 33101 = 61,009 is not a distance. The ZIP code is a nominal variable despite its numeric storage.
Rigorous definition
A random variable is discrete when the set of its possible values is finite or countably infinite. It is continuous when that set is a non-degenerate interval of ℝ and its cumulative distribution function is continuous, so that the probability of any single point is zero.
In plain terms
Discrete: the values can be counted one by one, and between two neighboring values there is nothing. Continuous: between any two values, however close, there are infinitely many others.
Point of caution — the central confusion
Discrete is not a synonym for categorical. A count of monthly visits is discrete (0, 1, 2, …) and yet perfectly numeric: order and gap are meaningful on it. The dichotomy that qualifies a learning problem is not discrete versus continuous but nominal versus numeric.
Point of caution — physical measurement
Every recorded measurement is discrete by construction, because instruments have finite resolution and floating-point representation is finite. A temperature recorded to a tenth of a degree takes finitely many values. It is treated as continuous, because its underlying structure is an interval of ℝ.
| Target | Discrete or continuous | Nominal or numeric | Problem type |
|---|---|---|---|
| Iris species | Discrete | Nominal | Classification |
| Transaction status | Discrete | Nominal | Classification |
| ZIP code | Discrete | Nominal | Classification |
| Monthly visit count | Discrete | Numeric | Regression |
| Number of claims filed | Discrete | Numeric | Regression |
| Maximum temperature | Continuous | Numeric | Regression |
| Sale price | Continuous | Numeric | Regression |
scikit-learn exposes a function that inspects the type of a target array. It is a useful control, provided you know its limits.
import numpy as np
from sklearn.utils.multiclass import type_of_target
targets = {
"transaction_status ": np.array(["normal", "fraud", "normal", "fraud"]),
"iris_species ": np.array(["setosa", "versicolor", "virginica", "setosa"]),
"temperature_celsius ": np.array([18.4, 21.0, 19.7, 23.2]),
"sale_price_usd ": np.array([245000.0, 312500.0, 189900.0, 405000.0]),
"monthly_visits ": np.array([0, 3, 1, 12]),
"satisfaction_1_to_5 ": np.array([1, 3, 2, 5]),
"churned ": np.array([0, 1, 1, 0]),
"zip_code ": np.array([94110, 33101, 60614, 94110]),
}
for name, y in targets.items():
print(f"{name} dtype={str(y.dtype):8s} -> type_of_target = {type_of_target(y)}")Output
transaction_status dtype=<U6 -> type_of_target = binary
iris_species dtype=<U10 -> type_of_target = multiclass
temperature_celsius dtype=float64 -> type_of_target = continuous
sale_price_usd dtype=float64 -> type_of_target = multiclass
monthly_visits dtype=int64 -> type_of_target = multiclass
satisfaction_1_to_5 dtype=int64 -> type_of_target = multiclass
churned dtype=int64 -> type_of_target = binary
zip_code dtype=int64 -> type_of_target = multiclassInterpretation
The first three lines agree with the business analysis. The next three contradict it:
sale_price_usd is a regression target, reported as multiclass because the
four values, although stored as floats, are whole numbers and few in number;monthly_visits is a regression target under the three-operation test,
reported as multiclass because it is stored as integers;satisfaction_1_to_5 is an ordinal target, and the function does not separate
it from a nominal one.The last two lines agree with the business analysis for the wrong reason.
churned is labeled binary only because exactly two distinct values happen to
be present in this array. zip_code is indeed nominal, but the function would
attach multiclass to any small set of integers, quantities included — it is
reacting to the count of distinct values, not to the absence of an order.
Operational conclusion: type_of_target applies a syntactic heuristic based
on storage type and the number of distinct values. It detects format
inconsistencies; it does not qualify a problem. Qualification remains an act of
analysis grounded in domain knowledge.
Five configurations resist direct qualification. Each calls for a documented decision, not a default choice.
Nature: a finite set carrying a business-meaningful order, with no interpretable distance between consecutive levels. Examples: a risk level {low, medium, high}, a satisfaction rating from 1 to 5, a tumor stage I to IV, a credit rating from AAA to D.
The dilemma: treating the target as multiclass classification destroys the order information — confusing "high" with "low" and confusing "high" with "medium" count as the same error. Treating it as regression assumes equal spacing between levels, an assumption that is generally false: the severity gap between stages I and II does not equal the gap between III and IV.
Choice adopted: classification, as the qualification of the problem, since the codomain remains finite. Two adjustments are recommended:
| Adjustment | Implementation | Justification |
|---|---|---|
| Order-sensitive metric | Quadratic weighted kappa, MAE on ranks | Penalizes errors that are further apart in the ordering |
| Dedicated ordinal model | Proportional odds model (McCullagh, 1980), decomposition into K−1 cumulative binary classifiers | Exploits the order without assuming equal spacing |
Falling back to regression: acceptable when the number of levels is high — from roughly ten upwards — and equal spacing is defensible, the real-valued prediction then being rounded. That choice must be justified explicitly. Ordinal classification is detailed in chapter 011.
Nature: the set of natural numbers — countably infinite, ordered, and carrying an interpretable distance. Examples: annual claims, visits, defects per batch.
Choice adopted: regression. All three operations of the test are meaningful, and the codomain is not finite. That the values are integers is not a criterion for classification.
| Point of attention | Recommended treatment |
|---|---|
| Positive support and strong skew | Poisson or negative binomial deviance loss rather than MSE |
| Overdispersion, variance above the mean | Negative binomial model |
| Excess zeros | Zero-inflated model, or a "zero versus non-zero" classifier followed by a regressor on the non-zeros |
| Non-integer real-valued prediction | Round in post-processing, never inside the loss function |
Frequent error: treating a count that happens to be bounded in the observed data (0, 1, 2, 3 claims) as a four-class classification. That formulation forbids the model from ever predicting 4, destroys the order, and makes the residual uninterpretable.
Nature: a duration until an event occurs, observed incompletely for part of the sample — the contract is still active, the patient is still alive, the machine has not yet failed by the end of the observation window.
Rigorous definition
The situation in which the duration of interest T for a subject is not observed directly, only the pair (min(T, C), 1{T ≤ C}) being available, where C denotes the follow-up duration. The information at hand is then "T is greater than C" rather than the value of T.
In plain terms
You know the event had not yet happened when you stopped watching, without knowing when it will happen.
Methodological consequence
Discarding censored observations biases the estimate towards short durations, because long-lived subjects are precisely the ones that get censored. Replacing the censored duration by the follow-up duration also biases the estimate downwards. The appropriate frame is survival analysis: the Kaplan-Meier estimator (1958), the Cox proportional hazards model (1972), survival forests.
Point of caution
Censoring is not a missing value in the sense of chapter 018. A censored duration carries usable partial information, not an absence of information.
Choice adopted: neither classification nor regression in the strict sense when censoring is substantial. The table below fixes the course of action.
| Situation | Formulation adopted | Justification |
|---|---|---|
| Complete history, every event observed | Regression on the duration | No censoring, the standard frame applies |
| Censoring present, a duration estimate is required | Survival analysis | The only frame that uses censored observations correctly |
| Censoring present, decision made at a fixed horizon H | Binary classification, "event before H" | Valid provided only subjects whose follow-up reaches H are retained |
| Heavy censoring and uneven follow-up | Survival analysis, mandatory | Restricting the sample would destroy most of it |
Nature: the value to produce is a number in the interval [0, 1]. Qualification depends entirely on what is observed in the training sample, not on what is requested as output.
| What is observed for each row | Problem type | Modeling |
|---|---|---|
| A binary outcome, 0 or 1 | Classification, binary | Probabilistic classifier, predict_proba output, log loss (chapter 061), calibration checked |
| A measured proportion, for example a conversion rate per store | Regression on [0, 1] | Beta regression, or regression on the logit transform, or a loss suited to bounded support |
Central point: asking for a probability as output does not make a problem a regression. A fraud detection model returning p = 0.83 is still a classification model: the target observed during training is 0 or 1. The continuous output is an estimate of P(Y = 1 | X = x), not a numeric target learned as such.
Point of caution: a probability score produced by a classifier is not necessarily calibrated. A score of 0.83 does not mean that 83% of the cases receiving that score are positive, unless calibration has been verified explicitly (chapter 061).
Nature: the available target is numeric — an amount, an age, a rate — and the organization asks for an output in classes defined by cutoffs: "low, medium or high potential customer", "acceptable or unacceptable risk".
Choice adopted: regress on the numeric target, then apply the cutoff to the prediction. Discretizing the target beforehand destroys information and reduces statistical power; the practice is documented in the methodological literature under the name of inappropriate dichotomization (Royston, Altman and Sauerbrei, 2006).
| Criterion | Discretize the target before training | Regress, then threshold |
|---|---|---|
| Information retained | Within-class variation is lost | Retained in full |
| Cutoff effect | Two values one dollar apart become two different classes | None: continuous treatment |
| Change of business cutoff | Complete relabeling and retraining | Change one constant, no retraining |
| Several cutoffs at once | One model per partition | A single model |
| Readability for the business | Immediate | Requires a presentation layer |
The following protocol quantifies the difference on a customer value dataset. The target is twelve-month revenue. The business defines "high potential" as revenue of at least $8,000. Two models are trained on the same features and the same split: one classifier on the discretized target, one regressor on the raw revenue whose prediction is thresholded at the same cutoff.
import numpy as np
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import precision_score, recall_score, f1_score
rng = np.random.default_rng(7)
n = 8000
# Customer base, features known at the start of the year
tenure_months = rng.integers(1, 96, n)
past_spend_usd = rng.gamma(2.0, 900, n)
n_orders = rng.poisson(1 + past_spend_usd / 1800)
support_calls = rng.poisson(0.8, n)
web_sessions = rng.poisson(4 + tenure_months / 12)
signal = (1.6 * past_spend_usd + 120 * n_orders + 38 * tenure_months
+ 160 * web_sessions - 300 * support_calls)
revenue_12m = np.maximum(0, signal + rng.normal(0, 1200, n)) # continuous target, USD
X = np.column_stack([tenure_months, past_spend_usd, n_orders, support_calls, web_sessions])
CUTOFF = 8000 # "high potential" as the business defines it
y_num = revenue_12m # native target
y_cat = (revenue_12m >= CUTOFF).astype(int) # target destroyed by discretization
X_tr, X_te, yn_tr, yn_te, yc_tr, yc_te = train_test_split(
X, y_num, y_cat, test_size=0.3, random_state=0, stratify=y_cat)
clf = RandomForestClassifier(n_estimators=300, min_samples_leaf=5, random_state=0).fit(X_tr, yc_tr)
reg = RandomForestRegressor(n_estimators=300, min_samples_leaf=5, random_state=0).fit(X_tr, yn_tr)
pred_clf = clf.predict(X_te)
pred_reg = (reg.predict(X_te) >= CUTOFF).astype(int)
print(f"Test set: {len(yc_te)} customers, {int(yc_te.sum())} high potential at ${CUTOFF:,}\n")
for name, pred in [("discretize the target, then classify", pred_clf),
("regress, then threshold at $8,000", pred_reg)]:
print(f"{name:36s} precision={precision_score(yc_te, pred):.3f} "
f"recall={recall_score(yc_te, pred):.3f} F1={f1_score(yc_te, pred):.3f}")
print("\nThe business moves the cutoff. The regressor is not retrained:")
for t in (3000, 5000, 12000):
target_t = (yn_te >= t).astype(int)
pred_t = (reg.predict(X_te) >= t).astype(int)
print(f" cutoff ${t:6,d}: precision={precision_score(target_t, pred_t):.3f} "
f"recall={recall_score(target_t, pred_t):.3f} F1={f1_score(target_t, pred_t):.3f} "
f"selected={int(pred_t.sum()):4d}")Output
Test set: 2400 customers, 548 high potential at $8,000
discretize the target, then classify precision=0.802 recall=0.723 F1=0.760
regress, then threshold at $8,000 precision=0.800 recall=0.706 F1=0.750
The business moves the cutoff. The regressor is not retrained:
cutoff $ 3,000: precision=0.936 recall=0.963 F1=0.949 selected=2122
cutoff $ 5,000: precision=0.886 recall=0.873 F1=0.879 selected=1461
cutoff $12,000: precision=0.714 recall=0.556 F1=0.625 selected= 49Interpretation
At the cutoff the classifier was trained on, the two formulations are effectively tied: F1 of 0.760 against 0.750, a gap of one point that no practitioner should treat as a decisive advantage. The classifier optimizes directly for that one separation, which buys it a marginal edge there and nothing anywhere else.
The asymmetry appears on the second block. The regressor answers the $3,000, $5,000 and $12,000 questions from the same fitted model, with no relabeling and no retraining, because it learned the underlying quantity rather than one arbitrary split of it. The classifier can answer exactly one question, the one it was trained on; every new cutoff costs a full relabel-and-retrain cycle. The argument for regressing first is therefore not that it wins on the metric at a fixed cutoff — it does not — but that the discretized formulation throws away the target's resolution in exchange for nothing.
Accepted exception: when the underlying numeric target is not observable and only the class is recorded in the source system — a self-declared income band, a risk level assigned by an expert. The available data is then natively categorical, the problem is a classification, and no reformulation is possible.
| Case | Structure of the target | Choice adopted | Deciding reason |
|---|---|---|---|
| Ordinal | Finite, ordered, non-metric | Classification, with an order-sensitive metric and model | The codomain remains finite |
| Count | Integers, infinite, metric | Regression, Poisson loss | All three operations are meaningful |
| Censored duration | ℝ⁺ partially observed | Survival analysis, or fixed-horizon classification | Censoring invalidates naive regression |
| Probability | [0, 1] | Classification if the observed label is binary, regression if a proportion is measured | Qualification follows the observed target |
| Discretized numeric | ℝ recoded into classes | Regress then threshold, unless the target is natively categorical | Discretization destroys information |
Qualification happens at step 3 of the project lifecycle (chapter 012). Every later step depends on it.
| Dimension | Classification | Regression |
|---|---|---|
| Codomain | {c₁, …, }, finite, unordered | A subset of ℝ, ordered and metric |
| Object learned | A partition of the input space, a decision boundary | A response surface defined over the whole input space |
| Quantity estimated | P(Y = c | X = x), the conditional probability of each class | E[Y | X = x], the conditional expectation, or a conditional quantile |
| Raw model output | A vector of K scores | One real number |
| Delivered output | One class, after a threshold or an argmax | The value, optionally bracketed by an interval |
| Notion of error | Binary disagreement, counted | Signed residual, graded |
| Usual loss functions | Cross-entropy, log loss, hinge, focal loss; Gini and entropy split criteria | MSE, MAE, Huber, quantile pinball, Poisson deviance, RMSLE |
| Evaluation metrics | Accuracy, precision, recall, specificity, F1, F-beta, balanced accuracy, log loss, ROC-AUC, PR-AUC | MAE, MSE, RMSE, R², adjusted R², MAPE, sMAPE, MedAE, RMSLE |
| Representative algorithms | Logistic regression, decision tree, random forest, boosting, SVC, k-NN, naive Bayes, MLP | Linear regression, Ridge, Lasso, Elastic Net, decision tree, random forest, boosting, SVR, k-NN, MLP |
| scikit-learn suffix | …Classifier | …Regressor |
| Reference baseline | Always predict the majority class | Always predict the mean or the median |
| Data splitting | Stratify on the target, recommended (chapter 027) | Random split; stratify on binned target if it is heavily skewed |
| Distributional pathology | Class imbalance (chapters 050 and 051) | Skew, extreme values, heteroscedasticity |
| Post-training tuning knob | Decision threshold (chapter 062) | No direct equivalent; possible rescaling or recalibration |
| Error diagnostics | Confusion matrix, false positive and false negative analysis | Residual plots, residuals against fitted values |
| Nature of the business tradeoff | Which error costs more, a false positive or a false negative | Which error costs more, over-prediction or under-prediction |
| Production monitoring | Drift in the distribution of predicted classes | Drift in the distribution and the mean of the predictions |
The loss function is not the metric. The loss is optimized during training and must be differentiable for gradient-based algorithms; the metric evaluates the model and answers a business question. A classifier optimizes log loss and is judged on recall; a regressor optimizes MSE and is judged on MAE. This distinction is developed in chapter 030.
The decision threshold exists only in binary classification. It is a powerful post-training lever: with the model unchanged, moving the threshold shifts the balance between false positives and false negatives. Regression offers no equivalent lever on the model itself; any threshold applied to its output belongs to the downstream decision rule, not to the model.
A business need is not a learning problem. It becomes a learning problem the moment a target variable is chosen. When several targets are available to serve the same need, several formulations coexist, possibly in different frames.
The reference case: predictive maintenance. An operator monitors a fleet of instrumented industrial pumps. The need is single: intervene before failure without multiplying pointless shutdowns. Two targets can be constructed from the same history and the same sensors.
Rigorous definition
The time separating the moment of observation from the moment of failure of a piece of equipment, conditional on its observed condition and its operating history. It is the reference target of prognostic approaches in condition-based maintenance.
In plain terms
The number of days the machine has left before it breaks down, estimated from its current condition.
Point of caution
Labeling a remaining useful life requires complete life cycles: the value is known only for equipment that actually ran to failure. Equipment still in service at the end of the observation window is censored in the sense of section 5.3. A maintenance dataset almost always contains censoring, and that is the first practical obstacle to the regression formulation.
The protocol below builds a degradation dataset, derives both targets from the same explanatory variables, trains both models, and tunes for each its own decision threshold on a validation split, against an explicit cost function: $800 for a preventive intervention, $12,000 for an unplanned failure.
import numpy as np
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import precision_score, recall_score, mean_absolute_error
rng = np.random.default_rng(42)
n = 6000
# A fleet of instrumented industrial pumps: the SAME features throughout
hours = rng.uniform(0, 20000, n) # cumulative run hours
vibration = 1.2 + 0.00018 * hours + rng.normal(0, 0.35, n) # mm/s RMS
bearing_t = 55 + 0.0011 * hours + rng.normal(0, 3.0, n) # bearing temperature, C
delta_p = 2.6 - 0.00007 * hours + rng.normal(0, 0.20, n) # pressure drop, bar
n_repairs = rng.poisson(0.5 + hours / 9000) # past interventions
wear = 0.55 * vibration + 0.035 * bearing_t - 0.9 * delta_p + 0.00004 * hours
rul = 300 * np.exp(-0.5 * wear) * np.exp(rng.normal(0, 0.22, n)) # remaining days
X = np.column_stack([hours, vibration, bearing_t, delta_p, n_repairs])
y_reg = rul # continuous target -> REGRESSION
y_clf = (rul <= 30).astype(int) # binary target -> CLASSIFICATION
X_tr, X_te, yr_tr, yr_te, yc_tr, yc_te = train_test_split(
X, y_reg, y_clf, test_size=0.3, random_state=0, stratify=y_clf)
X_tr, X_va, yr_tr, yr_va, yc_tr, yc_va = train_test_split(
X_tr, yr_tr, yc_tr, test_size=0.25, random_state=0, stratify=yc_tr)
C_PREVENTIVE, C_FAILURE = 800, 12000 # dollars: planned intervention / unplanned failure
def cost(y_true, alert):
return int(alert.sum()) * C_PREVENTIVE + int(((y_true == 1) & (alert == 0)).sum()) * C_FAILURE
clf = RandomForestClassifier(n_estimators=300, min_samples_leaf=5, random_state=0).fit(X_tr, yc_tr)
reg = RandomForestRegressor(n_estimators=300, min_samples_leaf=5, random_state=0).fit(X_tr, yr_tr)
p_va, p_te = clf.predict_proba(X_va)[:, 1], clf.predict_proba(X_te)[:, 1]
r_va, r_te = reg.predict(X_va), reg.predict(X_te)
# Each formulation gets its own decision threshold, tuned on cost, on the validation split
thr_a = min(np.arange(0.02, 0.61, 0.01), key=lambda s: cost(yc_va, (p_va >= s).astype(int)))
thr_b = min(np.arange(10, 121, 1), key=lambda t: cost(yc_va, (r_va <= t).astype(int)))
print(f"Thresholds tuned on validation: A p >= {thr_a:.2f} B predicted RUL <= {thr_b} days")
print(f"MAE of B on remaining useful life: {mean_absolute_error(yr_te, r_te):.1f} days")
print(f"Reference cost, no alert at all: ${int(yc_te.sum()) * C_FAILURE:,}\n")
for name, alert in [("A - binary classification ", (p_te >= thr_a).astype(int)),
("B - regression on RUL ", (r_te <= thr_b).astype(int))]:
print(f"{name} precision={precision_score(yc_te, alert, zero_division=0):.3f} "
f"recall={recall_score(yc_te, alert):.3f} alerts={int(alert.sum()):3d} "
f"missed={int(((yc_te == 1) & (alert == 0)).sum()):2d} cost=${cost(yc_te, alert):,}")
print("\nB - intervention horizon changed with no retraining:")
for h in (60, 90):
target_h, alert_h = (yr_te <= h).astype(int), (r_te <= h).astype(int)
print(f" horizon {h:2d} d: precision={precision_score(target_h, alert_h):.3f} "
f"recall={recall_score(target_h, alert_h):.3f} alerts={int(alert_h.sum()):3d}")Output
Thresholds tuned on validation: A p >= 0.05 B predicted RUL <= 40 days
MAE of B on remaining useful life: 18.5 days
Reference cost, no alert at all: $2,076,000
A - binary classification precision=0.431 recall=0.954 alerts=383 missed= 8 cost=$402,400
B - regression on RUL precision=0.486 recall=0.913 alerts=325 missed=15 cost=$440,000
B - intervention horizon changed with no retraining:
horizon 60 d: precision=0.900 recall=0.888 alerts=668
horizon 90 d: precision=0.932 recall=0.927 alerts=979Interpretation
| Observation | Reading |
|---|---|
| Both formulations cut the cost from $2,076,000 to roughly $0.4M | The need is tractable in both frames; qualification is not settled by feasibility |
| A reaches $402,400 against $440,000 for B at the 30-day horizon | Classification optimizes directly for the separation at the horizon of interest; regression optimizes error across the whole duration scale, including regions where no decision is at stake |
| B shows slightly higher precision and 58 fewer alerts, at the price of 7 more missed failures | The two formulations sit at different points of the precision-recall tradeoff; the comparison only means something once the cost function is fixed |
| The optimal threshold for B is 40 days, not 30 | A regressor's output cannot be used with the raw business cutoff: it is shrunk towards the mean and must be recalibrated empirically |
| B handles the 60-day and 90-day horizons with the same trained model | Changing the horizon under formulation A requires a complete relabel and retrain |
| The MAE of B is 18.5 days | An average error of 18.5 days makes formulation B unusable for a 7-day or 14-day horizon — a fact that no classification metric would have revealed |
Read together, the two blocks say something the cost column alone does not. At the horizon the business fixed today, formulation A is the better buy by $37,600 on this test set. Across horizons the business might fix tomorrow, formulation B is the only one that answers without a new training run, and its predicted RUL can also rank machines for scheduling, which a probability above a threshold cannot do as directly. Neither result dominates. The arbitration is a business decision informed by the numbers, not a technical verdict read off them.
| Criterion | Points to classification | Points to regression |
|---|---|---|
| Decision horizon | Single, fixed, stable over time | Multiple, variable, or negotiated case by case |
| Label availability | Only the occurrence of the event is recorded | Complete life cycles are documented |
| Censoring in the history | Substantial: fixed-horizon classification is more robust | Low, or handled by survival analysis |
| Volume of events | Low: concentrate model capacity on the boundary | High: the richness of a continuous target can be exploited |
| Nature of the downstream decision | Binary, immediate, no prioritization | Scheduling, planning, resource allocation |
| Need to rank cases | Served by the probability score | Served by the predicted value, directly interpretable |
| Communication to the business | "83% risk within 30 days" | "about 45 days left" |
| Sensitivity to policy change | Low: any change of horizon forces a retrain | High: a change of horizon is one constant to edit |
| Control over the error tradeoff | Direct, through the decision threshold | Indirect, through the threshold applied to the output |
Rule of conduct: when both formulations are feasible, build both, evaluate them on the same business cost function and the same test set, then decide on that result. Comparing heterogeneous metrics — an MAE against an F1 — is not an arbitration.
An intersection can be signaled in two ways. The traffic light gives a category: red, amber, green. The countdown timer displays a number of seconds remaining.
The light is enough to decide whether to stop: the decision is binary and its horizon is immediate. The countdown additionally lets a driver anticipate, modulate speed, and coordinate with other vehicles; in exchange it demands richer information that is harder to produce.
The choice between the two devices has nothing to do with the intersection. It depends on what you want to be able to decide, and on the precision actually achievable.
Statements like "medicine is classification" or "finance is regression" have no basis. A single hospital department produces classification problems (diagnosis) and regression problems (length of stay, dosage, lab values).
Correct formulation : "The problem type is determined by the structure of the set of values the target variable can take, independently of the application domain."
The major algorithm families — trees, forests, boosting, k-NN, SVM, neural networks — exist in both variants. The choice of algorithm comes after qualification and therefore cannot determine it.
Correct formulation : "The target qualifies the problem; the problem restricts the set of admissible algorithms; the algorithm is chosen inside that set."
Logistic regression is a classification model. The word "regression" refers to the linear regression performed on the logit of the probability, not to the nature of the target, which is categorical. Chapter 036 details this point.
Correct formulation : "Logistic regression models the log-odds of a binary target linearly; it belongs to classification."
A ZIP code, a product line identifier or a district code are stored as integers
without being quantities. Conversely, a number of claims stored as an integer is
a quantity. Inspecting the dtype does not replace semantic analysis.
Correct formulation : "The data type of the column is a property of the storage format; the structure of the codomain is a property of the domain."
Cutting a numeric target into bands before training reduces statistical power, introduces arbitrary cutoff effects, and makes the model useless as soon as the business cutoffs move. Readability for business teams is obtained by discretizing the prediction, not the target.
Correct formulation : "The model is trained on the numeric target; the binning is applied to the output, in the presentation layer."
A binary classifier produces a continuous score in [0, 1]. That continuous output is an estimate of the conditional probability of belonging to the positive class. The codomain of the problem is still finite.
Correct formulation : "Qualification bears on the target observed during training, not on the form of the model's intermediate output."
Restricting the sample to equipment that actually failed, or replacing censored durations by the follow-up duration, biases the estimate systematically towards durations that are too short.
Correct formulation : "In the presence of right censoring the appropriate frame is survival analysis; fixed-horizon classification is a valid alternative provided each subject's follow-up covers the chosen horizon."
An MAE of 18.5 days and an F1 of 0.60 are not comparable. Arbitrating between a classification formulation and a regression formulation requires reducing both to a decision and evaluating them on the same cost function, on the same test set.
Correct formulation : "Two formulations of one need are compared on the decision they produce and on its cost, never on their respective native metrics."
THE SINGLE QUALIFICATION CRITERION
The structure of the codomain of the target variable.
Not the domain, not the algorithm, not the type of the input
variables, not the storage format.
CLASSIFICATION
f : X -> {c1, ..., cK}, a FINITE and UNORDERED set.
Only equality is defined. Error is counted.
REGRESSION
f : X -> an interval of R, an ORDERED and METRIC set.
The gap y - y_pred is meaningful. Error is measured.
THE THREE-OPERATION TEST
Equality only -> classification
Equality + order -> ordinal case, handled as classification
Equality + order + gap -> regression
THE FIVE AMBIGUOUS CASES
Ordinal -> classification, order-sensitive metric
Count -> regression, Poisson loss
Censored duration -> survival analysis, or fixed-horizon classification
Probability -> follows the OBSERVED label: binary or proportion
Binned numeric -> regression, then threshold the prediction
WHAT THE CHOICE DETERMINES NEXT
Admissible algorithms, loss function, evaluation metrics, form of the
output, baseline, splitting strategy, error diagnostics, post-training
tuning lever, production monitoring indicators.
REFORMULATION
One business need can be framed either way.
The two formulations are compared on the SAME cost function
and the SAME test set, never on their native metrics.Summary statement
A supervised learning problem is a classification when its target takes values in a finite unordered set, and a regression when its target takes values on a numeric scale where the gap between two values is interpretable; this qualification depends exclusively on the nature of the target variable selected, and it then determines the entire modeling chain, from the admissible algorithms through to the production monitoring indicators.
Associated quizzes
010.1-quiz-qualification-criterion.md010.2-quiz-classification.md010.3-quiz-regression.md010.4-quiz-decision-tree.md010.5-quiz-ambiguous-cases.md010.6-quiz-consequences-of-the-choice.md010.7-quiz-reformulation.mdNext chapter : 011.0-types-of-classification.md