Update app.py
Browse files
app.py
CHANGED
|
@@ -16,11 +16,11 @@ from imblearn.over_sampling import SMOTE
|
|
| 16 |
from imblearn.pipeline import Pipeline as ImbPipeline
|
| 17 |
|
| 18 |
# =====================================================================
|
| 19 |
-
# 1. CORE PIPELINE TRAINING
|
| 20 |
# =====================================================================
|
| 21 |
print("Initializing and training the Stacking Pipeline...")
|
| 22 |
|
| 23 |
-
# Load
|
| 24 |
df = pd.read_csv('loan_dataset.csv')
|
| 25 |
|
| 26 |
X = df.drop('BAD', axis=1)
|
|
@@ -45,25 +45,23 @@ def cap_outliers_iqr(data, columns):
|
|
| 45 |
|
| 46 |
X_cleaned = cap_outliers_iqr(X, num_cols)
|
| 47 |
|
| 48 |
-
#
|
| 49 |
num_pipeline = Pipeline([
|
| 50 |
('imputer', KNNImputer(n_neighbors=5)),
|
| 51 |
('scaler', StandardScaler())
|
| 52 |
])
|
| 53 |
|
| 54 |
-
# FIX: Categorical Pipeline uses SimpleImputer (most_frequent) instead of KNNImputer
|
| 55 |
cat_pipeline = Pipeline([
|
| 56 |
('imputer', SimpleImputer(strategy='most_frequent')),
|
| 57 |
('encoder', OneHotEncoder(handle_unknown='ignore', sparse_output=False))
|
| 58 |
])
|
| 59 |
|
| 60 |
-
# Combining layout tracks
|
| 61 |
preprocessor = ColumnTransformer([
|
| 62 |
('num', num_pipeline, num_cols),
|
| 63 |
('cat', cat_pipeline, cat_cols)
|
| 64 |
])
|
| 65 |
|
| 66 |
-
#
|
| 67 |
rf_base = RandomForestClassifier(n_estimators=100, max_depth=10, random_state=42, n_jobs=-1)
|
| 68 |
xgb_base = XGBClassifier(n_estimators=100, learning_rate=0.1, max_depth=5, eval_metric='logloss', random_state=42, n_jobs=-1)
|
| 69 |
|
|
@@ -72,24 +70,22 @@ voting_base = VotingClassifier(
|
|
| 72 |
voting='soft'
|
| 73 |
)
|
| 74 |
|
| 75 |
-
#
|
| 76 |
stacking_ensemble = StackingClassifier(
|
| 77 |
estimators=[('rf', rf_base), ('xgb', xgb_base), ('voting', voting_base)],
|
| 78 |
final_estimator=LogisticRegression(max_iter=1000, C=0.1),
|
| 79 |
-
cv=3,
|
| 80 |
n_jobs=-1
|
| 81 |
)
|
| 82 |
|
| 83 |
-
# Master Production Pipeline
|
| 84 |
production_pipeline = ImbPipeline([
|
| 85 |
('preprocessing', preprocessor),
|
| 86 |
('smote', SMOTE(random_state=42, sampling_strategy=0.6)),
|
| 87 |
('ensemble_model', stacking_ensemble)
|
| 88 |
])
|
| 89 |
|
| 90 |
-
# Train model layout
|
| 91 |
production_pipeline.fit(X_cleaned, y)
|
| 92 |
-
print("Model Pipeline Trained Successfully!
|
| 93 |
|
| 94 |
# =====================================================================
|
| 95 |
# 2. GRADIO INFERENCE FUNCTION
|
|
@@ -113,42 +109,99 @@ def evaluate_loan_risk(loan, mortdue, value, reason, job, yoj, derog, delinq, cl
|
|
| 113 |
prediction_proba = production_pipeline.predict_proba(input_data)[0]
|
| 114 |
risk_of_default = prediction_proba[1]
|
| 115 |
|
|
|
|
| 116 |
if risk_of_default > 0.40:
|
| 117 |
-
decision = "❌
|
|
|
|
| 118 |
else:
|
| 119 |
-
decision = "✅
|
|
|
|
| 120 |
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
|
| 128 |
# =====================================================================
|
| 129 |
-
# 3.
|
| 130 |
# =====================================================================
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
io.
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
|
| 153 |
if __name__ == "__main__":
|
| 154 |
-
|
|
|
|
| 16 |
from imblearn.pipeline import Pipeline as ImbPipeline
|
| 17 |
|
| 18 |
# =====================================================================
|
| 19 |
+
# 1. CORE PIPELINE TRAINING (Fast Optimization Layout)
|
| 20 |
# =====================================================================
|
| 21 |
print("Initializing and training the Stacking Pipeline...")
|
| 22 |
|
| 23 |
+
# Load dataset safely
|
| 24 |
df = pd.read_csv('loan_dataset.csv')
|
| 25 |
|
| 26 |
X = df.drop('BAD', axis=1)
|
|
|
|
| 45 |
|
| 46 |
X_cleaned = cap_outliers_iqr(X, num_cols)
|
| 47 |
|
| 48 |
+
# Transformers
|
| 49 |
num_pipeline = Pipeline([
|
| 50 |
('imputer', KNNImputer(n_neighbors=5)),
|
| 51 |
('scaler', StandardScaler())
|
| 52 |
])
|
| 53 |
|
|
|
|
| 54 |
cat_pipeline = Pipeline([
|
| 55 |
('imputer', SimpleImputer(strategy='most_frequent')),
|
| 56 |
('encoder', OneHotEncoder(handle_unknown='ignore', sparse_output=False))
|
| 57 |
])
|
| 58 |
|
|
|
|
| 59 |
preprocessor = ColumnTransformer([
|
| 60 |
('num', num_pipeline, num_cols),
|
| 61 |
('cat', cat_pipeline, cat_cols)
|
| 62 |
])
|
| 63 |
|
| 64 |
+
# Streamlined High-Speed Base Learners
|
| 65 |
rf_base = RandomForestClassifier(n_estimators=100, max_depth=10, random_state=42, n_jobs=-1)
|
| 66 |
xgb_base = XGBClassifier(n_estimators=100, learning_rate=0.1, max_depth=5, eval_metric='logloss', random_state=42, n_jobs=-1)
|
| 67 |
|
|
|
|
| 70 |
voting='soft'
|
| 71 |
)
|
| 72 |
|
| 73 |
+
# Meta-Classifier Network
|
| 74 |
stacking_ensemble = StackingClassifier(
|
| 75 |
estimators=[('rf', rf_base), ('xgb', xgb_base), ('voting', voting_base)],
|
| 76 |
final_estimator=LogisticRegression(max_iter=1000, C=0.1),
|
| 77 |
+
cv=3,
|
| 78 |
n_jobs=-1
|
| 79 |
)
|
| 80 |
|
|
|
|
| 81 |
production_pipeline = ImbPipeline([
|
| 82 |
('preprocessing', preprocessor),
|
| 83 |
('smote', SMOTE(random_state=42, sampling_strategy=0.6)),
|
| 84 |
('ensemble_model', stacking_ensemble)
|
| 85 |
])
|
| 86 |
|
|
|
|
| 87 |
production_pipeline.fit(X_cleaned, y)
|
| 88 |
+
print("Model Pipeline Trained Successfully! Building Custom UI Grid...")
|
| 89 |
|
| 90 |
# =====================================================================
|
| 91 |
# 2. GRADIO INFERENCE FUNCTION
|
|
|
|
| 109 |
prediction_proba = production_pipeline.predict_proba(input_data)[0]
|
| 110 |
risk_of_default = prediction_proba[1]
|
| 111 |
|
| 112 |
+
# Generate clean output cards
|
| 113 |
if risk_of_default > 0.40:
|
| 114 |
+
decision = "❌ RISK ASSESSMENT: LOAN APPLICATION REJECTED"
|
| 115 |
+
explanation = "The risk metrics calculated by the Stacking Ensemble cross-validation profile indicate an elevated default probability threshold. Application does not meet current fiscal safety rules."
|
| 116 |
else:
|
| 117 |
+
decision = "✅ RISK ASSESSMENT: LOAN APPLICATION APPROVED"
|
| 118 |
+
explanation = "The client profile demonstrates an established pattern of capital control, manageable debt-to-income limits, and minimal adverse filings. Proceed with standard capitalization."
|
| 119 |
|
| 120 |
+
metrics_html = f"""
|
| 121 |
+
<div style="background-color: #1a202c; color: #ffffff; padding: 20px; border-radius: 12px; border: 1px solid #2d3748;">
|
| 122 |
+
<h3 style="margin-top: 0; color: #38bdf8; font-size: 1.3rem; font-weight: 700;">{decision}</h3>
|
| 123 |
+
<p style="color: #cbd5e1; font-size: 0.95rem; line-height: 1.5; margin-bottom: 15px;">{explanation}</p>
|
| 124 |
+
<hr style="border-color: #2d3748; margin-bottom: 15px;">
|
| 125 |
+
<div style="display: flex; justify-content: space-between; font-family: monospace; font-size: 1rem;">
|
| 126 |
+
<div><span style="color: #94a3b8;">DEFAULT PROBABILITY:</span> <strong style="color: {'#ef4444' if risk_of_default > 0.40 else '#22c55e'}">{risk_of_default * 100:.2f}%</strong></div>
|
| 127 |
+
<div><span style="color: #94a3b8;">PIPELINE CONFIDENCE:</span> <strong style="color: #38bdf8;">{max(prediction_proba) * 100:.2f}%</strong></div>
|
| 128 |
+
</div>
|
| 129 |
+
</div>
|
| 130 |
+
"""
|
| 131 |
+
return metrics_html
|
| 132 |
|
| 133 |
# =====================================================================
|
| 134 |
+
# 3. ELEGANT GRAPHIC LAYOUT AND STYLING (Gradio Blocks)
|
| 135 |
# =====================================================================
|
| 136 |
+
custom_css = """
|
| 137 |
+
#main_container { background-color: #f8fafc; padding: 20px; font-family: 'Inter', sans-serif; }
|
| 138 |
+
.block_header { text-align: center; margin-bottom: 25px; border-bottom: 2px solid #e2e8f0; padding-bottom: 15px; }
|
| 139 |
+
.section_box { border: 1px solid #e2e8f0; background: #ffffff; padding: 18px; border-radius: 10px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); }
|
| 140 |
+
.section_title { color: #1e293b; font-size: 1.1rem; font-weight: 600; margin-bottom: 12px; display: flex; align-items: center; gap: 8px; }
|
| 141 |
+
"""
|
| 142 |
+
|
| 143 |
+
with io.Blocks(css=custom_css, title="AI Loan Underwriting Portal") as app:
|
| 144 |
+
|
| 145 |
+
with io.Div(elem_id="main_container"):
|
| 146 |
+
# Header Graphic Title
|
| 147 |
+
with io.Div(elem_classes="block_header"):
|
| 148 |
+
io.Markdown("# 🏦 Automated FinTech Loan Underwriting Interface")
|
| 149 |
+
io.Markdown("Production underwriting dashboard fueled by an advanced **92.18% accurate Stacking Ensemble Network**.")
|
| 150 |
+
|
| 151 |
+
# Main Workspace Split
|
| 152 |
+
with io.Row():
|
| 153 |
+
|
| 154 |
+
# Left Panel: User Parameter Inputs grouped cleanly into rows/columns
|
| 155 |
+
with io.Column(scale=2):
|
| 156 |
+
|
| 157 |
+
with io.Group(elem_classes="section_box"):
|
| 158 |
+
io.Markdown("### 📊 Block A: Loan Request & Purpose")
|
| 159 |
+
with io.Row():
|
| 160 |
+
loan = io.Number(label="Loan Amount ($) [LOAN]", value=15000)
|
| 161 |
+
reason = io.Dropdown(choices=["DebtCon", "HomeImp"], label="Purpose [REASON]", value="DebtCon")
|
| 162 |
+
|
| 163 |
+
io.Spacer()
|
| 164 |
+
|
| 165 |
+
with io.Group(elem_classes="section_box"):
|
| 166 |
+
io.Markdown("### 🏠 Block B: Financial Standing & Assets")
|
| 167 |
+
with io.Row():
|
| 168 |
+
mortdue = io.Number(label="Mortgage Owed ($) [MORTDUE]", value=50000)
|
| 169 |
+
value = io.Number(label="Property Asset Value ($) [VALUE]", value=85000)
|
| 170 |
+
with io.Row():
|
| 171 |
+
job = io.Dropdown(choices=["Other", "Mgr", "Office", "ProfExe", "Sales", "Self"], label="Job Category [JOB]", value="Other")
|
| 172 |
+
yoj = io.Number(label="Years at Present Job [YOJ]", value=5)
|
| 173 |
+
|
| 174 |
+
io.Spacer()
|
| 175 |
+
|
| 176 |
+
with io.Group(elem_classes="section_box"):
|
| 177 |
+
io.Markdown("### 💳 Block C: Internal Credit Risk Metrics")
|
| 178 |
+
with io.Row():
|
| 179 |
+
debtinc = io.Number(label="Debt-to-Income Ratio (%) [DEBTINC]", value=32.5)
|
| 180 |
+
clage = io.Number(label="Oldest Credit Account (Months) [CLAGE]", value=180)
|
| 181 |
+
with io.Row():
|
| 182 |
+
delinq = io.Number(label="Delinquent Credit Lines [DELINQ]", value=0)
|
| 183 |
+
derog = io.Number(label="Derogatory Reports [DEROG]", value=0)
|
| 184 |
+
with io.Row():
|
| 185 |
+
ninq = io.Number(label="Recent Credit Inquiries [NINQ]", value=1)
|
| 186 |
+
clno = io.Number(label="Total Existing Credit Lines [CLNO]", value=20)
|
| 187 |
+
|
| 188 |
+
submit_btn = io.Button("⚡ Generate Automated Underwriting Decision", variant="primary")
|
| 189 |
+
|
| 190 |
+
# Right Panel: Results & Analytical Metrics Card
|
| 191 |
+
with io.Column(scale=1):
|
| 192 |
+
with io.Group(elem_classes="section_box"):
|
| 193 |
+
io.Markdown("### 🏁 Underwriting Output Terminal")
|
| 194 |
+
output_html = io.HTML(
|
| 195 |
+
label="Assessment Outcome Dashboard",
|
| 196 |
+
value="<div style='color: #64748b; font-style: italic; text-align: center; padding: 40px 10px;'>Adjust inputs on the left panels and click the generate button to update underwriting logs.</div>"
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
# Wire Button Click trigger link to prediction interface execution logic
|
| 200 |
+
submit_btn.click(
|
| 201 |
+
fn=evaluate_loan_risk,
|
| 202 |
+
inputs=[loan, mortdue, value, reason, job, yoj, derog, delinq, clage, ninq, clno, debtinc],
|
| 203 |
+
outputs=output_html
|
| 204 |
+
)
|
| 205 |
|
| 206 |
if __name__ == "__main__":
|
| 207 |
+
app.launch(share=True)
|