Classification or Regression: Qualifying the Problem

31 min
Block 2 — Identifying the problem
Objective
qualify any supervised learning problem as classification or regression from the structure of the target variable alone, handle the five ambiguous configurations that resist this qualification, state what the choice determines across the whole modeling chain, and arbitrate between two competing formulations of one business need.
Estimated duration
40 minutes
Prerequisites
chapters 001 to 009, in particular 004 (supervised learning), 006 (features and target) and 007 (X, y, labels, classes)
Associated quizzes
010.1-quiz-qualification-criterion.md to 010.7-quiz-reformulation.md

1. The qualification criterion: the structure of the codomain

1.1 What does not qualify a problem

The statements below are routinely used to justify the choice between classification and regression. None of them is valid.

Statement heardStatusImmediate counter-example
"It is a medical problem, so it is classification"FalsePredicting blood glucose three months out is regression in a medical setting
"I am using a random forest, so it is classification"FalseRandomForestRegressor exists and handles real-valued targets
"My input variables are categorical, so it is classification"FalseThe type of the inputs is independent of the type of the target
"The target is stored as an integer, so it is classification"FalseA count of monthly visits is an integer and belongs to regression
"There are only two possible output values, so it is binary regression"FalseTwo 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.

1.2 The shared formal frame

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.

DEFINITION — Codomain (output space)

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.

1.3 The fundamental fork

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.


2. Classification

DEFINITION — Classification (supervised classification)

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₂, …, cKc_K} 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 valuesClassificationJustification
Test equality y₁ = y₂LegalEquality is the founding relation of Y
Order y₁ < y₂IllegalA nominal set carries no intrinsic order
Compute the gap y₁ − y₂IllegalSubtraction is not defined
Average the target valuesIllegalThe expectation of a nominal variable is meaningless
Count the occurrences of a classLegalYields 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.

2.2 Form of the output

A classifier in fact produces two distinct outputs, and confusing them is a frequent source of error.

OutputNaturescikit-learn methodCodomain
Per-class score or probabilityA vector of K reals summing to 1predict_proba()[0, 1]^K
Predicted classOne categorypredict(){c₁, …, cKc_K}

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.

DEFINITION — Decision boundary

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.

ANALOGY — The mail sorting center

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.

2.3 Representative examples

DomainBusiness questionCodomainK
PaymentsIs this transaction fraudulent?{fraud, legitimate}2
EmailIs this message unsolicited?{spam, ham}2
HealthDoes this patient have the condition?{positive, negative}2
TelecomWill this customer churn?{churn, retain}2
BotanyWhich species is this?{setosa, versicolor, virginica}3
ManufacturingWhich defect affects this part?{scratch, crack, porosity, none}4

3. Regression

DEFINITION — Regression (supervised regression)

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 valuesRegressionPractical consequence
Test equality y₁ = y₂Legal but pointlessExact equality has probability zero on a continuous variable
Order y₁ < y₂LegalEnables rank-based metrics
Compute the gap y₁ − y₂LegalGrounds the notion of residual
Average the valuesLegalGrounds the "predict the mean" baseline
Square the gapLegalGrounds 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".

3.2 Form of the output

OutputNatureUse
Point predictionOne real ŷStandard output of predict()
Prediction intervalA pair [y^low\hat{y}_{\mathrm{low}}, y^high\hat{y}_{\mathrm{high}}]Communicating uncertainty
Conditional quantilesSeveral realsAsymmetric 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.

ANALOGY — The drawer and the scale

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.

3.3 Representative examples and paired examples

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.

DomainCategorical target → classificationNumeric target → regression
Real estateWill the property sell within 90 days?Sale price in dollars
HealthIs the patient diabetic?HbA1c level in percent
EnergyWill the peak load be exceeded?Daily consumption in kWh
MeteorologyWill it rain tomorrow?Maximum temperature in °C
PaymentsIs the transaction fraudulent?Loss amount if fraudulent
Human resourcesWill the candidate accept the offer?Accepted salary in dollars
ManufacturingIs the part within specification?Measured dimension in millimeters
MarketingWill 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.


4. The qualification question and its decision tree

4.1 The question to ask

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 questionProblem 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.

4.2 The three-operation test

When the business question stays ambiguous, the following test settles it mechanically. It applies to the observed values of the target.

Operation testedReading 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

  • Only operation 1 is meaningful: classification (nominal target).
  • Operations 1 and 2 are meaningful, 3 is not: ordinal case, treated in 5.1.
  • All three are meaningful: regression.

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.

4.3 The complete decision tree

4.4 Discrete variables and continuous variables

DEFINITION — Discrete variable and continuous variable

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 ℝ.

TargetDiscrete or continuousNominal or numericProblem type
Iris speciesDiscreteNominalClassification
Transaction statusDiscreteNominalClassification
ZIP codeDiscreteNominalClassification
Monthly visit countDiscreteNumericRegression
Number of claims filedDiscreteNumericRegression
Maximum temperatureContinuousNumericRegression
Sale priceContinuousNumericRegression

4.5 Instrumented check on the nature of the target

scikit-learn exposes a function that inspects the type of a target array. It is a useful control, provided you know its limits.

python
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 = multiclass

Interpretation

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.


5. The five ambiguous cases and how to treat them

Five configurations resist direct qualification. Each calls for a documented decision, not a default choice.

5.1 Ordinal target

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:

AdjustmentImplementationJustification
Order-sensitive metricQuadratic weighted kappa, MAE on ranksPenalizes errors that are further apart in the ordering
Dedicated ordinal modelProportional odds model (McCullagh, 1980), decomposition into K−1 cumulative binary classifiersExploits 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.

5.2 Count target

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 attentionRecommended treatment
Positive support and strong skewPoisson or negative binomial deviance loss rather than MSE
Overdispersion, variance above the meanNegative binomial model
Excess zerosZero-inflated model, or a "zero versus non-zero" classifier followed by a regressor on the non-zeros
Non-integer real-valued predictionRound 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.

5.3 Duration with censoring

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.

DEFINITION — Right censoring

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.

SituationFormulation adoptedJustification
Complete history, every event observedRegression on the durationNo censoring, the standard frame applies
Censoring present, a duration estimate is requiredSurvival analysisThe only frame that uses censored observations correctly
Censoring present, decision made at a fixed horizon HBinary classification, "event before H"Valid provided only subjects whose follow-up reaches H are retained
Heavy censoring and uneven follow-upSurvival analysis, mandatoryRestricting the sample would destroy most of it

5.4 A probability as the target

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 rowProblem typeModeling
A binary outcome, 0 or 1Classification, binaryProbabilistic classifier, predict_proba output, log loss (chapter 061), calibration checked
A measured proportion, for example a conversion rate per storeRegression 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).

5.5 A numeric target deliberately discretized

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).

CriterionDiscretize the target before trainingRegress, then threshold
Information retainedWithin-class variation is lostRetained in full
Cutoff effectTwo values one dollar apart become two different classesNone: continuous treatment
Change of business cutoffComplete relabeling and retrainingChange one constant, no retraining
Several cutoffs at onceOne model per partitionA single model
Readability for the businessImmediateRequires 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.

python
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=  49

Interpretation

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.

5.6 Summary table of the ambiguous cases

CaseStructure of the targetChoice adoptedDeciding reason
OrdinalFinite, ordered, non-metricClassification, with an order-sensitive metric and modelThe codomain remains finite
CountIntegers, infinite, metricRegression, Poisson lossAll three operations are meaningful
Censored durationℝ⁺ partially observedSurvival analysis, or fixed-horizon classificationCensoring invalidates naive regression
Probability[0, 1]Classification if the observed label is binary, regression if a proportion is measuredQualification follows the observed target
Discretized numericℝ recoded into classesRegress then threshold, unless the target is natively categoricalDiscretization destroys information

6. What the choice determines across the whole chain

Qualification happens at step 3 of the project lifecycle (chapter 012). Every later step depends on it.

6.1 Full comparison table

DimensionClassificationRegression
Codomain{c₁, …, cKc_K}, finite, unorderedA subset of ℝ, ordered and metric
Object learnedA partition of the input space, a decision boundaryA response surface defined over the whole input space
Quantity estimatedP(Y = c | X = x), the conditional probability of each classE[Y | X = x], the conditional expectation, or a conditional quantile
Raw model outputA vector of K scoresOne real number
Delivered outputOne class, after a threshold or an argmaxThe value, optionally bracketed by an interval
Notion of errorBinary disagreement, countedSigned residual, graded
Usual loss functionsCross-entropy, log loss, hinge, focal loss; Gini and entropy split criteriaMSE, MAE, Huber, quantile pinball, Poisson deviance, RMSLE
Evaluation metricsAccuracy, precision, recall, specificity, F1, F-beta, balanced accuracy, log loss, ROC-AUC, PR-AUCMAE, MSE, RMSE, R², adjusted R², MAPE, sMAPE, MedAE, RMSLE
Representative algorithmsLogistic regression, decision tree, random forest, boosting, SVC, k-NN, naive Bayes, MLPLinear regression, Ridge, Lasso, Elastic Net, decision tree, random forest, boosting, SVR, k-NN, MLP
scikit-learn suffix…Classifier…Regressor
Reference baselineAlways predict the majority classAlways predict the mean or the median
Data splittingStratify on the target, recommended (chapter 027)Random split; stratify on binned target if it is heavily skewed
Distributional pathologyClass imbalance (chapters 050 and 051)Skew, extreme values, heteroscedasticity
Post-training tuning knobDecision threshold (chapter 062)No direct equivalent; possible rescaling or recalibration
Error diagnosticsConfusion matrix, false positive and false negative analysisResidual plots, residuals against fitted values
Nature of the business tradeoffWhich error costs more, a false positive or a false negativeWhich error costs more, over-prediction or under-prediction
Production monitoringDrift in the distribution of predicted classesDrift in the distribution and the mean of the predictions

6.2 Two structural points

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.


7. Reformulation: one business need, two possible frames

7.1 The principle

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.

DEFINITION — Remaining Useful Life (RUL)

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.

7.2 The two formulations, quantified

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.

python
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=979

Interpretation

ObservationReading
Both formulations cut the cost from $2,076,000 to roughly $0.4MThe 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 horizonClassification 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 failuresThe 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 30A 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 modelChanging the horizon under formulation A requires a complete relabel and retrain
The MAE of B is 18.5 daysAn 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.

7.3 Criteria for arbitrating between the two formulations

CriterionPoints to classificationPoints to regression
Decision horizonSingle, fixed, stable over timeMultiple, variable, or negotiated case by case
Label availabilityOnly the occurrence of the event is recordedComplete life cycles are documented
Censoring in the historySubstantial: fixed-horizon classification is more robustLow, or handled by survival analysis
Volume of eventsLow: concentrate model capacity on the boundaryHigh: the richness of a continuous target can be exploited
Nature of the downstream decisionBinary, immediate, no prioritizationScheduling, planning, resource allocation
Need to rank casesServed by the probability scoreServed by the predicted value, directly interpretable
Communication to the business"83% risk within 30 days""about 45 days left"
Sensitivity to policy changeLow: any change of horizon forces a retrainHigh: a change of horizon is one constant to edit
Control over the error tradeoffDirect, through the decision thresholdIndirect, 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.

ANALOGY — The traffic light and the countdown timer

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.


8. Common reasoning mistakes

MISTAKE — Qualifying the problem by the business domain

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."

MISTAKE — Qualifying the problem by the algorithm under consideration

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."

MISTAKE — Confusing logistic regression with regression

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."

MISTAKE — Inferring the problem type from the storage type of the target

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."

MISTAKE — Treating a regression problem as classification for convenience

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."

MISTAKE — Concluding that a model producing probabilities does regression

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."

MISTAKE — Applying regression to a duration without handling censoring

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."

MISTAKE — Comparing two competing formulations on heterogeneous metrics

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."


9. Summary

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.md
  • 010.2-quiz-classification.md
  • 010.3-quiz-regression.md
  • 010.4-quiz-decision-tree.md
  • 010.5-quiz-ambiguous-cases.md
  • 010.6-quiz-consequences-of-the-choice.md
  • 010.7-quiz-reformulation.md

Next chapter : 011.0-types-of-classification.md