Skip to content
v0.1.3latest release121 skills4 categories6 sub-categories247 tested scripts397 reference docsContact us

Pipeline Leakage Patterns: Before and After

Reference for target-leakage-detector · 133 lines

AI & Machine Learning / Classical Machine Learningv1.0.0Updated OCT 25 20264 references2 scripts

LK001 preprocessing before the split

python
# BEFORE
X = StandardScaler().fit_transform(X)
X_train, X_test, y_train, y_test = train_test_split(X, y)

# AFTER
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=0)
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000))
pipe.fit(X_train, y_train)

LK002 resampling before the split

python
# BEFORE: synthetic neighbours of test rows are in training
X_res, y_res = SMOTE().fit_resample(X, y)
cross_val_score(model, X_res, y_res, cv=5)

# AFTER
from imblearn.pipeline import Pipeline
pipe = Pipeline([("smote", SMOTE(random_state=0)), ("model", model)])
cross_val_score(pipe, X, y, cv=StratifiedKFold(5, shuffle=True, random_state=0), scoring="average_precision")

Samplers in an imblearn Pipeline run only during fit, never on validation folds.

LK003 feature selection before CV

python
# BEFORE
X_sel = SelectKBest(f_classif, k=20).fit_transform(X, y)
cross_val_score(model, X_sel, y)

# AFTER
cross_val_score(make_pipeline(SelectKBest(f_classif, k=20), model), X, y)

LK004 target in X

python
# BEFORE
y = df["churned"]
X = df.drop(columns=["customer_id"])

# AFTER
TARGET = "churned"
y = df[TARGET]
X = df.drop(columns=[TARGET, "customer_id", *KNOWN_LEAKS])
assert TARGET not in X.columns

LK005 fitting on test data

python
# BEFORE
scaler.fit(X_test)              # or fit_transform(X_test)
# AFTER
X_test_t = scaler.transform(X_test)

LK006 in-sample target statistics

python
# BEFORE
df["plan_rate"] = df.groupby("plan")["churned"].transform("mean")

# AFTER (i.i.d. rows): cross-fitted encoding inside the pipeline
ColumnTransformer([("te", TargetEncoder(smooth="auto"), ["plan"])], remainder="passthrough")

# AFTER (temporal rows): expanding mean of past labels only
df = df.sort_values("ts")
g = df.groupby("plan")["churned"]
df["plan_rate_prior"] = (g.cumsum() - df["churned"]) / g.cumcount().replace(0, np.nan)

LK007 shuffled splits on temporal data

python
# BEFORE
train_test_split(X, y, test_size=0.2)                       # shuffles by default
# AFTER
df = df.sort_values("score_date")
cut = df["score_date"].quantile(0.8)
train, test = df[df.score_date <= cut], df[df.score_date > cut]
# or for CV: TimeSeriesSplit(n_splits=5, gap=label_window_in_rows)

When labels look ahead (30-day churn window), leave a gap of at least the label window between the last training snapshot and the first test snapshot.

LK008 global statistics before the split

python
# BEFORE
df["income"] = df["income"].fillna(df["income"].median())
df["z"] = (df["x"] - df["x"].mean()) / df["x"].std()
# AFTER: SimpleImputer(strategy="median") and StandardScaler inside the Pipeline

LK009 early stopping on the test set

python
# BEFORE
model.fit(X_train, y_train, eval_set=[(X_test, y_test)])
print(score(model, X_test, y_test))          # test used twice

# AFTER
X_tr, X_val, y_tr, y_val = train_test_split(X_train, y_train, test_size=0.15, stratify=y_train, random_state=0)
model.fit(X_tr, y_tr, eval_set=[(X_val, y_val)])
print(score(model, X_test, y_test))          # test used once

LK010 CV of a bare estimator after preprocessing

python
# BEFORE
X_prep = prep.fit_transform(X)
cross_val_score(LogisticRegression(), X_prep, y)
# AFTER
cross_val_score(make_pipeline(prep, LogisticRegression()), X, y)

Hyperparameter search and the final score

python
outer = StratifiedKFold(5, shuffle=True, random_state=1)
inner = StratifiedKFold(5, shuffle=True, random_state=2)
search = GridSearchCV(pipe, grid, cv=inner, scoring="average_precision")
nested = cross_val_score(search, X, y, cv=outer, scoring="average_precision")   # honest
More in Classical Machine Learning

anomaly-detection-model-builder

Build and evaluate anomaly detection for tabular, sensor and transaction data with few or no labels: define the anomaly type (point, contextual, collective), choose detectors (robust z-score/MAD and IQR rules, Mahalanobis with robust covariance, k-NN distance, LOF, Isolation Forest, one-class SVM, PCA reconstruction / autoencoders, forecasting residuals for time series), combine them by rank, explain each alert by its deviating features, set thresholds from an alert budget or the score distribution, and evaluate with precision@k, PR-AUC and recall on known incidents, or detector agreement when no labels exist. Includes pure-Python detectors (robust z, Mahalanobis, kNN, Isolation Forest, ensemble) and an evaluation script.

catboost-model-builder

Build CatBoost models that use its strengths correctly: raw categorical columns as cat_features (ordered target statistics, no manual encoding), text_features, Pool construction with NaN-safe categories, ordered boosting and has_time for temporal data, symmetric (oblivious) trees, overfitting detector with eval_set and use_best_model, losses for classification, regression (Quantile, Poisson, Tweedie) and ranking (YetiRank), class weights, monotone constraints, feature importance (PredictionValuesChange, LossFunctionChange) and SHAP values, GPU training and model export. Plans cat/text/numeric columns from a CSV and generates a runnable training script, and checks parameter sets for the conflicts CatBoost rejects (iterations vs n_estimators, Bayesian bootstrap with subsample, multiple class-weight options, depth > 16, use_best_model without eval_set).

categorical-encoding-selector

Choose and implement the right encoding for every categorical column given the model family and the data: one-hot (with infrequent-level grouping and handle_unknown), ordinal with an explicit order, cross-fitted target encoding (scikit-learn TargetEncoder, CatBoost ordered statistics, category_encoders inside CV), frequency/count encoding, feature hashing, native categorical support in LightGBM, HistGradientBoosting, XGBoost and CatBoost, prefix levels for codes (zip3, NAICS-2), and embeddings. Measures cardinality, rare-level share, unseen-level rate on a time-ordered holdout and target signal per column, emits the ColumnTransformer, and quantifies target-encoding leakage (in-sample vs out-of-fold vs holdout AUC).

classification-model-selector

Choose the right classification algorithm for tabular, text or mixed data and prove the choice with a fair bake-off: logistic regression (L2, L1, elastic net), linear SVM, naive Bayes, k-NN, RBF SVM, decision trees, random forest, extra trees, HistGradientBoosting, LightGBM, XGBoost, CatBoost, explainable boosting machines (EBM/GAM), points scorecards and MLPs, matched to data size, width, categorical and high-cardinality share, missingness, class imbalance, text, and constraints such as interpretability, monotonic constraints, calibrated probabilities, latency budgets and tiny deployable models. Ranks candidates with starting hyperparameters and cautions, then generates a bake-off script running every candidate on identical CV folds with per-fold metrics, fit time and prediction latency.

clustering-algorithm-selector

Choose the right clustering algorithm and check that clustering makes sense at all: cluster tendency (Hopkins statistic with a correlated-features caveat, nearest-neighbour isolation), then k-means / MiniBatchKMeans, Gaussian mixtures with BIC, agglomerative (Ward, average, complete, single) with dendrograms, DBSCAN, HDBSCAN, OPTICS, spectral clustering, BIRCH, mean shift, k-prototypes and k-modes for mixed or categorical data, and Gower distance, matched to data size, expected shapes, noise, varying density, known k, soft memberships, hierarchy and streaming. Covers preprocessing (scaling, encoding, dimensionality, distance metrics), validation (internal indices, bootstrap stability, external labels, business profiling) and assigning new points.

collaborative-filtering-implementer

Implement collaborative filtering recommenders that beat popularity: item-based kNN with cosine, Jaccard or asymmetric similarity, shrinkage, neighbourhood size, positive-only or mean-centred rating signals and 'because you liked X' explanations; implicit ALS with confidence weighting, BPR pairwise ranking and the closed-form EASE model in plain NumPy, tuned on a temporal validation split by recall@k and NDCG@k and refit on all data; plus user-kNN, explicit matrix factorisation, the implicit/LightFM libraries, hyperparameter ranges, cold-start fallbacks, scaling with sparse matrices and approximate nearest neighbours. Produces top-k lists in the format of the recommendation evaluator.