Update app.py
Browse files
app.py
CHANGED
|
@@ -21,19 +21,19 @@ MODEL_PATH = "loan_stacking_model.pkl"
|
|
| 21 |
DATA_PATH = "loan_dataset.csv"
|
| 22 |
|
| 23 |
# =====================================================================
|
| 24 |
-
#
|
| 25 |
# =====================================================================
|
| 26 |
-
|
| 27 |
-
print(
|
| 28 |
|
| 29 |
if not os.path.exists(DATA_PATH):
|
| 30 |
-
raise FileNotFoundError(f"Missing '{DATA_PATH}'. Please ensure your dataset is in the same directory.")
|
| 31 |
|
| 32 |
df = pd.read_csv(DATA_PATH)
|
| 33 |
X = df.drop('BAD', axis=1)
|
| 34 |
y = df['BAD']
|
| 35 |
|
| 36 |
-
#
|
| 37 |
num_cols = X.select_dtypes(include=['int64', 'float64']).columns.tolist()
|
| 38 |
cat_cols = X.select_dtypes(include=['object', 'string']).columns.tolist()
|
| 39 |
|
|
@@ -53,7 +53,7 @@ if not os.path.exists(MODEL_PATH):
|
|
| 53 |
|
| 54 |
X_cleaned = cap_outliers_iqr(X, num_cols)
|
| 55 |
|
| 56 |
-
# Fast
|
| 57 |
num_pipeline = Pipeline([
|
| 58 |
('imputer', KNNImputer(n_neighbors=5)),
|
| 59 |
('scaler', StandardScaler())
|
|
@@ -69,32 +69,44 @@ if not os.path.exists(MODEL_PATH):
|
|
| 69 |
('cat', cat_pipeline, cat_cols)
|
| 70 |
])
|
| 71 |
|
| 72 |
-
# Optimized
|
| 73 |
rf_base = RandomForestClassifier(n_estimators=50, max_depth=8, random_state=42, n_jobs=-1)
|
| 74 |
xgb_base = XGBClassifier(n_estimators=50, learning_rate=0.1, max_depth=4, eval_metric='logloss', random_state=42, n_jobs=-1)
|
| 75 |
voting_base = VotingClassifier(estimators=[('rf_v', rf_base), ('xgb_v', xgb_base)], voting='soft')
|
| 76 |
|
| 77 |
-
# Meta Stacking
|
| 78 |
stacking_ensemble = StackingClassifier(
|
| 79 |
estimators=[('rf', rf_base), ('xgb', xgb_base), ('voting', voting_base)],
|
| 80 |
final_estimator=LogisticRegression(max_iter=500, C=0.1),
|
| 81 |
-
cv=2, #
|
| 82 |
n_jobs=-1
|
| 83 |
)
|
| 84 |
|
| 85 |
-
|
| 86 |
('preprocessing', preprocessor),
|
| 87 |
('smote', SMOTE(random_state=42, sampling_strategy=0.6)),
|
| 88 |
('ensemble_model', stacking_ensemble)
|
| 89 |
])
|
| 90 |
|
| 91 |
-
|
| 92 |
-
joblib.dump(
|
| 93 |
-
print("Model Stacking Pipeline Cached Successfully!")
|
|
|
|
| 94 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
else:
|
| 96 |
-
|
| 97 |
-
production_pipeline = joblib.load(MODEL_PATH)
|
| 98 |
|
| 99 |
|
| 100 |
# =====================================================================
|
|
@@ -123,12 +135,12 @@ def evaluate_loan_risk(loan, mortdue, value, reason, job, yoj, derog, delinq, cl
|
|
| 123 |
bg_gradient = "linear-gradient(135deg, #3b1111 0%, #1a0505 100%)"
|
| 124 |
accent_color = "#f87171"
|
| 125 |
status_text = "❌ RISK ASSESSMENT: APPLICATION REJECTED"
|
| 126 |
-
description = "The calculated default risk probability exceeds
|
| 127 |
else:
|
| 128 |
bg_gradient = "linear-gradient(135deg, #062411 0%, #021207 100%)"
|
| 129 |
accent_color = "#4ade80"
|
| 130 |
status_text = "✅ RISK ASSESSMENT: APPLICATION APPROVED"
|
| 131 |
-
description = "This financial profile displays
|
| 132 |
|
| 133 |
metrics_html = f"""
|
| 134 |
<div style="background: {bg_gradient}; color: #ffffff; padding: 24px; border-radius: 12px; border: 1px solid #334155; box-shadow: 0 4px 10px rgba(0,0,0,0.45);">
|
|
@@ -204,7 +216,6 @@ with io.Blocks() as app:
|
|
| 204 |
ninq = io.Number(label="Recent Bureau Inquiries [NINQ]", value=1)
|
| 205 |
clno = io.Number(label="Total Active Credit Lines [CLNO]", value=20)
|
| 206 |
|
| 207 |
-
# Replaced io.Spacer() with direct margin styling configuration inside button
|
| 208 |
submit_btn = io.Button("⚡ Run Stacking Underwriting Evaluation", variant="primary")
|
| 209 |
|
| 210 |
# Output Feed Hub Panel (Right Side)
|
|
@@ -227,5 +238,4 @@ with io.Blocks() as app:
|
|
| 227 |
)
|
| 228 |
|
| 229 |
if __name__ == "__main__":
|
| 230 |
-
# Correctly passes title and css keywords inside the .launch constructor to support Gradio 6.0+
|
| 231 |
app.launch(css=custom_css, title="AI Loan Underwriting Portal", share=True)
|
|
|
|
| 21 |
DATA_PATH = "loan_dataset.csv"
|
| 22 |
|
| 23 |
# =====================================================================
|
| 24 |
+
# HIGH-SPEED CORE TRAINING FUNCTION
|
| 25 |
# =====================================================================
|
| 26 |
+
def train_and_cache_pipeline():
|
| 27 |
+
print("Initializing ultra-fast pipeline training framework using current local environment...")
|
| 28 |
|
| 29 |
if not os.path.exists(DATA_PATH):
|
| 30 |
+
raise FileNotFoundError(f"Missing '{DATA_PATH}'. Please ensure your dataset is placed in the same repository directory.")
|
| 31 |
|
| 32 |
df = pd.read_csv(DATA_PATH)
|
| 33 |
X = df.drop('BAD', axis=1)
|
| 34 |
y = df['BAD']
|
| 35 |
|
| 36 |
+
# Explicit layout matching to prevent Pandas deprecation warnings
|
| 37 |
num_cols = X.select_dtypes(include=['int64', 'float64']).columns.tolist()
|
| 38 |
cat_cols = X.select_dtypes(include=['object', 'string']).columns.tolist()
|
| 39 |
|
|
|
|
| 53 |
|
| 54 |
X_cleaned = cap_outliers_iqr(X, num_cols)
|
| 55 |
|
| 56 |
+
# Fast Feature Transformation Pipelines
|
| 57 |
num_pipeline = Pipeline([
|
| 58 |
('imputer', KNNImputer(n_neighbors=5)),
|
| 59 |
('scaler', StandardScaler())
|
|
|
|
| 69 |
('cat', cat_pipeline, cat_cols)
|
| 70 |
])
|
| 71 |
|
| 72 |
+
# Optimized hyper-parameters for near-instant execution
|
| 73 |
rf_base = RandomForestClassifier(n_estimators=50, max_depth=8, random_state=42, n_jobs=-1)
|
| 74 |
xgb_base = XGBClassifier(n_estimators=50, learning_rate=0.1, max_depth=4, eval_metric='logloss', random_state=42, n_jobs=-1)
|
| 75 |
voting_base = VotingClassifier(estimators=[('rf_v', rf_base), ('xgb_v', xgb_base)], voting='soft')
|
| 76 |
|
| 77 |
+
# Meta Stacking Level Layout
|
| 78 |
stacking_ensemble = StackingClassifier(
|
| 79 |
estimators=[('rf', rf_base), ('xgb', xgb_base), ('voting', voting_base)],
|
| 80 |
final_estimator=LogisticRegression(max_iter=500, C=0.1),
|
| 81 |
+
cv=2, # Streamlines cross-validation execution speed down to seconds
|
| 82 |
n_jobs=-1
|
| 83 |
)
|
| 84 |
|
| 85 |
+
pipeline = ImbPipeline([
|
| 86 |
('preprocessing', preprocessor),
|
| 87 |
('smote', SMOTE(random_state=42, sampling_strategy=0.6)),
|
| 88 |
('ensemble_model', stacking_ensemble)
|
| 89 |
])
|
| 90 |
|
| 91 |
+
pipeline.fit(X_cleaned, y)
|
| 92 |
+
joblib.dump(pipeline, MODEL_PATH)
|
| 93 |
+
print("Model Stacking Pipeline Compiled and Cached Successfully!")
|
| 94 |
+
return pipeline
|
| 95 |
|
| 96 |
+
# =====================================================================
|
| 97 |
+
# FAULT-TOLERANT SNAPSHOT INITIALIZATION (Fixes the Unpickling Error)
|
| 98 |
+
# =====================================================================
|
| 99 |
+
if os.path.exists(MODEL_PATH):
|
| 100 |
+
try:
|
| 101 |
+
print("Pre-trained file located. Loading parameters...")
|
| 102 |
+
production_pipeline = joblib.load(MODEL_PATH)
|
| 103 |
+
print("Pipeline imported successfully!")
|
| 104 |
+
except Exception as error_context:
|
| 105 |
+
print(f"Version warning/mismatch detected during unpickling: {error_context}")
|
| 106 |
+
print("Bypassing incompatible snapshot file to initiate seamless automated fresh compile...")
|
| 107 |
+
production_pipeline = train_and_cache_pipeline()
|
| 108 |
else:
|
| 109 |
+
production_pipeline = train_and_cache_pipeline()
|
|
|
|
| 110 |
|
| 111 |
|
| 112 |
# =====================================================================
|
|
|
|
| 135 |
bg_gradient = "linear-gradient(135deg, #3b1111 0%, #1a0505 100%)"
|
| 136 |
accent_color = "#f87171"
|
| 137 |
status_text = "❌ RISK ASSESSMENT: APPLICATION REJECTED"
|
| 138 |
+
description = "The calculated default risk probability exceeds security margins. Financial variables present elevated interaction risk patterns."
|
| 139 |
else:
|
| 140 |
bg_gradient = "linear-gradient(135deg, #062411 0%, #021207 100%)"
|
| 141 |
accent_color = "#4ade80"
|
| 142 |
status_text = "✅ RISK ASSESSMENT: APPLICATION APPROVED"
|
| 143 |
+
description = "This financial profile displays proper asset coverage stability, balanced leverage indexes, and strong structural repayment probabilities."
|
| 144 |
|
| 145 |
metrics_html = f"""
|
| 146 |
<div style="background: {bg_gradient}; color: #ffffff; padding: 24px; border-radius: 12px; border: 1px solid #334155; box-shadow: 0 4px 10px rgba(0,0,0,0.45);">
|
|
|
|
| 216 |
ninq = io.Number(label="Recent Bureau Inquiries [NINQ]", value=1)
|
| 217 |
clno = io.Number(label="Total Active Credit Lines [CLNO]", value=20)
|
| 218 |
|
|
|
|
| 219 |
submit_btn = io.Button("⚡ Run Stacking Underwriting Evaluation", variant="primary")
|
| 220 |
|
| 221 |
# Output Feed Hub Panel (Right Side)
|
|
|
|
| 238 |
)
|
| 239 |
|
| 240 |
if __name__ == "__main__":
|
|
|
|
| 241 |
app.launch(css=custom_css, title="AI Loan Underwriting Portal", share=True)
|