TExcelTAD
Home › Data Preparation Toolkit: Cleaning to Leakage-Free Splits › Introduction: From Checked Data to Model-Ready Data

Introduction: From Checked Data to Model-Ready Data

Data for ML ended with a quality report: you know what your data looks like, where it came from, and which problems it has (missing values, duplicates, outliers, inconsistent units, imbalanced classes). This course is the next step: the technical toolkit that turns that checked raw data into inputs a model can learn from, without fooling yourself about how good the model is.

That second half matters as much as the first. Almost every preparation step learns something from the data: a median to fill gaps, a mean and standard deviation to scale, the categories to encode, the features worth keeping. If any of those are learned from data the model will later be tested on, the test is no longer a test. The thread through the whole course is therefore one rule:

Split first. Fit every preparation step on the training data only. Apply the fitted steps, unchanged, to validation, test and production data.

scikit-learn's Pipeline and ColumnTransformer make this rule automatic, so you will meet them in almost every lesson, and they get a lesson of their own in Pipelines, ColumnTransformer and FunctionTransformer.

Where preparation sits

Raw datachecked, plusquality report Cleaningfixed rules+ cleaning log Split Training partfit imputers, scalers, ... Validation / testtransform only, never fit Modeltrain, thenevaluate fitted steps everything right of "Split" lives inside one scikit-learn Pipeline

Cleaning (fixing types, units, spellings, impossible values, broken files) uses rules written in advance that do not learn from the data, so it can run before the split. Everything that learns is fitted after it, on the training part.

The ten techniques

The course follows the ten common data-preparation techniques, one section each, and then applies them per data type:

# Technique What it does Lessons
1 Data cleaning duplicates, types, dates and units, ranges, category names, broken files, a cleaning log Data Cleaning
2 Missing values the eight methods, from deleting to iterative imputation; never "fill with zero" by default Missing Values
3 Scaling and transforms eight scalers and transforms, and which models need them Scaling
4 Categorical encoding eight encoders, from one-hot to target encoding and learned embeddings Encoding
5 Feature engineering ratios, interactions, date parts, lags, group aggregates, domain, text and media features Feature Engineering
6 Feature selection filters, wrappers and embedded methods Feature Selection
7 Data augmentation label-preserving variations of images, audio and text Augmentation
8 Class imbalance resampling, SMOTE, class weights, focal loss, thresholds Imbalance
9 Dimensionality reduction PCA, SVD, LDA, random projection, autoencoders, t-SNE Dimensionality Reduction
10 Splits and leakage eight split strategies, the leakage rules, pipelines Splits and Leakage

The section Preparation by Data Type then walks through tabular, image, text, audio, time-series and video data. The course ends with exercises and a mini project: an end-to-end, leakage-free preprocessing pipeline for a messy table, compared with a naive leaky version.

A first taste: the same steps, two ways

Here is the whole idea in one example. A small table with missing values, a skewed number and a category; we prepare it and score a model in two ways. The leaky way prepares the whole table first and then cross-validates. The honest way puts the same steps in a pipeline, so each cross-validation fold fits them on its own training part.

python · try it yourself
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

rng = np.random.default_rng(0)
n = 120
df = pd.DataFrame(rng.normal(size=(n, 300)), columns=[f"m{i}" for i in range(300)])  # 300 noisy measurements
df["income"] = rng.lognormal(10, 0.7, n)
df["plan"] = rng.choice(["basic", "pro", "team"], n)
df.loc[rng.random(n) < 0.2, "income"] = np.nan
y = rng.integers(0, 2, n)            # the label is pure chance: no feature can predict it
num = [c for c in df.columns if c != "plan"]

def prep():
    return ColumnTransformer([
        ("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), num),
        ("cat", OneHotEncoder(handle_unknown="ignore"), ["plan"]),
    ])

cv = StratifiedKFold(5, shuffle=True, random_state=0)

# Leaky: prepare and select features on ALL rows, then cross-validate only the model.
X_all = SelectKBest(f_classif, k=10).fit_transform(prep().fit_transform(df), y)
leaky = cross_val_score(LogisticRegression(), X_all, y, cv=cv).mean()

# Honest: every step inside the pipeline, refitted in each training fold.
pipe = make_pipeline(prep(), SelectKBest(f_classif, k=10), LogisticRegression())
honest = cross_val_score(pipe, df, y, cv=cv).mean()

print("labels are random, so the true accuracy is about 0.5")
print(f"leaky estimate:  {leaky:.3f}")
print(f"honest estimate: {honest:.3f}")
labels are random, so the true accuracy is about 0.5
leaky estimate:  0.692
honest estimate: 0.542

The labels are coin flips, yet the leaky version reports 0.692 accuracy: by choosing the 10 features most related to the label on all 120 rows, it picked features that happen to fit the validation rows too. The honest pipeline reports 0.542, close to the truth (with 120 rows, a few points either side of 0.5 is normal noise). The code for the steps is the same; only where they are fitted differs. Feature selection is the step where leaking hurts most; leaking a scaler or an imputer usually inflates scores much less, but it is wrong for the same reason. The Leakage Rules has a lab that shows all three cases.

What you need

Every example runs in your browser (NumPy, pandas, scikit-learn, imbalanced-learn, OpenCV, SciPy). A few examples use PyTorch (embeddings, autoencoders); those are recorded: they ran in a CPU-only container and the page shows their saved output. Every dataset is generated in the code or ships with scikit-learn, so nothing is downloaded.

Test yourself

Which preparation steps may run on the whole dataset before the split?

  1. Imputation with the median
  2. Standardisation
  3. Fixed cleaning rules that learn nothing from the data, such as a unit conversion table
  4. Feature selection

In the first example, why does the leaky version score far above 0.5 on random labels?

  1. Logistic regression is too strong
  2. The features were selected using the labels of all rows, including the validation rows
  3. Cross-validation is broken
  4. The data has missing values

What does putting the preparation steps inside a scikit-learn Pipeline guarantee during cross-validation?

  1. Faster training
  2. Each fold fits the steps on its own training part and only transforms its validation part
  3. Better accuracy
  4. No missing values