Explanatory Variables and the Target

54 min
Block 1 — Core vocabulary
Objective
define the explanatory variable and the target variable rigorously, master their competing synonyms and the discipline each one comes from, formalize an observation as a feature vector in a space of dimension p, and apply the professional criteria that decide whether an available column may legitimately be submitted to a model.
Estimated duration
40 minutes
Prerequisites
chapters 001 to 005
Associated quizzes
006.1-quiz-features-target-relation.md to 006.7-quiz-case-studies.md

1. The structure of a supervised problem: FEATURES to MODEL to TARGET

1.1 The mental formula

Every supervised learning problem reduces to a single structure, whatever the application domain, the algorithm chosen or the volume of data.

Memorize the formula literally. It carries three methodological commitments.

  1. What sits on the left is known at prediction time. A variable placed on the input side that will not be available at the instant the prediction must be produced invalidates the entire setup. This is the first selection criterion, developed in section 6.
  2. What sits on the right is what you are trying to obtain. The target is never handed to the model during prediction. Its value is precisely what the model is asked for.
  3. The arrow is not a causal relation. It expresses a statistical association exploited for predictive purposes. Chapter 016 treats the distinction between correlation and causation.

1.2 The two operating regimes

The same structure reads differently depending on the phase. This is the most common source of confusion among beginners.

PhaseExplanatory variablesTarget variableWhat is produced
TrainingKnown, suppliedKnown, suppliedThe model
ValidationKnown, suppliedKnown but hidden from the model, used for comparisonA performance measurement
Production predictionKnown, suppliedUnknownAn estimate ŷ
Retrospective monitoringKnownObserved later, with a delayA drift measurement

Point of caution. During training the target sits in the dataset just like any other column. Its functional nature is nevertheless radically different. Treating it as an ordinary column, or forgetting to remove it from the inputs, produces a model that predicts perfectly in training and is unusable in production.

ANALOGY — The detective and the clues

An investigator never has the answer. What the investigator has are clues: a fingerprint, a timestamp, a witness statement, a bank record. Each clue is partial information, incomplete, sometimes misleading. The investigator can only reason on what has been collected.

Explanatory variables are exactly those clues: they are the only information the model holds when it commits to an answer. The target variable is the identity of the culprit, that is, what the investigation must establish.

Three consequences follow from the analogy, all of them technically exact.

  • A clue that is unavailable does not exist. An investigator cannot ground a deduction in surveillance footage from a camera that was never installed. A model cannot use a variable that will not be populated at prediction time.
  • A clue that postdates the crime is not a clue, it is a confession. If the investigator "deduces" the culprit from the signed confession, nothing has been deduced. That is the mechanism of data leakage, treated in chapter 028.
  • The quality of the clues determines the quality of the investigation more than the interrogation technique does. Section 6.6 develops this point.

2. The explanatory variable

2.1 Definition

DEFINITION — Explanatory variable (feature, characteristic)

Rigorous definition

A measured or constructed quantity, attached to every observation in a dataset, whose values are submitted to the model as input and from which the model produces an estimate of the target variable.

Equivalent formulation in learning theory

A component of the input vector x belonging to the feature space 𝒳, on which the prediction function f : 𝒳 → 𝒴 is defined — the function that the learning algorithm selects from a hypothesis class.

In plain terms

A piece of information you give the machine to help it answer.

The nature of the concept

An explanatory variable is a functional role, not a data type. A column is not an explanatory variable by nature; it becomes one through a design decision, and that decision is revocable. The same column can be explanatory in one project, the target in another, excluded in a third. Section 4.3 develops this.

Point of caution

Taken literally, the word explanatory misleads. An explanatory variable explains nothing in the causal sense: it carries information statistically associated with the target. A strongly predictive variable may have no causal link with the target whatsoever and be nothing more than an indirect marker of an unobserved common cause.

2.2 What an explanatory variable is not

Common statementStatusJustification
"Every column in the file is a feature"IncorrectIdentifiers, the target and leaking variables are excluded (chapter 005, section 3.2)
"A feature explains the target"Incorrect in the strict senseIt is associated with the target; causal explanation belongs to a different methodological framework (chapter 016)
"A feature must be numeric"IncorrectIt may be categorical, temporal or textual; numeric encoding is a later step (chapters 022 and 023)
"The more features, the better the model"IncorrectPast a certain point, adding variables degrades generalization performance (chapters 025 and 031)
"A feature is given by the data"Partly inaccurateA large share of the most predictive variables are constructed, not recorded (chapter 024)

2.3 The taxonomy of synonyms

The field aggregates vocabulary from distinct disciplines, each of which coined its own term for the same object. The names below are strictly equivalent in practice; they differ in origin, register and connotation.

TermDiscipline of originDistinctive connotationCurrent register
FeaturePattern recognition and computer visionA quantity extracted from a raw signal, possibly constructedDominant in machine learning
CharacteristicLiteral rendering of featureIdentical to featureCommon in formal writing; rare in speech
Explanatory variableApplied statistics, modelingSuggests a contribution to explaining the phenomenonAcademic standard
Independent variableExperimental statistics, design of experiments, experimental psychology (from Fisher, 1935)Suggests a variable manipulated by the experimenterFrequent but problematic in ML (section 4)
Input variable, inputControl theory, systems theory, engineeringNeutral: what goes into the boxVery common, unambiguous
PredictorApplied statistics, regression literatureStresses the predictive purpose rather than the explanatory oneCommon, particularly well suited to ML
RegressorEconometricsA term of the regression model, tied to a coefficientReserved for parametric linear models
CovariateBiostatistics, epidemiology, clinical trialsA variable whose effect is adjusted for in order to isolate a treatment effectStandard in clinical research
AttributeSymbolic learning, data mining, relational databases (Quinlan, 1986)A descriptive property of an entityDated in ML, alive in databases
DescriptorChemometrics, cheminformaticsA computed quantity describing a structureSpecialized
Exogenous variableStructural econometricsDetermined outside the modeled systemSpecialized, theoretically loaded
FactorDesign of experiments, analysis of varianceA controlled categorical variableAmbiguous: means something else in factor analysis

Professional recommendation. In writing, use explanatory variable or feature; both are unobjectionable, and feature is the established usage in code and in conversation. When speaking to business stakeholders, input variable or information supplied to the model are understood immediately. Avoid independent variable for the reasons set out in section 4.

DEFINITION — Predictor

Rigorous definition

A variable whose values are used to estimate those of another variable, independently of any explanatory or causal claim.

Why the term is useful

It is the most honest term epistemologically for machine learning: it names exactly what is being sought — predictive power — without suggesting any understanding of the underlying mechanism.

Point of caution

Do not confuse predictor in the sense of an input variable with predictor in the sense of an entire model, a usage found in the English-language literature where "a predictor" sometimes designates the complete prediction system. Context resolves the ambiguity; in a technical report, state which sense you mean the first time you use it.

DEFINITION — Regressor and covariate

Regressor (econometrics)

A variable appearing on the right-hand side of a regression equation, tied to an estimated coefficient. In the model y = β₀ + β₁x₁ + … + βp\beta_p xpx_p + ε, the xjx_j are the regressors and the explained variable y is the regressand.

The term is inseparable from an explicit parametric model. Calling the inputs of a random forest "regressors" is an abuse of language: no coefficient is attached to any variable there.

Covariate (biostatistics)

A measured variable whose effect is accounted for in the model so as to isolate the effect of a variable of interest, typically a treatment. In a clinical trial evaluating a drug, patient age and sex are covariates: they are not the object of the study but they influence the outcome.

Point of caution

The vocabulary of covariates presupposes a hierarchy among variables: one variable of interest, several adjustment variables. That hierarchy does not exist in predictive machine learning, where every explanatory variable has the same functional status. Importing the term into an ML project imports a conceptual structure with nothing to apply to.

2.4 The two senses of the word feature

The term is used in the literature with two different scopes, and confusing them causes real errors.

SenseWhat it designatesExample
Broad senseAny descriptive column of the dataset, whatever its usesignup_date is "a feature of the dataset"
Strict senseAny input actually submitted to the model after preparationtenure_days, derived from signup_date, is a feature of the model

The gap between the two senses is exactly the scope of feature engineering (chapter 024) and feature selection (chapter 025).

Notational consequence. The number of explanatory variables p in a model is almost never equal to the number of columns in the original file. Saying "my dataset has 14 features" without stating which sense you mean is a reliable source of misunderstanding between practitioners.


3. The target variable

3.1 Definition

DEFINITION — Target variable (target, variable to predict)

Rigorous definition

A quantity whose value is unknown at the moment the system must commit to an answer, and whose estimation is the purpose of the model. In supervised learning, its observed value is available for the observations of the training set, which makes it possible to construct an error signal and therefore to learn.

Position in the formalism

An element y of the output space 𝒴. The pair (x, y) constitutes a labeled example; the training set is a collection of such pairs assumed drawn from an unknown and fixed joint distribution P(X, Y).

In plain terms

What you want the machine to guess.

The criterion that defines supervised learning

It is the existence of an observed target that defines supervised learning and separates it from unsupervised learning (chapter 003). With no target there is no error signal, therefore nothing to minimize, therefore no supervised learning is possible.

Point of caution

The target variable is not given by nature. It is constructed by a design decision that fixes what counts as the phenomenon to predict and over what horizon. Section 3.4 develops this.

3.2 The taxonomy of synonyms

TermDiscipline of originParticular scopeRegister
TargetMachine learningNeutral, any kind of targetDominant
Target variableMachine learningIdentical, slightly more formalStandard
Dependent variableExperimental statistics, experimental psychologySuggests causal dependence on the manipulated variablesFrequent, problematic in ML (section 4)
Response variableStatistics, design of experimentsWhat responds to a controlled variation of the inputsAcademic standard
Explained variableStatistics and econometricsSymmetric counterpart of "explanatory variable"Common in formal writing
Endogenous variable, regressandStructural econometricsDetermined inside the modeled systemSpecialized
OutputControl theory, systems theoryNeutral: what comes out of the boxVery common
LabelSupervised learning, data annotationRestricted to categorical targetsDominant in classification
ClassPattern recognition, classificationOne particular level of the labelDominant in classification
Ground truthRemote sensing, then computer visionThe reference value held to be true, as opposed to the predictionStandard in annotation
Gold standardBiostatistics, medical diagnosisThe reference procedure used to establish the true valueStandard in medicine
Criterion variablePsychometrics, personnel selectionThe outcome the instrument seeks to predictSpecialized
DEFINITION — Label

Rigorous definition

A categorical value assigned to an observation, designating its membership in one level of a finite set of predefined classes.

The discriminating point

Label is not an exact synonym of target. Every label is a target; not every target is a label.

Problem typeTargetMay you say "label"
Binary classification: fraud / normalCategorical, 2 levelsYes
Multiclass classification: cat / dog / horseCategorical, k levelsYes
Regression: price in eurosContinuous numericNo, by established convention

In plain terms

The tag stuck on the example: "this is spam", "this is a fraud".

Point of caution

The phrase labeled data is used in the literature for any dataset carrying an observed target, regression included. The usage is therefore broader than the strict definition of a label. Chapter 007 works out the articulation between label, class and numeric coding.

DEFINITION — Ground truth

Rigorous definition

The value of the target variable held to be exact, established by a reference procedure independent of the model, and used as the benchmark for training and evaluation.

Origin of the term

The expression comes from remote sensing: validating the interpretation of satellite imagery required measurements taken in the field, on the ground.

Major point of caution

Ground truth is not the truth. It is a measurement, produced by a fallible protocol: human annotation subject to disagreement, imperfect medical diagnosis, a fraudulent transaction that went undetected and was therefore labeled "normal". The measured performance of a model is bounded by the quality of the labeling. A model cannot learn a distinction correctly if its labels do not encode that distinction correctly.

Operational consequence

Before blaming the algorithm for a disappointing result, audit the labeling protocol: who labeled, under what definition, with what inter-annotator agreement rate.

3.3 One target, or several

ConfigurationStructure of the targetNameReference
A single target column, one value per observationy ∈ ℝ or y ∈ {c₁, …, ckc_k}Standard caseChapter 010
An observation may belong to several classes at oncey ∈ {0,1}^kMultilabel classificationChapter 011
Several numeric targets predicted jointlyy ∈ Rm\mathbb{R}^mMulti-output regressionChapter 048
Categorical target with ordered levelsy ∈ {c₁ < … < ckc_k}Ordinal classificationChapter 011

Point of caution. The presence of several columns that could serve as the target does not license treating them as one target. Two distinct targets define two distinct problems, each demanding its own model, its own metrics and its own validation.

3.4 The target is a construction, not a natural datum

No operational system spontaneously produces a column named churned. That column is the result of a chain of explicit decisions.

DecisionEffect on the project
Definition of the eventSets the positive rate, hence the degree of imbalance (chapter 050)
Time horizonSets the difficulty of the problem and the operational usefulness of the prediction
Population in scopeSets the model's domain of validity and the selection biases
Observation dateSets which explanatory variables are legitimately available (section 6.1)

Guiding principle. No algorithmic refinement compensates for a badly defined target. Formalizing the target is the first step in the lifecycle of a project (chapter 012), and it belongs to a discussion with the business, not to a technical decision.


4. Dependent and independent variables

4.1 Origin of the terminology

DEFINITION — Independent variable and dependent variable

Rigorous definition in the original experimental setting

In a designed experiment, the independent variable is the quantity whose values the experimenter deliberately sets, independently of every other factor in the setup; the dependent variable is the measured quantity, for which one seeks to establish whether it varies as a function of the first.

Historical context

This terminology comes from the experimental methodology formalized by Ronald Fisher (The Design of Experiments, 1935) and spread by experimental psychology. It presupposes a setup in which the experimenter manipulates one variable, controls the others and randomizes the assignment of units, which is what licenses a causal inference.

In plain terms

What you set yourself, and what you observe as a result.

Point of caution

Those conditions are essentially never met in applied machine learning, which operates on observational data collected without an experimental design. The vocabulary survives; its justification has not.

4.2 Why the terminology misleads in machine learning

DifficultyWhat the term suggestsWhat holds in machine learning
Statistical independenceThat the explanatory variables are independent of one anotherThey are almost always correlated with one another. Strong correlation among explanatory variables has a name, multicollinearity, and it is a problem treated in chapter 017
Experimental manipulationThat the analyst sets the values of the input variablesThey are observed, not manipulated. Nobody "sets" a customer's age or an apartment's floor area
Causal dependenceThat the target varies because of the input variablesThe model captures an association. Causal inference requires a specific framework, not a predictive model (chapter 016)
Intrinsic propertyThat a variable is independent or dependent by natureThe status is a role assigned by the project, and it reverses from one project to the next
Logical symmetryThat only one reading is possibleThe direction of the arrow is a design choice constrained by temporal availability, not by logic

The most frequent misreading. Concluding that explanatory variables must be independent of one another because they are called "independent". The requirement of low collinearity does exist for certain parametric models, but it has nothing to do with the origin of the term, which refers to independence with respect to the experimental setup, not among variables.

4.3 The role is functional, not intrinsic

The same quantity changes role depending on the question asked. The column does not change; the project does.

QuantityProject where it is the targetProject where it is explanatory
Transaction amountAverage basket forecastingPayment fraud detection
Customer satisfaction scorePredicting post-call satisfactionPredicting churn
Length of hospital stayHospital capacity planningPredicting readmission risk
Bearing temperatureThermal forecasting for equipmentDetecting an imminent failure
SalarySalary estimation at hiringCredit scoring

4.4 Terminological recommendation

SituationRecommended phrasingPhrasing to avoid
Technical reportExplanatory variables / target variableIndependent variables / dependent variable
Code and technical documentationfeatures / target, X / y
Presentation to a business audienceInformation supplied / value to predictAny untranslated statistical term
Scientific article in statisticsPredictors / response variable
Job interviewExplanatory variables, while signaling that you know the synonymsUsing a single term with no perspective on it

Expected professional stance. Know the synonyms, be able to translate between registers, and be able to explain why independent variable is an inherited term ill-suited to the observational setting of machine learning.


5. Feature vector and feature space

5.1 From row to vector

DEFINITION — Feature vector

Rigorous definition

The representation of an observation as an ordered p-tuple of values, one per retained explanatory variable:

x=(x1,x2,,xp)Rp\displaystyle x = (x_1, x_2, \dots , x_p)^{\top} \in \mathbb{R}^p

where p is the number of explanatory variables and xjx_j the value taken by the j-th variable for that observation.

Three binding properties

  1. The order is fixed and meaningful. The j-th component always corresponds to the same variable, for every observation. A permutation between training and prediction produces predictions that are numerically valid and semantically absurd.
  2. The dimension is constant. Every observation is described by the same number of components. An observation missing a variable cannot be processed as it stands: it requires imputation or exclusion (chapter 019).
  3. The components are numeric. Categorical variables must have been encoded beforehand (chapter 022).

In plain terms

A row of the table, reduced to the useful columns and converted into a sequence of numbers.

DEFINITION — Design matrix (X)

Rigorous definition

A matrix X ∈ Rn×p\mathbb{R}^{n \times p} whose i-th row is the feature vector xᵢᵀ of the i-th observation and whose j-th column is the vector of values taken by the j-th explanatory variable across the n observations.

The associated target vector is y ∈ Yn\mathcal{Y}^n, where 𝒴 = ℝ in regression and 𝒴 = {c₁, …, ckc_k} in classification.

Origin of the term

Design matrix comes from the design-of-experiments literature, where the rows of the matrix described the experimental configuration of each run. The term survives in regression and in statistical learning.

Notational convention

Capital X for the matrix, lowercase y for the target vector: the case signals the difference in dimensionality, two dimensions against one. The convention is universal in the literature and in software libraries.

ObjectNotationDimensionContent
Training set(X, y)n pairs (observation, target)
Matrix of explanatory variablesXn × pNumeric values
Target vectorynOne value per observation
Feature vector of one observationxᵢpRow i of X
Value of one variable for one observationxijx_{ij}scalarCell (i, j)
Vector of one variable across the datasetX[:, j]nColumn j of X
Prediction for one observationŷᵢscalar or vectorOutput of the model

5.2 Separating X from y in practice

The dataset used below is simulated so that every output in this chapter can be reproduced. It describes 10,000 telecom customers and carries one binary target, churned.

python
import numpy as np
import pandas as pd

rng = np.random.default_rng(96)
n = 10_000

age = rng.integers(18, 86, n)
tenure_months = rng.integers(1, 121, n)
plan_type = rng.choice(["Mobile", "Fiber", "Fiber+TV"], n, p=[0.42, 0.38, 0.20])
contract = rng.choice(["Monthly", "12_months", "24_months"], n, p=[0.35, 0.38, 0.27])

base_price = np.select([plan_type == "Mobile", plan_type == "Fiber"], [26.0, 48.0], 74.0)
monthly_bill = np.round(np.clip(base_price + rng.normal(0, 7, n), 15.0, 95.0), 2)
support_calls = rng.poisson(1.6, n)
satisfaction = np.clip(np.round(rng.normal(3.6, 1.1, n)), 1, 5)

logit = (-0.7
         - 0.016 * tenure_months
         + 0.24 * support_calls
         - 0.38 * satisfaction
         + 0.013 * monthly_bill
         + np.where(contract == "Monthly", 0.95, 0.0))
churned = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)

pd.DataFrame({
    "client_id": [f"C-{i + 1:05d}" for i in range(n)],
    "age": age,
    "tenure_months": tenure_months,
    "plan_type": plan_type,
    "contract": contract,
    "monthly_bill": monthly_bill,
    "support_calls": support_calls,
    "satisfaction": satisfaction,
    "churned": churned,
}).to_csv("telecom_churn.csv", index=False)

The split itself is three lines. Everything that matters is in the decision of what goes into X and what does not.

python
import pandas as pd

df = pd.read_csv("telecom_churn.csv")

target = "churned"
identifiers = ["client_id"]

X = df.drop(columns=[target] + identifiers)
y = df[target]

print("X :", X.shape)
print("y :", y.shape)
print()
print(X.dtypes)
X : (10000, 7)
y : (10000,)

age                int64
tenure_months      int64
plan_type            str
contract             str
monthly_bill     float64
support_calls      int64
satisfaction     float64
dtype: object

Interpretation. The dataset holds n = 10,000 observations. The matrix X has seven columns, the target and the identifier having been removed. The shape of y, (10000,), confirms that it is a one-dimensional vector and not a single-column matrix. That distinction is the source of warnings and errors in several libraries.

Point of caution. Write df.drop(columns=[target]) before any other transformation. Any preparation step computed on a dataset that still contains the target exposes you to leakage (chapter 028).

5.3 The feature vector of one observation

python
print(X.iloc[0])
age                     74
tenure_months           72
plan_type           Mobile
contract         12_months
monthly_bill         27.66
support_calls            3
satisfaction           4.0
Name: 0, dtype: object

This row is not yet a vector of Rp\mathbb{R}^p: two components are text. Encoding the categorical variables produces the numeric representation actually submitted to the model.

python
X_encoded = pd.get_dummies(X, columns=["plan_type", "contract"])
X_numeric = X_encoded.astype(float)

print("Columns before encoding:", X.shape[1])
print("Columns after encoding: ", X_encoded.shape[1])
print(list(X_encoded.columns))
print("dtype:", X_numeric.to_numpy().dtype, "| shape:", X_numeric.to_numpy().shape)
print("Feature vector of the first observation:")
print(X_numeric.to_numpy()[0])
Columns before encoding: 7
Columns after encoding:  11
['age', 'tenure_months', 'monthly_bill', 'support_calls', 'satisfaction',
 'plan_type_Fiber', 'plan_type_Fiber+TV', 'plan_type_Mobile',
 'contract_12_months', 'contract_24_months', 'contract_Monthly']
dtype: float64 | shape: (10000, 11)
Feature vector of the first observation:
[74.   72.   27.66  3.    4.    0.    0.    1.    1.    0.    0.  ]

Interpretation. The observation, described at the outset by seven heterogeneous columns, is now a point of ℝ¹¹. The first five components are the original numeric variables; the next six are binary indicators coding the levels of the two categorical variables. The values 1 in positions eight and nine identify a Mobile plan under a 12-month contract.

Two lessons of general scope.

  • p is not the number of columns in the file. Here seven columns produce eleven dimensions. With high-cardinality categorical variables the gap becomes considerable: a municipality variable with 400 levels adds 400 dimensions on its own under indicator encoding.
  • The scales are heterogeneous. tenure_months ranges from 1 to 120, monthly_bill from 15 to 95, and the indicators are 0 or 1. This heterogeneity has no effect on a decision tree and is decisive for any model based on distances or on gradient descent (chapter 023).

5.4 The feature space

DEFINITION — Feature space

Rigorous definition

The set 𝒳 of all admissible values of the feature vector. In the usual case of p real-valued variables, 𝒳 ⊆ Rp\mathbb{R}^p, equipped with a normed vector space structure that allows a distance between observations to be defined.

Geometric formulation

Each observation is a point in that space; each explanatory variable is an axis; the dataset is a cloud of n points in a space of dimension p. The learning task consists in identifying a structure in that space — a boundary separating regions in classification, a response surface in regression — that correctly reproduces the link between position and target value.

In plain terms

The set of all possible profile sheets, seen as points on a map with p dimensions.

Point of caution

Geometric intuition acquired in dimension 2 or 3 stops being reliable beyond it. In high dimension, volume concentrates in the peripheral regions, pairwise distances become almost all equivalent, and the notion of a neighborhood loses its discriminating power. This phenomenon, known as the curse of dimensionality, particularly affects distance-based methods (chapter 040).

ANALOGY — The map and the measurement points

A flat map has two axes, longitude and latitude. Each city occupies a unique point on it. Two cities that are neighbors on the map are neighbors in reality: proximity in the representation space means something.

The feature space is that map, with p axes instead of two. Two customers whose feature vectors are close are "similar" customers in the sense of the retained variables.

Three exact extensions of the analogy.

  • Changing the variables amounts to changing the map. A relief map and a rail-network map place the same cities at different distances from one another. That is the stake of feature engineering: building the map on which the phenomenon becomes legible.
  • Changing the units distorts the map. If one axis is graduated in meters and the other in kilometers, the notion of proximity is dominated by the first. That is the justification for scaling (chapter 023).
  • A map with 300 axes cannot be read by eye. Visualization requires a projection into two or three dimensions, an operation that necessarily loses information (chapter 015).

5.5 The model as a function on the feature space

ElementFormalizationReading
An observationx ∈ 𝒳 ⊆ Rp\mathbb{R}^pA point
The true targety ∈ 𝒴The true value
The modelf : 𝒳 → 𝒴A function defined on the whole space
The predictionŷ = f(x)The value assigned to the point
The error on one observationℓ(y, ŷ)The gap measured by a loss function
The learning objectiveminimize 𝔼[ℓ(Y, f(X))]Reduce the expected error over the distribution, not over the sample

Essential point. The model is defined over the entire space, including the regions where no observation was ever recorded. It will produce a prediction for a feature vector lying outside the domain covered by training, without signaling that the region was never observed. This silent extrapolation is a major source of production failure and is the reason data drift is monitored (chapter 082).


6. Criteria for admitting an explanatory variable

Having a column does not license using it. Four successive filters apply, in this order, before any consideration of performance.

6.1 First criterion: availability at prediction time

DEFINITION — Availability at prediction time

Rigorous definition

A variable is available at prediction time tpredt_{\mathrm{pred}} if its value is observed, accessible and final in the information systems at that instant, for every observation on which the model will have to commit to an answer.

Operational formulation

Let tpredt_{\mathrm{pred}} be the instant at which the prediction must be produced and tobst_{\mathrm{obs}} the instant at which the value of the variable actually becomes known. The variable is admissible if and only if:

tobst_{\mathrm{obs}}tpredt_{\mathrm{pred}}, for every observation, without exception

In plain terms

Will I really have this information when I have to answer, or only in my history because I am looking at the past?

Point of caution

A historical dataset is assembled after the fact: it naturally contains information accumulated after the decision instant. Nothing in the file distinguishes an available variable from a variable that came later. Only knowledge of the business process settles it. This check cannot be automated.

Use caseCandidate variabletobst_{\mathrm{obs}} relative to tpredt_{\mathrm{pred}}Verdict
Customer churn within 90 daysTenure in monthsBeforeAdmissible
Customer churn within 90 daysCancellation dateAfter, and defined by the eventExcluded, manifest leakage
Customer churn within 90 daysDeparture reason entered by the advisorAfterExcluded
Customer churn within 90 daysNumber of support calls over the last 6 monthsBefore, if the window is capped at tpredt_{\mathrm{pred}}Admissible under strict windowing
Credit approvalIncome declared at applicationBeforeAdmissible
Credit approvalNumber of missed payments on the granted loanAfterExcluded
Estimating a property sale priceFloor area, year builtBeforeAdmissible
Estimating a property sale priceDays on marketAfter listing, known only afterwardsExcluded
Predictive maintenance within 7 daysMean vibration over the last 24 hoursBeforeAdmissible
Predictive maintenance within 7 daysFault code from the failure diagnosisAfterExcluded
Medical triage at admissionVital signs on arrivalBeforeAdmissible
Medical triage at admissionTreatment administeredAfter, and a consequence of the diagnosisExcluded

Three forms of unavailability, two of which are routinely overlooked.

FormDescriptionIllustration
Temporal unavailabilityThe value does not yet exist at tpredt_{\mathrm{pred}}Total amount billed over the current year
Latency unavailabilityThe value exists but is consolidated in the systems only after a delay longer than the decision windowAn external score refreshed monthly, used in real-time scoring
Scope unavailabilityThe value exists for the historical population but not for the target populationA variable populated only for customers of an acquired subsidiary

Point of caution on latency. A model validated on a complete history can collapse in production because one variable arrives forty-eight hours late and therefore shows up as systematically missing at prediction time. The check is not only whether the variable exists, but whether it is effectively available in the calling system, with the required freshness.

The full mechanism by which an unavailable variable damages a project, its subtler forms and the detection protocols are treated in chapter 028.

6.2 Second criterion: absence of leakage

DEFINITION — Data leakage

Rigorous definition

The presence, among the information used to build the model, of information that will not legitimately be available at prediction time, or that is determined by the value of the target, leading to an overestimate of the measured performance and to failure in production.

In plain terms

The model saw the answer, directly or indirectly, during training.

The two broad families

FamilyMechanismDetection
Leakage through a variableA column encodes all or part of the targetAbnormally high performance, importance concentrated on one variable
Leakage through the protocolA statistic computed on the whole dataset before splitting contaminates the test setSmall gap between validation and test, collapse in production

The most reliable warning signal

Performance clearly above what the business expects. A model reaching 0.99 AUC on a problem reputed to be hard should be suspected of leakage before it is celebrated.

Point of caution

Leakage raises no runtime error. It produces excellent results. That is exactly what makes it dangerous: nothing invites you to look for it.

Type of suspect variableControl questionExample
Consequence variableIs the value produced because the event took place?churn_date, cancellation_reason, amount_refunded
Treatment variableDoes the value reflect an action triggered by knowledge of the outcome?retention_offer_made, case_sent_to_collections
Unwindowed aggregateDoes the aggregate cover a period after tpredt_{\mathrm{pred}}?total_transactions, annual_average
Near-perfect proxyIs the correlation with the target suspiciously trivial?account_status = "closed" to predict churn
Order-bearing identifierDoes the identifier implicitly encode chronology or group?Sequential numbers assigned in batches, one batch per class

6.3 Third criterion: business plausibility

A variable statistically associated with the target but with no plausible mechanism must be examined before it is retained. Four outcomes are possible.

DiagnosisNature of the linkCourse of action
Identified business mechanismWell-founded associationKeep
Indirect marker of an unobserved causeReal but fragile associationKeep with reservations, document, monitor stability
Spurious correlation specific to the sampleAssociation with no foundationExclude; it will not reproduce
Collection artifactThe association comes from how the data were assembledExclude and fix the collection

Point of caution. Business plausibility is a filter, not a proof. A plausible variable may be useless, and a variable whose mechanism is not understood may be genuinely predictive. The criterion serves to identify the variables that need examination, not to settle the matter on its own.

Point of caution on stability. A variable whose distribution or definition shifts over time — a nomenclature overhaul, a change of collection system, a modified business rule — degrades the model without triggering any technical alert. Monitoring these shifts is treated in chapter 082.

6.4 Fourth criterion: legality and ethics

CategoryStatusSpecific difficulty
Directly sensitive variables: ethnic origin, religion, political opinions, health, sexual orientationStrictly regulated or prohibited depending on jurisdiction and purposeEasy to identify
Indirect variables strongly correlated with a sensitive oneThe prohibition is often circumvented unintentionallyPostal code can stand in for origin; a first name for gender
Variables collected without a legal basisUnusableProvenance must be traceable
Variables produced by another modelUsable with careCascading dependency, increased opacity, bias propagation

Point of caution. Removing sensitive variables is not enough to produce a fair model. Indirect variables reconstruct the information that was deleted. A fairness audit is conducted on the model's predictions, not on the list of its inputs alone (chapter 080).

6.5 An eight-question control grid

#QuestionIf the answer is unfavorable
1Will the variable be populated at prediction time, for the whole target population?Exclusion
2Is its value final at that instant, or revised later?Exclusion, or explicit windowing
3Is its value a consequence of the event to be predicted?Exclusion for leakage
4Does an aggregate it contains spill over into the later period?Recompute with a capped window
5Does a plausible business mechanism link this variable to the target?Detailed review
6Are its definition and distribution stable over time?Reinforced monitoring
7Is its use lawful given the purpose and the regulation?Exclusion
8Is its acquisition cost in production compatible with the intended use?Trade-off

These eight questions come before any statistical measurement. Selection methods based on importance, correlation or performance intervene after this filtering, and are treated in chapter 025.

6.6 Feature quality dominates the choice of algorithm

The observation below is documented by industrial practice and by modeling competitions alike: for a fixed dataset, the gain obtained by enriching the information supplied to the model generally exceeds the gain obtained by substituting one algorithm for another.

The demonstration is reproducible. The data are simulated, so the generating mechanism is known exactly: the price is the product of the floor area and the local price per square meter, discounted for the age of the building. Six noise variables with no link to the target are also present, to reproduce the ordinary condition of a real dataset.

python
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.metrics import r2_score

rng = np.random.default_rng(7)
n = 600

area_sqm = rng.uniform(20, 160, n)
local_price_sqm = rng.uniform(2000, 7000, n)
year_built = rng.integers(1900, 2021, n)
building_age = 2024 - year_built

# Generating mechanism: the price is a PRODUCT, discounted for age
price = area_sqm * local_price_sqm * (1 - 0.0025 * building_age) + rng.normal(0, 40_000, n)

noise = pd.DataFrame({f"noise_{j+1}": rng.normal(0, 1, n) for j in range(6)})

S1 = pd.concat([pd.DataFrame({"area_sqm": area_sqm, "year_built": year_built}), noise], axis=1)
S2 = pd.concat([pd.DataFrame({"area_sqm": area_sqm, "year_built": year_built,
                              "local_price_sqm": local_price_sqm}), noise], axis=1)
S3 = S2.copy()
S3["theoretical_value"] = area_sqm * local_price_sqm
S3["building_age"] = building_age
S4 = S3.drop(columns=[f"noise_{j+1}" for j in range(6)])

feature_sets = [
    ("S1 raw, incomplete", S1),
    ("S2 raw, complete", S2),
    ("S3 engineered", S3),
    ("S4 engineered, denoised", S4),
]
models = [
    ("Linear regression", LinearRegression()),
    ("Decision tree", DecisionTreeRegressor(max_depth=6, random_state=0)),
    ("Gradient boosting", HistGradientBoostingRegressor(random_state=0)),
]

print(f"{'Feature set':26s} | {'Model':18s} |  p | R2 test")
print("-" * 66)
for set_name, X in feature_sets:
    X_tr, X_te, y_tr, y_te = train_test_split(X, price, test_size=0.3, random_state=0)
    for model_name, model in models:
        model.fit(X_tr, y_tr)
        r2 = r2_score(y_te, model.predict(X_te))
        print(f"{set_name:26s} | {model_name:18s} | {X.shape[1]:2d} | {r2:7.3f}")
Feature set                | Model              |  p | R2 test
------------------------------------------------------------------
S1 raw, incomplete         | Linear regression  |  8 |   0.543
S1 raw, incomplete         | Decision tree      |  8 |   0.347
S1 raw, incomplete         | Gradient boosting  |  8 |   0.493
S2 raw, complete           | Linear regression  |  9 |   0.898
S2 raw, complete           | Decision tree      |  9 |   0.819
S2 raw, complete           | Gradient boosting  |  9 |   0.927
S3 engineered              | Linear regression  | 11 |   0.946
S3 engineered              | Decision tree      | 11 |   0.917
S3 engineered              | Gradient boosting  | 11 |   0.929
S4 engineered, denoised    | Linear regression  |  5 |   0.947
S4 engineered, denoised    | Decision tree      |  5 |   0.916
S4 engineered, denoised    | Gradient boosting  |  5 |   0.929

What the four feature sets contain

SetContentpWhat it represents
S1area_sqm, year_built, 6 noise variables8A determining variable is missing from the file
S2S1 plus local_price_sqm9Every raw variable of the mechanism is present
S3S2 plus theoretical_value = area × local price, plus building_age11The mechanism is made explicit through two constructed variables
S4S3 with the six noise variables removed5The mechanism is explicit and the file carries nothing else

Reading the results

The three lines are, from the topmost at S4 downward: linear regression, then gradient boosting, then the decision tree. The important feature of the chart is not the ranking of the lines but their slope: all three rise steeply from S1 to S3 and then flatten. The horizontal axis, which carries the information supplied, moves performance far more than the vertical spread between models does.

ComparisonDifference in R²Reading
Best model on S1 against worst model on S4+0.373 in favor of S4The weakest algorithm, correctly informed, crushes the strongest algorithm deprived of a determining variable
Change of algorithm at constant S2 features (linear → boosting)+0.029The gain available from swapping algorithms
Enrichment of the features at constant linear algorithm (S2 → S3)+0.048The gain available from constructing two variables
Linear model on S3 against gradient boosting on S2+0.019 in favor of the linear modelThe simplest model, correctly informed, beats the most powerful model that is poorly informed
Removal of the six noise variables (S3 → S4)+0.001 to −0.001Marginal here, because n = 600 is comfortable; the effect grows as n shrinks
Spread across models within S20.108Vertical amplitude, the algorithm lever
Spread across feature sets for the linear model0.404Horizontal amplitude, the information lever

The last two lines are the quantitative heart of the section. On this problem the information lever is roughly four times the algorithm lever.

Why the mechanism produces this result

Interpretation. The generating mechanism is multiplicative. A linear model cannot represent a product of two variables: it is structurally incapable of it for as long as that product is not handed to it. As soon as theoretical_value is constructed, the problem becomes linear again and the simplest model reaches the best performance in the whole table. Gradient boosting, which approximates the product by a sum of piecewise-constant trees, gets part of the way there — at a higher computational cost and with less interpretability.

A second reading, less often stated. Between S1 and S2 the ranking of the models reverses: on S1 the linear model leads (0.543 against 0.493), on S2 gradient boosting leads (0.927 against 0.898). A benchmark conducted on an incomplete feature set can therefore select the wrong algorithm. Comparing models before the features are settled is not merely inefficient; it is unreliable.

Scope of the demonstration and its limits. The result is built on simulated data whose mechanism is known. It illustrates a principle; it is not a generalizable measurement. On real data the gap depends on the problem, and there are documented cases where the change of algorithm dominates — notably when the raw variables already expose the mechanism in a form the hypothesis class can represent, or when the dataset is so large that a flexible model recovers the interaction on its own. The guiding principle nevertheless holds.

Any algorithm whatsoever can exploit only the information contained in the variables it is given. No algorithmic sophistication compensates for absent information.

MISTAKE — "A sufficiently powerful model will find the interaction on its own"

Partly true, and operationally misleading. A flexible model — gradient boosting, a random forest, a neural network — can approximate an interaction between variables, but it does so by consuming data and capacity. It needs enough observations to discover a structure that a single column would have stated outright, and the approximation stays piecewise where the true relation is smooth.

On the run above, gradient boosting on S2 reaches R² = 0.927 where a linear model on S3 reaches 0.946 with eleven columns and no tuning. The flexible model paid in data and in compute for something that one multiplication supplied for free.

Correct formulation : "A flexible model can approximate an interaction that is not supplied to it, at a cost in observations, in compute and in interpretability; supplying the interaction directly is cheaper and more reliable whenever the mechanism is known."

6.7 The hierarchy of improvement levers

Improving a model is not a menu of independent options. The levers are ordered, and working them out of order wastes budget.

#LeverTypical effectCostWhen it applies
1Correct the definition of the targetDecisiveLow, but requires business agreementWhenever the target was fixed without discussion
2Eliminate leakage and unavailable variablesDecisive for validityLowAlways, before any measurement is trusted
3Acquire a new and relevant data sourceOften highHighWhen a determining variable is simply missing
4Construct derived variables matched to the mechanismOften highModerateWhen the mechanism is understood but not expressed
5Increase the number of observationsVariable, with diminishing returnsModerate to highWhen the learning curve has not yet flattened
6Change algorithmModerateLowOnce the features are settled
7Tune hyperparametersLow to moderateModerateLast, on the retained algorithm

The two levers in the upper-left quadrant — a correctly defined target and the removal of leakage — are cheap and decisive, and they are the two most often skipped. The lever practitioners reach for first, changing the algorithm, sits in the low-effect band.

Point of caution on the ordering. Levers 1 and 2 are not optimizations. They are conditions of validity. A model whose target is badly defined or whose inputs leak does not have a performance number that means anything; tuning it is tuning a measurement instrument that is not connected to the quantity being measured.


7. Three annotated case studies

Each case presents an extract of the raw file, the decisions made on every column, and the specific trap of the domain. The three domains were chosen because the trap differs in each: a consequence column in telecom, a statistic computed too early in real estate, a group structure in industry.

7.1 Telecom churn

client_idagetenure_monthsplan_typemonthly_billsupport_callssatisfactionchurn_datechurn_reasonchurned
C-00001348Mobile29.90040
C-000026745Fiber64.90320
C-00003292Mobile19.9012025-01-14Price1
C-000045261Fiber+TV89.90050
C-000054117Fiber49.90712024-11-22Service1
ElementDetermination
Target variablechurned, binary, cancellation observed within the 90 days following the observation date
Problem typeBinary classification
Explanatory variables retainedage, tenure_months, plan_type, monthly_bill, support_calls, satisfaction
Columns excluded as identifiersclient_id
Columns excluded for leakagechurn_date and churn_reason: both are populated only when the cancellation took place. Their mere presence determines the target
Dimension after encodingp = 8: five numeric variables and three indicators for plan_type
Windowing cautionsupport_calls must be computed over a window capped at the observation date. A count over the customer's whole lifetime includes calls made afterwards, the cancellation call among them

Detecting the leak from the completeness rate

The column churn_reason is empty for every customer who did not cancel. A column whose completeness rate coincides exactly with the positive rate of the target is a leaking variable until proven otherwise. The check costs three lines and catches a large share of leakage through a variable.

python
import numpy as np
import pandas as pd

rng = np.random.default_rng(96)
df = pd.read_csv("telecom_churn.csv")
n = len(df)

# Two columns present in the operational export, populated only for leavers
df["churn_reason"] = np.where(df["churned"] == 1,
                              rng.choice(["Price", "Service", "Competitor"], n), None)
df["churn_date"] = np.where(df["churned"] == 1, "2025-01-14", None)

print("Positive rate of the target :", round(df["churned"].mean(), 4))
print()
print("Completeness rate per column")
print(df.notna().mean().round(4).to_string())
Positive rate of the target : 0.1848

Completeness rate per column
client_id        1.0000
age              1.0000
tenure_months    1.0000
plan_type        1.0000
contract         1.0000
monthly_bill     1.0000
support_calls    1.0000
satisfaction     1.0000
churned          1.0000
churn_reason     0.1848
churn_date       0.1848

Interpretation. Two columns have a completeness rate of 0.1848, equal to the positive rate of the target to four decimal places. That coincidence is not a coincidence: the presence of a value in those columns is the target. No statistical test is needed; the missingness pattern alone convicts them.

The cost of keeping the leak

python
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import roc_auc_score

df["has_churn_reason"] = df["churn_reason"].notna().astype(int)

base = ["age", "tenure_months", "monthly_bill", "support_calls", "satisfaction"]
cat = pd.get_dummies(df[["plan_type", "contract"]]).astype(float)

X_clean = pd.concat([df[base], cat], axis=1)
X_leaky = X_clean.copy()
X_leaky["has_churn_reason"] = df["has_churn_reason"]
y = df["churned"]

for name, X in [("Without the leaking column", X_clean),
                ("With has_churn_reason", X_leaky)]:
    X_tr, X_te, y_tr, y_te = train_test_split(
        X, y, test_size=0.3, random_state=0, stratify=y)
    model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
    model.fit(X_tr, y_tr)
    auc = roc_auc_score(y_te, model.predict_proba(X_te)[:, 1])
    print(f"{name:28s} | p = {X.shape[1]:2d} | test AUC = {auc:.4f}")
Without the leaking column   | p = 11 | test AUC = 0.7179
With has_churn_reason        | p = 12 | test AUC = 1.0000

Interpretation. Adding a single leaking indicator takes the AUC from 0.7179, a plausible figure for a churn problem, to 1.0000, a perfect score. Nothing in the run signals a problem: no error, no warning, no unstable behavior. The model is simply reading the answer. In production the column has_churn_reason is empty for every customer who has not yet left — which is every customer the model is asked about — so the model would score them all as non-churners and deliver an AUC near 0.5.

The warning sign to internalize. A perfect or near-perfect score on a problem the business regards as hard is a leakage alert, not a success. The correct reflex is to look for the leaking column before writing the report. Chapter 028 gives the full detection protocol and chapter 092 runs it as a lab.

7.2 Real estate price estimation

listing_idcity_districtarea_sqmroomsyear_builtenergy_ratingelevatordays_on_marketviewingssale_price
A-10471Lyon 3rd6831972D14712331,000
A-10472Villeurbanne4222015B12219218,500
A-10473Lyon 6th10551930E01188712,000
A-10474Bron7741988D06311249,000
A-10475Lyon 3rd3112019A11524189,900
ElementDetermination
Target variablesale_price, continuous numeric, strictly positive
Problem typeRegression
Explanatory variables retainedcity_district, area_sqm, rooms, year_built, energy_rating, elevator
Columns excluded as identifierslisting_id
Columns excluded for unavailabilitydays_on_market and viewings: these values are known only after the sale. The intended use is estimation at the moment of listing, an instant at which they are zero or undefined
Variables to constructbuilding_age = sale_year − year_built; median_price_sqm_district computed on the training set only; area_per_room
Dimension after encodingDepends on the cardinality of city_district; indicator encoding over 60 districts pushes p past 65

Note on energy_rating. The ratings A to G are ordered. Indicator encoding discards that order and spends six dimensions; ordinal encoding preserves it and spends one. The choice is treated in chapter 022; the point here is that the decision belongs to the feature definition stage, not to the modeling stage.

The trap: a statistic computed too early

median_price_sqm_district is simultaneously the strongest performance lever in the problem and a vector of leakage. Computed over the whole dataset, it incorporates the sale prices of the test set into the training inputs. It must be estimated exclusively on the training set, then applied to the other sets, which requires embedding it in a pipeline (chapters 079 and 092) rather than computing it upstream in a notebook cell.

The order of the arrows is the entire content of the diagram. Computing the medians before the split — that is, moving step 4 above step 1 — inflates the measured performance and produces a model that disappoints in production without anyone being able to say why.

Note on temporal dependence. The general level of prices drifts. If the intended use is to estimate future transactions, the split must be chronological (chapter 027) and drift monitoring must be in place (chapter 082). A random split on a market that has risen 15 percent over the period lets the model see the future price level, which is a second, subtler form of leakage.

Note on the ambiguity of rooms. The number of rooms and the floor area are strongly correlated. Keeping both is legitimate for a tree-based model and problematic for a linear model whose coefficients then become unstable and uninterpretable. That is multicollinearity, treated in chapter 017. It affects the reading of the model, not its admissibility as a feature.

7.3 Predictive maintenance on industrial equipment

sensor_idmachine_idtimestamptemperature_cvibration_rmspressure_baroperating_hoursdays_since_servicefault_code_diagfailure_within_7d
S-0001M-142025-03-02 06:0062.41.824.1018,420340
S-0002M-142025-03-02 07:0071.93.474.0818,42134E-2071
S-0003M-222025-03-02 06:0058.11.443.956,210120
S-0004M-222025-03-02 07:0058.61.513.966,211120
S-0005M-072025-03-02 06:0079.24.914.4241,003961
ElementDetermination
Target variablefailure_within_7d, binary, occurrence of an unplanned stoppage within seven days
Problem typeBinary classification with a heavily imbalanced target
What one observation representsAn hourly reading for one machine, not a machine. The same machine occupies thousands of rows
Explanatory variables retainedtemperature_c, vibration_rms, pressure_bar, operating_hours, days_since_service, plus temporal aggregates to be constructed
Columns excluded as identifierssensor_id; machine_id is retained as a grouping key, not as an explanatory variable
Columns excluded for leakagefault_code_diag: this code is emitted by the diagnosis performed at the moment of the failure. Its presence mechanically determines the target
Variables to constructMeans, standard deviations and slopes of vibration_rms over rolling windows of 6, 24 and 72 hours; deviation from the per-machine reference value

The trap: the group structure of the observations

A single machine generates thousands of rows that share its signature: its baseline vibration level, its temperature range, its installation era. A random split would place readings from the same machine, and often from the same hour, in both training and test. The model would memorize the machine's signature rather than the degradation mechanism, and the measured performance would be substantially overstated. The split must be conducted by group of machines and must respect chronology (chapter 027).

The trap: window centering

Every rolling window must lie strictly before the observation's timestamp. A window centered on the current instant incorporates future measurements and produces a leak that will only show itself in production.

In pandas, the difference is one argument. rolling(window="24h") on a chronologically sorted, time-indexed frame is trailing and safe; rolling(window="24h", center=True) is centered and leaks. The second call raises no warning.

Note on imbalance. Unplanned failures are rare. A target with a positive rate of one or two percent changes the choice of metric, the reading of the confusion matrix and possibly the sampling strategy. That subject occupies chapters 050 and 051.

7.4 What the three cases have in common

DomainMost frequent leakMost critical availability questionStructural trap
Telecom churnColumns populated only for leaversSupport-contact aggregates, over a capped windowWindowing of lifetime counters
Real estatePrice statistics computed over the whole datasetVariables describing how the sale unfoldedChronological drift of the price level
Industrial maintenanceDiagnostic codes posterior to the failureAggregates over strictly trailing windowsRepeated entities, one machine over thousands of rows

Three different domains, three different traps, one identical discipline: for every column, name the instant at which its value becomes known and compare it with the instant at which the prediction must be produced.

The diagram makes one point that a list of criteria cannot: admission is not permanent. A variable admitted at design time returns to review when its distribution or its definition shifts, which is the link between this chapter and the monitoring covered in chapter 082.


8. Reference sheet

8.1 Formulas and notation

FEATURE VECTOR
    x = (x1, x2, …, xp)ᵀ ∈ ℝ^p
    p = number of components actually submitted to the model, after preparation

DESIGN MATRIX AND TARGET VECTOR
    X ∈ ℝ^(n×p)        row i = xiᵀ, column j = values of variable j
    y ∈ 𝒴^n            𝒴 = ℝ in regression, 𝒴 = {c1, …, ck} in classification

THE MODEL AS A FUNCTION
    f : 𝒳 → 𝒴          defined over the WHOLE space, observed regions included or not
    ŷ = f(x)           the prediction for one observation
    objective          minimize E[ℓ(Y, f(X))] over the distribution, not over the sample

THE ADMISSIBILITY CONDITION
    t_obs ≤ t_pred     for EVERY observation, without exception
    t_obs              instant at which the value of the variable becomes known
    t_pred             instant at which the prediction must be produced

8.2 Reading the dimensions

SymbolObjectTypical shape in codeFrequent error
nNumber of observationsX.shape[0]Confusing it with the number of entities when rows repeat per entity
pNumber of explanatory variablesX.shape[1]Reading it off the source file before encoding
XDesign matrix(n, p)Leaving the target or an identifier inside
yTarget vector(n,)Passing (n, 1), which triggers a DataConversionWarning
x_iOne feature vector(p,)Passing it to predict without reshaping to (1, p)
ŷPredictions(n,) or (n, k)Confusing predict output with predict_proba output

8.3 Conditions of use, and of non-use

Use the framework of this chapter whenDo not rely on it alone when
The problem is supervised and a target is observedNo target is observed: the problem is unsupervised (chapter 003)
Each observation can be described by a fixed-length vectorThe observation is a sequence, a graph or an image of variable size, where the vector is built by a learned representation
The prediction instant is identifiable and stableThe decision is sequential and the model's own action changes the state, which is reinforcement learning
The goal is predictionThe goal is a causal effect estimate: the admission criteria change entirely (chapter 016)
Availability at tpredt_{\mathrm{pred}} can be established from the business processThe process is undocumented: establish it before modeling, not after

8.4 The scikit-learn call, with its important arguments

python
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split

df = pd.read_csv("telecom_churn.csv")

TARGET = "churned"
IDENTIFIERS = ["client_id"]
LEAKING = []                      # populate after the audit of section 6

X = df.drop(columns=[TARGET] + IDENTIFIERS + LEAKING)
y = df[TARGET]

numeric = X.select_dtypes(include="number").columns.tolist()
categorical = [c for c in X.columns if c not in numeric]

preprocess = ColumnTransformer(
    transformers=[
        ("num", StandardScaler(), numeric),
        ("cat", OneHotEncoder(handle_unknown="ignore", drop=None), categorical),
    ],
    remainder="drop",             # anything not listed is discarded, not passed through
    verbose_feature_names_out=False,
)

pipe = Pipeline([
    ("prep", preprocess),
    ("model", LogisticRegression(max_iter=1000)),
])

X_tr, X_te, y_tr, y_te = train_test_split(
    X, y, test_size=0.3, random_state=0, stratify=y)

pipe.fit(X_tr, y_tr)
print("p after preparation :", pipe[:-1].transform(X_tr).shape[1])
print("feature names       :", list(pipe[:-1].get_feature_names_out())[:6], "…")
p after preparation : 11
feature names       : ['age', 'tenure_months', 'monthly_bill', 'support_calls', 'satisfaction', 'plan_type_Fiber'] …
ArgumentDefaultWhy it matters here
ColumnTransformer(remainder=...)"drop"The default silently discards unlisted columns. A variable forgotten from both lists disappears without any message
OneHotEncoder(handle_unknown=...)"error"With the default, a category seen only in production raises at predict time. "ignore" encodes it as all zeros
OneHotEncoder(drop=...)NoneKeeping all levels is right for tree models and for regularized models; drop="first" avoids the dummy trap in unregularized linear models (chapter 017)
verbose_feature_names_outTrueThe default prefixes every name with its transformer block (num__age). Setting False keeps names readable in importance tables
train_test_split(stratify=...)NoneWithout it, the class proportion drifts between the two sets on an imbalanced target
Pipeline versus manual preparationOnly the pipeline guarantees that every statistic is fitted on the training data alone. This is the structural defense against leakage (chapters 079 and 092)

8.5 The eight-question grid, in one block

BEFORE ANY STATISTICAL MEASUREMENT, FOR EVERY CANDIDATE COLUMN
    1. Populated at t_pred, for the whole target population?      no → exclude
    2. Value final at that instant, or revised later?             no → exclude or window
    3. Value a consequence of the event to be predicted?          yes → exclude, leakage
    4. Does an aggregate spill past t_pred?                       yes → recompute, capped window
    5. Plausible business mechanism linking it to the target?     no  → detailed review
    6. Definition and distribution stable over time?              no  → reinforced monitoring
    7. Use lawful given purpose and regulation?                   no  → exclude
    8. Acquisition cost in production acceptable?                 no  → trade-off

9. Common reasoning mistakes

MISTAKE — Treating every available column as an explanatory variable

The presence of a column in a historical file establishes neither its availability at prediction time nor its legitimacy. Identifiers, consequence variables and variables consolidated late must be set aside before any modeling.

The file is an artifact of how the history was assembled. It records what is known today about events that took place in the past, not what was known at the instant each decision had to be made. Those two states of knowledge differ, and nothing in the file marks the difference.

Correct formulation : "A column becomes an explanatory variable after satisfying four criteria: availability at the prediction instant, absence of leakage, business plausibility and lawfulness."

MISTAKE — Reading "independent variable" as a requirement of mutual independence

The qualifier comes from the experimental setting, where the variable is set by the experimenter independently of the apparatus. It prescribes no statistical independence among the input variables, which are generally correlated with one another.

The confusion has a practical cost: practitioners who believe the requirement exists start removing correlated features from tree-based models, where collinearity is harmless to predictive performance, while failing to address it where it actually bites, namely the interpretation of coefficients in an unregularized linear model.

Correct formulation : "The term independent is an inheritance from the design of experiments; correlation among explanatory variables is a distinct phenomenon, multicollinearity, treated in chapter 017."

MISTAKE — Confusing label and target

Label designates a categorical value assigned to an observation. A continuous numeric target is a target without being a label. Speaking of the "label" of a regression problem is a loose usage that signals incomplete command of the vocabulary.

Correct formulation : "The target is a label in classification and a numeric value in regression; target covers both cases, label only the first."

MISTAKE — Assuming the role of a variable is intrinsic

No quantity is explanatory or target by nature. A transaction amount is the target in an average-basket forecasting project and an explanatory variable in a fraud detection project.

The corollary matters more than the statement: a variable that was legitimately explanatory in a previous project is not thereby legitimate in the current one. Its admissibility must be re-established against the new prediction instant.

Correct formulation : "The role of a variable is assigned by the question asked, not by the variable itself."

MISTAKE — Believing that adding variables mechanically improves the model

Adding uninformative variables raises the dimension of the feature space, increases the variance of the estimate, encourages overfitting and burdens the production chain. The relation between the number of variables and generalization performance is not monotone.

Correct formulation : "Relevant information improves the model; the number of columns, on its own, does not."

MISTAKE — Deducing the feature space from the number of columns in the file

Encoding categorical variables, constructing derived variables and selecting among them all change the dimension p. Seven source columns can produce eleven dimensions, as in section 5.3, or several hundred with high-cardinality variables.

Correct formulation : "p denotes the number of components of the vector actually submitted to the model, after preparation."

MISTAKE — Looking for performance in the choice of algorithm before examining the variables

The order of the levers is established: definition of the target, elimination of leakage, enrichment of the information, and only then the choice of algorithm and the tuning of hyperparameters. Reversing that order spends a large budget for a marginal gain.

Section 6.6 adds a second reason, independent of efficiency: the ranking of algorithms is not stable across feature sets. On the run in that section the linear model beat gradient boosting on the incomplete set and lost to it on the complete set. A benchmark run too early selects the wrong model.

Correct formulation : "Before changing model, verify that the information required for the prediction is actually present in the inputs."

MISTAKE — Treating ground truth as exact by definition

Labeling is produced by a fallible protocol. Disagreement between annotators, mistaken diagnoses and undetected frauds introduce noise into the target that caps attainable performance.

The practical consequence is a diagnostic order. When a model plateaus below the level the business expects, audit the labeling before enlarging the hypothesis class. A model cannot learn a distinction its labels do not encode.

Correct formulation : "Ground truth is a reference measurement, not the truth; the quality of the labeling sets the ceiling on the model's performance."

MISTAKE — Reading a perfect score as a success

An AUC of 1.000, an R² of 0.999 or an accuracy of 100 percent on a problem the business considers difficult is a symptom, not an achievement. Section 7.1 produces exactly that figure by adding a single leaking indicator to a model that otherwise scores 0.7179.

The asymmetry is what makes leakage dangerous: an error in the code produces a crash, which is investigated, while leakage produces an excellent result, which is celebrated and shipped.

Correct formulation : "Performance clearly above the business expectation is a leakage alert; the leaking column must be identified before any result is reported."


10. Summary

THE MENTAL FORMULA
    FEATURES  →  MODEL  →  TARGET
    what is known        the learned      what is sought
    at instant t_pred    function         and unknown at t_pred

EXPLANATORY VARIABLE — SYNONYMS AND ORIGINS
    feature, characteristic       pattern recognition
    explanatory variable          applied statistics
    independent variable          design of experiments (Fisher, 1935)
    input variable, input         control theory, systems theory
    predictor                     regression statistics
    regressor                     econometrics
    covariate                     biostatistics, clinical trials
    attribute                     data mining, relational databases (Quinlan, 1986)
    descriptor                    chemometrics
    exogenous variable            structural econometrics

TARGET VARIABLE — SYNONYMS AND ORIGINS
    target, target variable       machine learning
    dependent variable            experimental statistics
    response variable             design of experiments
    explained variable            statistics
    endogenous variable           econometrics
    output                        control theory
    label, class                  classification only
    ground truth                  remote sensing, then computer vision
    gold standard                 biostatistics, medical diagnosis
    criterion variable            psychometrics

DEPENDENT / INDEPENDENT TERMINOLOGY
    Inherited from the design of experiments, ill-suited to observational ML.
    "Independent" does not mean independent of the other variables.
    "Dependent" does not mean causally determined.
    The role is functional and reverses from one project to the next.

FORMALIZATION
    x = (x1, …, xp)ᵀ ∈ ℝ^p        feature vector
    X ∈ ℝ^(n×p)                   design matrix
    y ∈ 𝒴^n                       target vector
    f : 𝒳 → 𝒴                     the model, defined over the WHOLE space
    ŷ = f(x)                      the prediction
    p ≠ number of columns in the source file

THE FOUR FILTERS, IN THIS ORDER
    1. Availability at the prediction instant       otherwise exclusion
    2. Absence of leakage                           otherwise exclusion
    3. Business plausibility                        otherwise detailed review
    4. Lawfulness and ethics                        otherwise exclusion
    Statistical selection intervenes only afterwards.

THE FIRST CRITERION
    t_obs ≤ t_pred, for all observations, without exception.
    Three forms of unavailability: temporal, latency, scope.

THE HIERARCHY OF LEVERS
    well-defined target > absence of leakage > new information
    > constructed variables > volume > algorithm > hyperparameters

THE MEASURED EVIDENCE (section 6.6, R² on the test set)
    decision tree on S4, the best features        0.916
    gradient boosting on S1, the worst features   0.493
    algorithm lever, features held fixed at S2    0.108 of spread
    information lever, linear model held fixed    0.404 of spread

Summary statement

The explanatory variables constitute the entirety of the information the model holds and the target variable is the quantity it must estimate; their names vary with the discipline of origin without the notion changing, and the statistical terminology of dependence and independence is an experimental inheritance ill-suited to the observational setting of machine learning. An observation is represented as a vector of Rp\mathbb{R}^p and the model as a function defined over that space, including the regions it never observed. A column becomes an explanatory variable only after satisfying four criteria, the first of which is its effective availability at the instant the prediction will have to be produced; and the quality of that information determines attainable performance more than the choice of algorithm does.


Associated quizzes

  • 006.1-quiz-features-target-relation.md
  • 006.2-quiz-explanatory-variable.md
  • 006.3-quiz-target-variable.md
  • 006.4-quiz-dependent-independent.md
  • 006.5-quiz-feature-vector-and-space.md
  • 006.6-quiz-admission-criteria.md
  • 006.7-quiz-case-studies.md

Next chapter : 007.0-x-y-labels-classes.md