Everything comes together here: a single, leakage-safe workflow from raw mixed-type data to a tuned, evaluated model. This is the shape of real scikit-learn projects.
The complete flow
from sklearn.compose import ColumnTransformerfrom sklearn.pipeline import Pipelinefrom sklearn.preprocessing import StandardScaler, OneHotEncoderfrom sklearn.impute import SimpleImputerfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import train_test_split, GridSearchCVX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,stratify=y, random_state=42)num = Pipeline([("imp", SimpleImputer(strategy="median")), ("sc", StandardScaler())])cat = Pipeline([("imp", SimpleImputer(strategy="most_frequent")),("oh", OneHotEncoder(handle_unknown="ignore"))])pre = ColumnTransformer([("num", num, num_cols), ("cat", cat, cat_cols)])pipe = Pipeline([("pre", pre), ("model", RandomForestClassifier())])grid = GridSearchCV(pipe, {"model__n_estimators": [100, 300]}, cv=5, scoring="f1")grid.fit(X_train, y_train)print(grid.best_params_, grid.score(X_test, y_test))
Key takeaways
- 01A full project is one Pipeline: ColumnTransformer (impute+scale+encode) → model.
- 02Wrap it in GridSearchCV to tune, cross-validated and leakage-free.
- 03Use step__param (double underscore) to tune a parameter inside the pipeline.
- 04The whole thing trains, tunes, evaluates and deploys as a single object.
