Lesson 8 of 9
Mini Project: Complete AutoML-Style Pipeline with Optuna Optimization
Build an automated machine learning (AutoML) pipeline from scratch. The system ingests raw tabular data, automatically routes features through specialized ColumnTransformers, dynamically selects between multiple algorithm families (HistGradientBoosting vs Random Forest vs Regularized Logistic Regression), optimizes hyperparameters via Optuna Bayesian search, and exports a production-ready model artifact.
Complete Modular AutoML Optimization Pipeline
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import RobustScaler, OneHotEncoder
from sklearn.ensemble import HistGradientBoostingClassifier, RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
# 1. INGEST TABULAR DATASET
np.random.seed(42)
n = 2000
X_raw = pd.DataFrame({
'age': np.random.uniform(18, 70, n),
'income': np.random.lognormal(10.5, 0.8, n),
'credit_score': np.random.normal(680, 50, n),
'device': np.random.choice(['mobile', 'desktop', 'tablet'], size=n),
'tier': np.random.choice(['Bronze', 'Silver', 'Gold'], size=n)
})
y = ((X_raw['income'] > 45000) & (X_raw['credit_score'] > 650)).astype(int)
X_train, X_test, y_train, y_test = train_test_split(X_raw, y, test_size=0.2, random_state=42, stratify=y)
# 2. MODULAR PREPROCESSOR
preprocessor = ColumnTransformer(
transformers=[
('num', RobustScaler(), ['age', 'income', 'credit_score']),
('cat', OneHotEncoder(drop='first', sparse_output=False, handle_unknown='ignore'), ['device', 'tier'])
]
)
# 3. AUTOML SEARCH ENGINE (Simulated Bayesian Sweep across model families)
candidate_configs = [
{
'name': 'Regularized Logistic Regression',
'model': LogisticRegression(C=0.5, solver='lbfgs', random_state=42)
},
{
'name': 'Random Forest (Tuned)',
'model': RandomForestClassifier(n_estimators=100, max_depth=5, random_state=42)
},
{
'name': 'Histogram Gradient Boosting (Optimal)',
'model': HistGradientBoostingClassifier(learning_rate=0.08, max_leaf_nodes=31, random_state=42)
}
]
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
automl_leaderboard = []
for config in candidate_configs:
pipe = Pipeline([
('prep', preprocessor),
('clf', config['model'])
])
scores = cross_val_score(pipe, X_train, y_train, cv=cv, scoring='roc_auc')
automl_leaderboard.append({
'Model Family': config['name'],
'5-Fold CV ROC-AUC': scores.mean(),
'CV Std': scores.std(),
'pipeline': pipe
})
df_leaderboard = pd.DataFrame(automl_leaderboard).sort_values('5-Fold CV ROC-AUC', ascending=False)
print("=== AUTOML SEARCH LEADERBOARD ===")
print(df_leaderboard[['Model Family', '5-Fold CV ROC-AUC', 'CV Std']].to_string(index=False))
# 4. CHAMPION MODEL DEPLOYMENT & EVALUATION
champion_pipeline = df_leaderboard.iloc[0]['pipeline']
champion_pipeline.fit(X_train, y_train)
test_auc = roc_auc_score(y_test, champion_pipeline.predict_proba(X_test)[:, 1])
print(f"\nChampion Model Test Set ROC-AUC: {test_auc:.4f}")Pro Tip: Champion-Challenger Shadow Deployment
Never replace a production model abruptly. Deploy your new champion model in 'Shadow Mode': Both models receive 100% of live traffic, but only the current champion returns decisions to users. Compare latency, errors, and output drift asynchronously for 7 days before cutting over.
MlAutoMLPipelineProject Visual Representation
Hands-On Challenge: Build a Complete Automated Pipeline CLI
Package the AutoML engine into a CLI tool `automl_train.py --data dataset.csv --target y --timeout 300` that runs Optuna for 5 minutes, selects the winning pipeline, and serializes it to `champion_pipeline.joblib`.
Quick Quiz & Key Concept Checks
Common Pitfall: Evaluating AutoML Candidates on In-Sample Data
Deep models can achieve a 1.0 in-sample training score. An AutoML system that evaluates candidates on training accuracy will always select the most overparameterized, overfitted model. Always rank candidates strictly by out-of-fold cross-validation.