VectorV17 commited on
Commit
e866ebb
·
verified ·
1 Parent(s): d58a370

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -27
app.py CHANGED
@@ -4,7 +4,7 @@ import gradio as io
4
 
5
  from sklearn.model_selection import train_test_split
6
  from sklearn.preprocessing import StandardScaler, OneHotEncoder
7
- from sklearn.impute import KNNImputer
8
  from sklearn.compose import ColumnTransformer
9
  from sklearn.pipeline import Pipeline
10
 
@@ -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 (Runs once when the app starts)
20
  # =====================================================================
21
- print("Initializing and training the 92.18% Accuracy Stacking Pipeline...")
22
 
23
- # Load your repository dataset
24
  df = pd.read_csv('loan_dataset.csv')
25
 
26
  X = df.drop('BAD', axis=1)
@@ -29,7 +29,7 @@ y = df['BAD']
29
  num_cols = X.select_dtypes(include=['int64', 'float64']).columns.tolist()
30
  cat_cols = X.select_dtypes(include=['object']).columns.tolist()
31
 
32
- # Define outlier bounds using IQR method before training to stabilize parameters
33
  def cap_outliers_iqr(data, columns):
34
  data_clean = data.copy()
35
  for col in columns:
@@ -45,47 +45,49 @@ def cap_outliers_iqr(data, columns):
45
 
46
  X_cleaned = cap_outliers_iqr(X, num_cols)
47
 
48
- # Build Transformation Layouts
49
  num_pipeline = Pipeline([
50
  ('imputer', KNNImputer(n_neighbors=5)),
51
- ('scaler', StandardScaler()) # Z-Score Normalization
52
  ])
53
 
 
54
  cat_pipeline = Pipeline([
55
- ('imputer', KNNImputer(n_neighbors=1, weights='uniform')),
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
- # Base Models
65
- rf_base = RandomForestClassifier(n_estimators=150, max_depth=12, random_state=42, n_jobs=-1)
66
- xgb_base = XGBClassifier(n_estimators=200, learning_rate=0.05, max_depth=6, eval_metric='logloss', random_state=42)
67
 
68
  voting_base = VotingClassifier(
69
  estimators=[('rf_v', rf_base), ('xgb_v', xgb_base)],
70
  voting='soft'
71
  )
72
 
73
- # Stacking Configuration using Meta-Heuristic Logistic Regression Meta-Model
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=5,
78
  n_jobs=-1
79
  )
80
 
81
- # Complete Production Pipeline
82
  production_pipeline = ImbPipeline([
83
  ('preprocessing', preprocessor),
84
  ('smote', SMOTE(random_state=42, sampling_strategy=0.6)),
85
  ('ensemble_model', stacking_ensemble)
86
  ])
87
 
88
- # Train model automatically on initialization
89
  production_pipeline.fit(X_cleaned, y)
90
  print("Model Pipeline Trained Successfully! Launching Gradio Web Interface...")
91
 
@@ -93,13 +95,12 @@ print("Model Pipeline Trained Successfully! Launching Gradio Web Interface...")
93
  # 2. GRADIO INFERENCE FUNCTION
94
  # =====================================================================
95
  def evaluate_loan_risk(loan, mortdue, value, reason, job, yoj, derog, delinq, clage, ninq, clno, debtinc):
96
- # Convert user web entries into a structured Pandas DataFrame matching the original dataset layout
97
  input_data = pd.DataFrame([{
98
- 'LOAN': float(loan),
99
  'MORTDUE': float(mortdue) if mortdue is not None else np.nan,
100
  'VALUE': float(value) if value is not None else np.nan,
101
- 'REASON': reason,
102
- 'JOB': job,
103
  'YOJ': float(yoj) if yoj is not None else np.nan,
104
  'DEROG': float(derog) if derog is not None else np.nan,
105
  'DELINQ': float(delinq) if delinq is not None else np.nan,
@@ -109,17 +110,13 @@ def evaluate_loan_risk(loan, mortdue, value, reason, job, yoj, derog, delinq, cl
109
  'DEBTINC': float(debtinc) if debtinc is not None else np.nan
110
  }])
111
 
112
- # Predict probabilities using the trained Stacking Classifier pipeline
113
  prediction_proba = production_pipeline.predict_proba(input_data)[0]
114
- risk_of_default = prediction_proba[1] # Index 1 tracks probability of 'BAD=1' (Defaulter)
115
 
116
- # Set risk safety thresholds
117
  if risk_of_default > 0.40:
118
  decision = "❌ LOAN REJECTED (High Financial Risk Profile)"
119
- color_theme = "Low Approval Odds"
120
  else:
121
  decision = "✅ LOAN APPROVED (Reliable Low-Risk Applicant)"
122
- color_theme = "High Approval Odds"
123
 
124
  metrics_output = (
125
  f"Decision Profile: {decision}\n"
@@ -148,11 +145,10 @@ interface = io.Interface(
148
  io.Number(label="Debt-to-Income Ratio (%) (DEBTINC)", value=32.5)
149
  ],
150
  outputs=io.Textbox(label="Automated Underwriting System Assessment Result", lines=4),
151
- title="🏦 AI-Driven Loan Underwriting & Risk Assessment System",
152
- description="Input customer attributes below. This production underwriting portal uses a custom **92.18% accurate Stacking Ensemble Classifier** wrapped in an automated data preprocessing layout to determine credit risk approval status instantly.",
153
  theme="soft"
154
  )
155
 
156
- # Start execution
157
  if __name__ == "__main__":
158
  interface.launch(share=True)
 
4
 
5
  from sklearn.model_selection import train_test_split
6
  from sklearn.preprocessing import StandardScaler, OneHotEncoder
7
+ from sklearn.impute import KNNImputer, SimpleImputer
8
  from sklearn.compose import ColumnTransformer
9
  from sklearn.pipeline import Pipeline
10
 
 
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 your dataset
24
  df = pd.read_csv('loan_dataset.csv')
25
 
26
  X = df.drop('BAD', axis=1)
 
29
  num_cols = X.select_dtypes(include=['int64', 'float64']).columns.tolist()
30
  cat_cols = X.select_dtypes(include=['object']).columns.tolist()
31
 
32
+ # Fast Outlier Rectification via IQR Capping
33
  def cap_outliers_iqr(data, columns):
34
  data_clean = data.copy()
35
  for col in columns:
 
45
 
46
  X_cleaned = cap_outliers_iqr(X, num_cols)
47
 
48
+ # Numerical Pipeline: Handles missing numeric values with KNN, then scales them
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
+ # Base Estimators (Optimized parameters to execute in less time)
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
 
70
  voting_base = VotingClassifier(
71
  estimators=[('rf_v', rf_base), ('xgb_v', xgb_base)],
72
  voting='soft'
73
  )
74
 
75
+ # Stacking Model Layout
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, # Reduced cross-validation folds from 5 to 3 for significantly faster training speed
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! Launching Gradio Web Interface...")
93
 
 
95
  # 2. GRADIO INFERENCE FUNCTION
96
  # =====================================================================
97
  def evaluate_loan_risk(loan, mortdue, value, reason, job, yoj, derog, delinq, clage, ninq, clno, debtinc):
 
98
  input_data = pd.DataFrame([{
99
+ 'LOAN': float(loan) if loan is not None else 0.0,
100
  'MORTDUE': float(mortdue) if mortdue is not None else np.nan,
101
  'VALUE': float(value) if value is not None else np.nan,
102
+ 'REASON': reason if reason else 'DebtCon',
103
+ 'JOB': job if job else 'Other',
104
  'YOJ': float(yoj) if yoj is not None else np.nan,
105
  'DEROG': float(derog) if derog is not None else np.nan,
106
  'DELINQ': float(delinq) if delinq is not None else np.nan,
 
110
  'DEBTINC': float(debtinc) if debtinc is not None else np.nan
111
  }])
112
 
 
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 = "❌ LOAN REJECTED (High Financial Risk Profile)"
 
118
  else:
119
  decision = "✅ LOAN APPROVED (Reliable Low-Risk Applicant)"
 
120
 
121
  metrics_output = (
122
  f"Decision Profile: {decision}\n"
 
145
  io.Number(label="Debt-to-Income Ratio (%) (DEBTINC)", value=32.5)
146
  ],
147
  outputs=io.Textbox(label="Automated Underwriting System Assessment Result", lines=4),
148
+ title="🏦 AI-Driven Loan Underwriting System",
149
+ description="Portal uses a custom Stacking Ensemble Classifier wrapped in an automated data preprocessing layout.",
150
  theme="soft"
151
  )
152
 
 
153
  if __name__ == "__main__":
154
  interface.launch(share=True)