Lesson 8 of 9
Mini Project: Production Preprocessing Pipeline for Credit Scoring
Design and implement an enterprise-grade, end-to-end data preprocessing and classification pipeline for credit risk scoring. We handle heterogeneous loan applicant data: imputing missing values, robust scaling of financial amounts, cross-validated target encoding of merchant codes, one-hot encoding of loan purpose, and cost-sensitive classification.
The Complete Credit Risk Preprocessing 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.impute import SimpleImputer
from sklearn.preprocessing import RobustScaler, OneHotEncoder, TargetEncoder
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import classification_report, roc_auc_score
# 1. INGEST SYNTHETIC CREDIT RISK DATASET
np.random.seed(42)
n_apps = 3000
df_credit = pd.DataFrame({
'annual_income': np.random.lognormal(10.8, 0.8, size=n_apps),
'revolving_debt': np.random.exponential(scale=5000, size=n_apps),
'delinquencies_2yr': np.random.poisson(lam=0.4, size=n_apps),
'home_ownership': np.random.choice(['RENT', 'MORTGAGE', 'OWN', 'OTHER'], size=n_apps, p=[0.45, 0.45, 0.08, 0.02]),
'loan_purpose': np.random.choice(['debt_consolidation', 'credit_card', 'small_business', 'home_improvement'], size=n_apps),
'employer_industry': np.random.choice([f"IND_{i:02d}" for i in range(25)], size=n_apps)
})
# Ground truth default target (imbalanced ~8% default rate)
logit = (
- 0.000015 * df_credit['annual_income']
+ 0.00012 * df_credit['revolving_debt']
+ 0.8 * df_credit['delinquencies_2yr']
- 1.5
)
df_credit['defaulted'] = (1 / (1 + np.exp(-logit)) > np.random.uniform(0, 1, size=n_apps)).astype(int)
# 2. SPLIT STRICTLY BEFORE PREPROCESSING
X = df_credit.drop(columns=['defaulted'])
y = df_credit['defaulted']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
# 3. CONSTRUCT COLUMN-TRANSFORMER
preprocessor = ColumnTransformer(
transformers=[
('num', Pipeline([
('imputer', SimpleImputer(strategy='median')),
('scaler', RobustScaler())
]), ['annual_income', 'revolving_debt', 'delinquencies_2yr']),
('cat_nom', Pipeline([
('imputer', SimpleImputer(strategy='constant', fill_value='MISSING')),
('ohe', OneHotEncoder(drop='first', sparse_output=False, handle_unknown='ignore'))
]), ['home_ownership', 'loan_purpose']),
('cat_high', Pipeline([
('target_enc', TargetEncoder(smooth='auto', cv=5, random_state=42))
]), ['employer_industry'])
],
remainder='drop'
)
# 4. ASSEMBLE COMPLETE ATOMIC PRODUCTION PIPELINE
credit_pipeline = Pipeline([
('preprocessor', preprocessor),
('classifier', HistGradientBoostingClassifier(class_weight='balanced', random_state=42))
])
# 5. CROSS-VALIDATION EVALUATION
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
cv_scores = cross_val_score(credit_pipeline, X_train, y_train, cv=cv, scoring='roc_auc')
print(f"5-Fold CV ROC-AUC: {cv_scores.mean():.4f} (± {cv_scores.std():.4f})")
# 6. FINAL TRAINING & EVALUATION ON HELD-OUT TEST DATA
credit_pipeline.fit(X_train, y_train)
y_probs = credit_pipeline.predict_proba(X_test)[:, 1]
test_auc = roc_auc_score(y_test, y_probs)
print(f"\nHeld-Out Test ROC-AUC : {test_auc:.4f}")
print("\nTest Classification Report (Threshold = 0.5):")
print(classification_report(y_test, credit_pipeline.predict(X_test), digits=4))Pro Tip: Export Preprocessor Feature Metadata
Always export the feature names generated by `preprocessor.get_feature_names_out()` alongside your serialized pipeline. This makes it trivial to interpret feature importances and audit prediction explainability dashboards.
MlPreprocessingPipelineProject Visual Representation
Hands-On Challenge: Build a Multi-Threshold Router
Implement an inference router that accepts loan application JSON payloads: applications with default probability < 0.15 are automatically approved; probabilities > 0.65 are automatically rejected; intermediate probabilities are routed to manual underwriting.
Quick Quiz & Key Concept Checks
Common Pitfall: Serializing Only the Model Without the Preprocessor
If you serialize only the classifier object (`joblib.dump(credit_pipeline.named_steps['classifier'])`), your production REST API will expect a pre-transformed numpy array and will fail on incoming raw JSON payloads. Always serialize the top-level `credit_pipeline` object.