Sub topic 3
Avoiding Data Leakage in scikit-learn Workflows
Assume you know basic Python, NumPy shapes, pandas DataFrames, and supervised learning. Data leakage occurs when information from evaluation data influences training. It can make a model appear better than it will perform on new data.
Fit preprocessing on training data only
A transformer learns values during fit, then applies them during transform. For example, StandardScaler learns a mean and standard deviation. Fit it on training data, not on the test set. The test set should remain unseen until evaluation.
Chaining steps with `Pipeline`
A Pipeline is an estimator that runs several steps in order. It can fit preprocessing and a model as one object. During cross-validation, scikit-learn refits each step on each training fold.
Mixed columns with `ColumnTransformer`
A ColumnTransformer applies different transformations to selected columns. Numeric columns can be scaled, while categorical columns can be converted to indicator columns by OneHotEncoder.
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
df = pd.DataFrame({
"age": [22, 35, 47, 52, 28, 41, 60, 33, 29, 55, 38, 44],
"city": ["Paris", "Rome", "Paris", "Oslo"] * 3,
"bought": [0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0],
})
X, y = df[["age", "city"]], df["bought"]
preprocess = ColumnTransformer([
("numeric", StandardScaler(), ["age"]),
("categorical", OneHotEncoder(handle_unknown="ignore"), ["city"]),
])
pipe = Pipeline([
("preprocess", preprocess),
("model", LogisticRegression(max_iter=200)),
])
scores = cross_val_score(pipe, X, y, cv=3)
print(scores.mean())cross_val_score evaluates each validation fold after fitting preprocessing only on that fold’s training portion. This prevents leakage.
Inspecting and copying estimators
Constructor settings are hyperparameters. Learned values appear after fit, often in attributes ending with _.
get_params()returns constructor settings.set_params()changes settings.clone()creates an unfitted copy with the same settings.
from sklearn.base import clone
from sklearn.linear_model import LogisticRegression
original = LogisticRegression(C=0.5)
copy = clone(original).set_params(C=2.0)
print(original.C, copy.C)Writing a custom transformer
A custom transformer should keep constructor arguments unchanged, return self from fit, and implement transform.
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
class LogTransformer(BaseEstimator, TransformerMixin):
def __init__(self, offset=1.0):
self.offset = offset
def fit(self, X, y=None):
return self
def transform(self, X):
return np.log(np.asarray(X) + self.offset)Exercise
Why should a scaler be inside a pipeline passed to crossvalscore?
Show answer
The pipeline refits the scaler on each training fold, preventing validation data from influencing preprocessing.