Sub topic 2
Different Preprocessing for Different Columns
Assume you know basic Python, pandas, train/test splits, and scikit-learn’s fit and predict methods. This chapter focuses on building one workflow that handles mixed tabular data safely.
Different preprocessing for different columns
A ColumnTransformer applies separate transformations to selected columns. Numeric columns might need missing-value imputation and scaling. Categorical columns might need imputation and one-hot encoding, which converts categories into indicator columns.
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression
X = pd.DataFrame({
"age": [25, 32, None, 47, 51, 38],
"income": [40000, 52000, 61000, None, 88000, 57000],
"city": ["Oslo", "Bergen", None, "Oslo", "Bergen", "Oslo"],
})
y = [0, 0, 1, 1, 1, 0]
numeric = ["age", "income"]
categorical = ["city"]
preprocess = ColumnTransformer([
("num", Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler()),
]), numeric),
("cat", Pipeline([
("impute", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(handle_unknown="ignore")),
]), categorical),
])
model = Pipeline([
("prep", preprocess),
("clf", LogisticRegression(max_iter=1000)),
])
model.fit(X, y)
print(model.predict(X))The outer Pipeline treats preprocessing and classification as one estimator. handle_unknown="ignore" allows prediction on a category that was absent during training.
Cross-validating the whole workflow
Cross-validation divides training data into folds. For each fold, the pipeline fits the imputer, scaler, encoder, and classifier using only that fold’s training portion. It then scores the untouched portion. This prevents validation information from influencing preprocessing statistics.
Use cross_val_score with the complete pipeline:
from sklearn.model_selection import cross_val_score
scores = cross_val_score(model, X, y, cv=5)
print(scores.mean())Tuning hyperparameters across steps
GridSearchCV can tune the pipeline as one estimator. Refer to a parameter with step_name__parameter_name.
from sklearn.model_selection import GridSearchCV
search = GridSearchCV(
model,
{"clf__C": [0.01, 0.1, 1, 10]},
cv=5,
)
search.fit(X, y)
print(search.best_params_)
print(search.best_score_)Each candidate value is evaluated with fresh preprocessing inside every fold. This avoids choosing a model using leaked information.
Exercise
Why should scaling be inside the pipeline rather than applied to the complete dataset before cross-validation?
Show answer
Scaling outside the pipeline lets validation-fold values influence the scaling statistics. Putting it inside the pipeline fits scaling separately on each training fold.