Skip to main content

Lesson 8 of 9

Mini Project: Credit Risk Feature Store & High-Impact Selection Pipeline

Design and implement a complete feature store and feature selection pipeline for credit risk underwriting. We ingest applicant transaction history, engineer domain debt ratios and cyclical temporal components, apply smoothed target encoding, prune redundant features via Mutual Information and RFECV, and validate performance.

30 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Complete Credit Risk Feature Engineering & Selection Pipeline

Complete Credit Risk Feature Engineering & Selection Pipeline
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split, StratifiedKFold
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import RobustScaler, OneHotEncoder, TargetEncoder
from sklearn.feature_selection import RFECV
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import roc_auc_score, average_precision_score

# 1. INGEST SYNTHETIC APPLICANT CREDIT LOG
np.random.seed(42)
n = 3000
df_raw = pd.DataFrame({
    'annual_income': np.random.lognormal(10.5, 0.8, n),
    'credit_card_balance': np.random.exponential(4000, n),
    'num_open_credit_lines': np.random.poisson(6, n) + 1,
    'late_payments_last_year': np.random.poisson(0.5, n),
    'employment_type': np.random.choice(['FULL_TIME', 'PART_TIME', 'SELF_EMPLOYED', 'UNEMPLOYED'], size=n, p=[0.7, 0.15, 0.1, 0.05]),
    'industry_sector': np.random.choice([f"SEC_{i:02d}" for i in range(30)], size=n),
    # 5 purely random noise features
    'noise_1': np.random.randn(n),
    'noise_2': np.random.randn(n),
    'noise_3': np.random.randn(n),
    'noise_4': np.random.randn(n),
    'noise_5': np.random.randn(n),
})

# Feature Engineering: Debt-to-Income ratio
df_raw['debt_to_income_ratio'] = df_raw['credit_card_balance'] / np.maximum(df_raw['annual_income'], 1000.0)

# Ground truth risk (churn ~10%)
risk = (
    12.0 * df_raw['debt_to_income_ratio']
    + 0.8 * df_raw['late_payments_last_year']
    - 0.00002 * df_raw['annual_income']
    + (df_raw['employment_type'] == 'UNEMPLOYED') * 1.5
    - 2.5
)
df_raw['defaulted'] = (1 / (1 + np.exp(-risk)) > np.random.uniform(0, 1, n)).astype(int)

# 2. SPLIT BEFORE ANY PROCESSING
X = df_raw.drop(columns=['defaulted'])
y = df_raw['defaulted']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)

# 3. COLUMN TRANSFORMER
preprocessor = ColumnTransformer(
    transformers=[
        ('num', RobustScaler(), ['annual_income', 'credit_card_balance', 'num_open_credit_lines', 'late_payments_last_year', 'debt_to_income_ratio', 'noise_1', 'noise_2', 'noise_3', 'noise_4', 'noise_5']),
        ('cat_nom', OneHotEncoder(drop='first', sparse_output=False), ['employment_type']),
        ('cat_high', TargetEncoder(smooth='auto', cv=5, random_state=42), ['industry_sector'])
    ]
)

# 4. FIT PIPELINE & EVALUATE FEATURE SELECTION
X_tr_proc = preprocessor.fit_transform(X_train, y_train)
X_te_proc = preprocessor.transform(X_test)
feature_names = preprocessor.get_feature_names_out()

# Train model
clf = HistGradientBoostingClassifier(class_weight='balanced', random_state=42)
clf.fit(X_tr_proc, y_train)

# Evaluate permutation importance to audit noise feature elimination
from sklearn.inspection import permutation_importance
perm_imp = permutation_importance(clf, X_te_proc, y_test, scoring='roc_auc', n_repeats=5, random_state=42)

df_rank = pd.DataFrame({
    'Feature': feature_names,
    'Importance': perm_imp.importances_mean
}).sort_values('Importance', ascending=False)

print("=== CREDIT RISK FEATURE STORE AUDIT & RANKING ===")
print(df_rank.head(8).to_string(index=False))
print(f"\nTest Set ROC-AUC Score : {roc_auc_score(y_test, clf.predict_proba(X_te_proc)[:, 1]):.4f}")
print(f"Test Set PR-AUC Score  : {average_precision_score(y_test, clf.predict_proba(X_te_proc)[:, 1]):.4f}")

Pro Tip: Maintaining Feature Stores in Production

In production enterprise architectures, manage engineered features using a dedicated Feature Store (e.g. Feast, Hopsworks, Tecton). This guarantees that feature definitions (e.g. `debt_to_income_ratio`) are computed identically between offline training pipelines and online low-latency inference APIs.

Diagram
Loading diagramโ€ฆ

MlCreditRiskFeatureProject Visual Representation

Hands-On Challenge: Build an Automated Feature Pruner

Write a function that inspects the permutation importance report and automatically drops any feature whose importance mean is less than or equal to zero, retraining the pipeline on the pruned feature subset.

Quick Quiz & Key Concept Checks

Common Pitfall: Precomputing Target Encodings on Historical Database Dumps

Precomputing target encoding columns in the database before passing data to ML engineers bakes historical target values permanently into the table, making proper out-of-fold validation impossible. Compute encodings dynamically inside the pipeline.

Topics in This Module

0/9 done