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.
The same structure reads differently depending on the phase. This is the most common source of confusion among beginners.
| Phase | Explanatory variables | Target variable | What is produced |
|---|---|---|---|
| Training | Known, supplied | Known, supplied | The model |
| Validation | Known, supplied | Known but hidden from the model, used for comparison | A performance measurement |
| Production prediction | Known, supplied | Unknown | An estimate ŷ |
| Retrospective monitoring | Known | Observed later, with a delay | A 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.
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.
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.
| Common statement | Status | Justification |
|---|---|---|
| "Every column in the file is a feature" | Incorrect | Identifiers, the target and leaking variables are excluded (chapter 005, section 3.2) |
| "A feature explains the target" | Incorrect in the strict sense | It is associated with the target; causal explanation belongs to a different methodological framework (chapter 016) |
| "A feature must be numeric" | Incorrect | It may be categorical, temporal or textual; numeric encoding is a later step (chapters 022 and 023) |
| "The more features, the better the model" | Incorrect | Past a certain point, adding variables degrades generalization performance (chapters 025 and 031) |
| "A feature is given by the data" | Partly inaccurate | A large share of the most predictive variables are constructed, not recorded (chapter 024) |
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.
| Term | Discipline of origin | Distinctive connotation | Current register |
|---|---|---|---|
| Feature | Pattern recognition and computer vision | A quantity extracted from a raw signal, possibly constructed | Dominant in machine learning |
| Characteristic | Literal rendering of feature | Identical to feature | Common in formal writing; rare in speech |
| Explanatory variable | Applied statistics, modeling | Suggests a contribution to explaining the phenomenon | Academic standard |
| Independent variable | Experimental statistics, design of experiments, experimental psychology (from Fisher, 1935) | Suggests a variable manipulated by the experimenter | Frequent but problematic in ML (section 4) |
| Input variable, input | Control theory, systems theory, engineering | Neutral: what goes into the box | Very common, unambiguous |
| Predictor | Applied statistics, regression literature | Stresses the predictive purpose rather than the explanatory one | Common, particularly well suited to ML |
| Regressor | Econometrics | A term of the regression model, tied to a coefficient | Reserved for parametric linear models |
| Covariate | Biostatistics, epidemiology, clinical trials | A variable whose effect is adjusted for in order to isolate a treatment effect | Standard in clinical research |
| Attribute | Symbolic learning, data mining, relational databases (Quinlan, 1986) | A descriptive property of an entity | Dated in ML, alive in databases |
| Descriptor | Chemometrics, cheminformatics | A computed quantity describing a structure | Specialized |
| Exogenous variable | Structural econometrics | Determined outside the modeled system | Specialized, theoretically loaded |
| Factor | Design of experiments, analysis of variance | A controlled categorical variable | Ambiguous: 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.
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.
Regressor (econometrics)
A variable appearing on the right-hand side of a regression equation, tied to an estimated coefficient. In the model y = β₀ + β₁x₁ + … + + ε, the 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.
The term is used in the literature with two different scopes, and confusing them causes real errors.
| Sense | What it designates | Example |
|---|---|---|
| Broad sense | Any descriptive column of the dataset, whatever its use | signup_date is "a feature of the dataset" |
| Strict sense | Any input actually submitted to the model after preparation | tenure_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.
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.
| Term | Discipline of origin | Particular scope | Register |
|---|---|---|---|
| Target | Machine learning | Neutral, any kind of target | Dominant |
| Target variable | Machine learning | Identical, slightly more formal | Standard |
| Dependent variable | Experimental statistics, experimental psychology | Suggests causal dependence on the manipulated variables | Frequent, problematic in ML (section 4) |
| Response variable | Statistics, design of experiments | What responds to a controlled variation of the inputs | Academic standard |
| Explained variable | Statistics and econometrics | Symmetric counterpart of "explanatory variable" | Common in formal writing |
| Endogenous variable, regressand | Structural econometrics | Determined inside the modeled system | Specialized |
| Output | Control theory, systems theory | Neutral: what comes out of the box | Very common |
| Label | Supervised learning, data annotation | Restricted to categorical targets | Dominant in classification |
| Class | Pattern recognition, classification | One particular level of the label | Dominant in classification |
| Ground truth | Remote sensing, then computer vision | The reference value held to be true, as opposed to the prediction | Standard in annotation |
| Gold standard | Biostatistics, medical diagnosis | The reference procedure used to establish the true value | Standard in medicine |
| Criterion variable | Psychometrics, personnel selection | The outcome the instrument seeks to predict | Specialized |
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 type | Target | May you say "label" |
|---|---|---|
| Binary classification: fraud / normal | Categorical, 2 levels | Yes |
| Multiclass classification: cat / dog / horse | Categorical, k levels | Yes |
| Regression: price in euros | Continuous numeric | No, 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.
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.
| Configuration | Structure of the target | Name | Reference |
|---|---|---|---|
| A single target column, one value per observation | y ∈ ℝ or y ∈ {c₁, …, } | Standard case | Chapter 010 |
| An observation may belong to several classes at once | y ∈ {0,1}^k | Multilabel classification | Chapter 011 |
| Several numeric targets predicted jointly | y ∈ | Multi-output regression | Chapter 048 |
| Categorical target with ordered levels | y ∈ {c₁ < … < } | Ordinal classification | Chapter 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.
No operational system spontaneously produces a column named churned. That
column is the result of a chain of explicit decisions.
| Decision | Effect on the project |
|---|---|
| Definition of the event | Sets the positive rate, hence the degree of imbalance (chapter 050) |
| Time horizon | Sets the difficulty of the problem and the operational usefulness of the prediction |
| Population in scope | Sets the model's domain of validity and the selection biases |
| Observation date | Sets 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.
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.
| Difficulty | What the term suggests | What holds in machine learning |
|---|---|---|
| Statistical independence | That the explanatory variables are independent of one another | They 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 manipulation | That the analyst sets the values of the input variables | They are observed, not manipulated. Nobody "sets" a customer's age or an apartment's floor area |
| Causal dependence | That the target varies because of the input variables | The model captures an association. Causal inference requires a specific framework, not a predictive model (chapter 016) |
| Intrinsic property | That a variable is independent or dependent by nature | The status is a role assigned by the project, and it reverses from one project to the next |
| Logical symmetry | That only one reading is possible | The 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.
The same quantity changes role depending on the question asked. The column does not change; the project does.
| Quantity | Project where it is the target | Project where it is explanatory |
|---|---|---|
| Transaction amount | Average basket forecasting | Payment fraud detection |
| Customer satisfaction score | Predicting post-call satisfaction | Predicting churn |
| Length of hospital stay | Hospital capacity planning | Predicting readmission risk |
| Bearing temperature | Thermal forecasting for equipment | Detecting an imminent failure |
| Salary | Salary estimation at hiring | Credit scoring |
| Situation | Recommended phrasing | Phrasing to avoid |
|---|---|---|
| Technical report | Explanatory variables / target variable | Independent variables / dependent variable |
| Code and technical documentation | features / target, X / y | — |
| Presentation to a business audience | Information supplied / value to predict | Any untranslated statistical term |
| Scientific article in statistics | Predictors / response variable | — |
| Job interview | Explanatory variables, while signaling that you know the synonyms | Using 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.
Rigorous definition
The representation of an observation as an ordered p-tuple of values, one per retained explanatory variable:
where p is the number of explanatory variables and the value taken by the j-th variable for that observation.
Three binding properties
In plain terms
A row of the table, reduced to the useful columns and converted into a sequence of numbers.
Rigorous definition
A matrix X ∈ 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 ∈ , where 𝒴 = ℝ in regression and 𝒴 = {c₁, …, } 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.
| Object | Notation | Dimension | Content |
|---|---|---|---|
| Training set | (X, y) | — | n pairs (observation, target) |
| Matrix of explanatory variables | X | n × p | Numeric values |
| Target vector | y | n | One value per observation |
| Feature vector of one observation | xᵢ | p | Row i of X |
| Value of one variable for one observation | scalar | Cell (i, j) | |
| Vector of one variable across the dataset | X[:, j] | n | Column j of X |
| Prediction for one observation | ŷᵢ | scalar or vector | Output of the model |
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.
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.
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: objectInterpretation. 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).
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: objectThis row is not yet a vector of : two components are text. Encoding the categorical variables produces the numeric representation actually submitted to the model.
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.
municipality variable with 400 levels adds 400 dimensions on
its own under indicator encoding.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).Rigorous definition
The set 𝒳 of all admissible values of the feature vector. In the usual case of p real-valued variables, 𝒳 ⊆ , 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).
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.
| Element | Formalization | Reading |
|---|---|---|
| An observation | x ∈ 𝒳 ⊆ | A point |
| The true target | y ∈ 𝒴 | The true value |
| The model | f : 𝒳 → 𝒴 | 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 objective | minimize 𝔼[ℓ(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).
Having a column does not license using it. Four successive filters apply, in this order, before any consideration of performance.
Rigorous definition
A variable is available at prediction time 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 be the instant at which the prediction must be produced and the instant at which the value of the variable actually becomes known. The variable is admissible if and only if:
≤ , 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 case | Candidate variable | relative to | Verdict |
|---|---|---|---|
| Customer churn within 90 days | Tenure in months | Before | Admissible |
| Customer churn within 90 days | Cancellation date | After, and defined by the event | Excluded, manifest leakage |
| Customer churn within 90 days | Departure reason entered by the advisor | After | Excluded |
| Customer churn within 90 days | Number of support calls over the last 6 months | Before, if the window is capped at | Admissible under strict windowing |
| Credit approval | Income declared at application | Before | Admissible |
| Credit approval | Number of missed payments on the granted loan | After | Excluded |
| Estimating a property sale price | Floor area, year built | Before | Admissible |
| Estimating a property sale price | Days on market | After listing, known only afterwards | Excluded |
| Predictive maintenance within 7 days | Mean vibration over the last 24 hours | Before | Admissible |
| Predictive maintenance within 7 days | Fault code from the failure diagnosis | After | Excluded |
| Medical triage at admission | Vital signs on arrival | Before | Admissible |
| Medical triage at admission | Treatment administered | After, and a consequence of the diagnosis | Excluded |
Three forms of unavailability, two of which are routinely overlooked.
| Form | Description | Illustration |
|---|---|---|
| Temporal unavailability | The value does not yet exist at | Total amount billed over the current year |
| Latency unavailability | The value exists but is consolidated in the systems only after a delay longer than the decision window | An external score refreshed monthly, used in real-time scoring |
| Scope unavailability | The value exists for the historical population but not for the target population | A 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.
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
| Family | Mechanism | Detection |
|---|---|---|
| Leakage through a variable | A column encodes all or part of the target | Abnormally high performance, importance concentrated on one variable |
| Leakage through the protocol | A statistic computed on the whole dataset before splitting contaminates the test set | Small 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 variable | Control question | Example |
|---|---|---|
| Consequence variable | Is the value produced because the event took place? | churn_date, cancellation_reason, amount_refunded |
| Treatment variable | Does the value reflect an action triggered by knowledge of the outcome? | retention_offer_made, case_sent_to_collections |
| Unwindowed aggregate | Does the aggregate cover a period after ? | total_transactions, annual_average |
| Near-perfect proxy | Is the correlation with the target suspiciously trivial? | account_status = "closed" to predict churn |
| Order-bearing identifier | Does the identifier implicitly encode chronology or group? | Sequential numbers assigned in batches, one batch per class |
A variable statistically associated with the target but with no plausible mechanism must be examined before it is retained. Four outcomes are possible.
| Diagnosis | Nature of the link | Course of action |
|---|---|---|
| Identified business mechanism | Well-founded association | Keep |
| Indirect marker of an unobserved cause | Real but fragile association | Keep with reservations, document, monitor stability |
| Spurious correlation specific to the sample | Association with no foundation | Exclude; it will not reproduce |
| Collection artifact | The association comes from how the data were assembled | Exclude 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.
| Category | Status | Specific difficulty |
|---|---|---|
| Directly sensitive variables: ethnic origin, religion, political opinions, health, sexual orientation | Strictly regulated or prohibited depending on jurisdiction and purpose | Easy to identify |
| Indirect variables strongly correlated with a sensitive one | The prohibition is often circumvented unintentionally | Postal code can stand in for origin; a first name for gender |
| Variables collected without a legal basis | Unusable | Provenance must be traceable |
| Variables produced by another model | Usable with care | Cascading 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).
| # | Question | If the answer is unfavorable |
|---|---|---|
| 1 | Will the variable be populated at prediction time, for the whole target population? | Exclusion |
| 2 | Is its value final at that instant, or revised later? | Exclusion, or explicit windowing |
| 3 | Is its value a consequence of the event to be predicted? | Exclusion for leakage |
| 4 | Does an aggregate it contains spill over into the later period? | Recompute with a capped window |
| 5 | Does a plausible business mechanism link this variable to the target? | Detailed review |
| 6 | Are its definition and distribution stable over time? | Reinforced monitoring |
| 7 | Is its use lawful given the purpose and the regulation? | Exclusion |
| 8 | Is 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.
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.
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| Set | Content | p | What it represents |
|---|---|---|---|
| S1 | area_sqm, year_built, 6 noise variables | 8 | A determining variable is missing from the file |
| S2 | S1 plus local_price_sqm | 9 | Every raw variable of the mechanism is present |
| S3 | S2 plus theoretical_value = area × local price, plus building_age | 11 | The mechanism is made explicit through two constructed variables |
| S4 | S3 with the six noise variables removed | 5 | The mechanism is explicit and the file carries nothing else |
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.
| Comparison | Difference in R² | Reading |
|---|---|---|
| Best model on S1 against worst model on S4 | +0.373 in favor of S4 | The weakest algorithm, correctly informed, crushes the strongest algorithm deprived of a determining variable |
| Change of algorithm at constant S2 features (linear → boosting) | +0.029 | The gain available from swapping algorithms |
| Enrichment of the features at constant linear algorithm (S2 → S3) | +0.048 | The gain available from constructing two variables |
| Linear model on S3 against gradient boosting on S2 | +0.019 in favor of the linear model | The 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.001 | Marginal here, because n = 600 is comfortable; the effect grows as n shrinks |
| Spread across models within S2 | 0.108 | Vertical amplitude, the algorithm lever |
| Spread across feature sets for the linear model | 0.404 | Horizontal 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.
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.
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."
Improving a model is not a menu of independent options. The levers are ordered, and working them out of order wastes budget.
| # | Lever | Typical effect | Cost | When it applies |
|---|---|---|---|---|
| 1 | Correct the definition of the target | Decisive | Low, but requires business agreement | Whenever the target was fixed without discussion |
| 2 | Eliminate leakage and unavailable variables | Decisive for validity | Low | Always, before any measurement is trusted |
| 3 | Acquire a new and relevant data source | Often high | High | When a determining variable is simply missing |
| 4 | Construct derived variables matched to the mechanism | Often high | Moderate | When the mechanism is understood but not expressed |
| 5 | Increase the number of observations | Variable, with diminishing returns | Moderate to high | When the learning curve has not yet flattened |
| 6 | Change algorithm | Moderate | Low | Once the features are settled |
| 7 | Tune hyperparameters | Low to moderate | Moderate | Last, 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.
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.
| client_id | age | tenure_months | plan_type | monthly_bill | support_calls | satisfaction | churn_date | churn_reason | churned |
|---|---|---|---|---|---|---|---|---|---|
| C-00001 | 34 | 8 | Mobile | 29.90 | 0 | 4 | — | — | 0 |
| C-00002 | 67 | 45 | Fiber | 64.90 | 3 | 2 | — | — | 0 |
| C-00003 | 29 | 2 | Mobile | 19.90 | 1 | — | 2025-01-14 | Price | 1 |
| C-00004 | 52 | 61 | Fiber+TV | 89.90 | 0 | 5 | — | — | 0 |
| C-00005 | 41 | 17 | Fiber | 49.90 | 7 | 1 | 2024-11-22 | Service | 1 |
| Element | Determination |
|---|---|
| Target variable | churned, binary, cancellation observed within the 90 days following the observation date |
| Problem type | Binary classification |
| Explanatory variables retained | age, tenure_months, plan_type, monthly_bill, support_calls, satisfaction |
| Columns excluded as identifiers | client_id |
| Columns excluded for leakage | churn_date and churn_reason: both are populated only when the cancellation took place. Their mere presence determines the target |
| Dimension after encoding | p = 8: five numeric variables and three indicators for plan_type |
| Windowing caution | support_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 |
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.
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.1848Interpretation. 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.
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.0000Interpretation. 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.
| listing_id | city_district | area_sqm | rooms | year_built | energy_rating | elevator | days_on_market | viewings | sale_price |
|---|---|---|---|---|---|---|---|---|---|
| A-10471 | Lyon 3rd | 68 | 3 | 1972 | D | 1 | 47 | 12 | 331,000 |
| A-10472 | Villeurbanne | 42 | 2 | 2015 | B | 1 | 22 | 19 | 218,500 |
| A-10473 | Lyon 6th | 105 | 5 | 1930 | E | 0 | 118 | 8 | 712,000 |
| A-10474 | Bron | 77 | 4 | 1988 | D | 0 | 63 | 11 | 249,000 |
| A-10475 | Lyon 3rd | 31 | 1 | 2019 | A | 1 | 15 | 24 | 189,900 |
| Element | Determination |
|---|---|
| Target variable | sale_price, continuous numeric, strictly positive |
| Problem type | Regression |
| Explanatory variables retained | city_district, area_sqm, rooms, year_built, energy_rating, elevator |
| Columns excluded as identifiers | listing_id |
| Columns excluded for unavailability | days_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 construct | building_age = sale_year − year_built; median_price_sqm_district computed on the training set only; area_per_room |
| Dimension after encoding | Depends 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.
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.
| sensor_id | machine_id | timestamp | temperature_c | vibration_rms | pressure_bar | operating_hours | days_since_service | fault_code_diag | failure_within_7d |
|---|---|---|---|---|---|---|---|---|---|
| S-0001 | M-14 | 2025-03-02 06:00 | 62.4 | 1.82 | 4.10 | 18,420 | 34 | — | 0 |
| S-0002 | M-14 | 2025-03-02 07:00 | 71.9 | 3.47 | 4.08 | 18,421 | 34 | E-207 | 1 |
| S-0003 | M-22 | 2025-03-02 06:00 | 58.1 | 1.44 | 3.95 | 6,210 | 12 | — | 0 |
| S-0004 | M-22 | 2025-03-02 07:00 | 58.6 | 1.51 | 3.96 | 6,211 | 12 | — | 0 |
| S-0005 | M-07 | 2025-03-02 06:00 | 79.2 | 4.91 | 4.42 | 41,003 | 96 | — | 1 |
| Element | Determination |
|---|---|
| Target variable | failure_within_7d, binary, occurrence of an unplanned stoppage within seven days |
| Problem type | Binary classification with a heavily imbalanced target |
| What one observation represents | An hourly reading for one machine, not a machine. The same machine occupies thousands of rows |
| Explanatory variables retained | temperature_c, vibration_rms, pressure_bar, operating_hours, days_since_service, plus temporal aggregates to be constructed |
| Columns excluded as identifiers | sensor_id; machine_id is retained as a grouping key, not as an explanatory variable |
| Columns excluded for leakage | fault_code_diag: this code is emitted by the diagnosis performed at the moment of the failure. Its presence mechanically determines the target |
| Variables to construct | Means, standard deviations and slopes of vibration_rms over rolling windows of 6, 24 and 72 hours; deviation from the per-machine reference value |
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).
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.
| Domain | Most frequent leak | Most critical availability question | Structural trap |
|---|---|---|---|
| Telecom churn | Columns populated only for leavers | Support-contact aggregates, over a capped window | Windowing of lifetime counters |
| Real estate | Price statistics computed over the whole dataset | Variables describing how the sale unfolded | Chronological drift of the price level |
| Industrial maintenance | Diagnostic codes posterior to the failure | Aggregates over strictly trailing windows | Repeated 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.
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| Symbol | Object | Typical shape in code | Frequent error |
|---|---|---|---|
n | Number of observations | X.shape[0] | Confusing it with the number of entities when rows repeat per entity |
p | Number of explanatory variables | X.shape[1] | Reading it off the source file before encoding |
X | Design matrix | (n, p) | Leaving the target or an identifier inside |
y | Target vector | (n,) | Passing (n, 1), which triggers a DataConversionWarning |
x_i | One feature vector | (p,) | Passing it to predict without reshaping to (1, p) |
ŷ | Predictions | (n,) or (n, k) | Confusing predict output with predict_proba output |
| Use the framework of this chapter when | Do not rely on it alone when |
|---|---|
| The problem is supervised and a target is observed | No target is observed: the problem is unsupervised (chapter 003) |
| Each observation can be described by a fixed-length vector | The 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 stable | The decision is sequential and the model's own action changes the state, which is reinforcement learning |
| The goal is prediction | The goal is a causal effect estimate: the admission criteria change entirely (chapter 016) |
| Availability at can be established from the business process | The process is undocumented: establish it before modeling, not after |
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'] …| Argument | Default | Why 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=...) | None | Keeping 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_out | True | The default prefixes every name with its transformer block (num__age). Setting False keeps names readable in importance tables |
train_test_split(stratify=...) | None | Without it, the class proportion drifts between the two sets on an imbalanced target |
Pipeline versus manual preparation | — | Only the pipeline guarantees that every statistic is fitted on the training data alone. This is the structural defense against leakage (chapters 079 and 092) |
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-offThe 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."
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."
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."
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."
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."
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."
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."
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."
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."
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 spreadSummary 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 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.md006.2-quiz-explanatory-variable.md006.3-quiz-target-variable.md006.4-quiz-dependent-independent.md006.5-quiz-feature-vector-and-space.md006.6-quiz-admission-criteria.md006.7-quiz-case-studies.mdNext chapter : 007.0-x-y-labels-classes.md