Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -200,11 +200,126 @@ with tab2:
|
|
| 200 |
st.divider()
|
| 201 |
st.subheader("🔮 Simulador Individual (Predição ao Vivo)")
|
| 202 |
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
st.divider()
|
| 201 |
st.subheader("🔮 Simulador Individual (Predição ao Vivo)")
|
| 202 |
|
| 203 |
+
# --- 4. ÁREA DE PREDIÇÃO ---
|
| 204 |
+
col_input, col_res = st.columns([1, 2])
|
| 205 |
+
|
| 206 |
+
with col_input:
|
| 207 |
+
income = st.number_input("Renda Anual", 4000, 2000000, 65000, step=1000)
|
| 208 |
+
loan_amnt = st.number_input("Valor Empréstimo", 1000, 35000, 15000, step=500)
|
| 209 |
+
int_rate = st.slider("Juros (%)", 5.0, 25.0, 11.0)
|
| 210 |
+
age = st.number_input("Idade", 18, 80, 25)
|
| 211 |
+
emp_length = st.number_input("Anos Emprego", 0.0, 60.0, 2.0)
|
| 212 |
+
|
| 213 |
+
home = st.selectbox("Moradia", ["ALUGUEL", "PRÓPRIA", "FINANCIADA", "OUTROS"])
|
| 214 |
+
intent = st.selectbox("Motivo", ["PESSOAL", "EDUCAÇÃO", "MÉDICO", "VENTURE", "REFORMA", "DÍVIDA"])
|
| 215 |
+
grade = st.selectbox("Grade", ["A", "B", "C", "D", "E", "F", "G"])
|
| 216 |
+
default_hist = st.selectbox("Já teve calote?", ["Não", "Sim"])
|
| 217 |
+
|
| 218 |
+
with col_res:
|
| 219 |
+
if st.button("Executar Simulação para este Cliente", type="primary"):
|
| 220 |
+
# Montagem do DF (Lógica de Feature Engineering)
|
| 221 |
+
percent_income = loan_amnt / income
|
| 222 |
+
data_dict = {
|
| 223 |
+
'person_age': age, 'person_income': income, 'person_emp_length': emp_length,
|
| 224 |
+
'loan_amnt': loan_amnt, 'loan_int_rate': int_rate, 'loan_percent_income': percent_income,
|
| 225 |
+
'cb_person_cred_hist_length': max(2, int(age - 20))
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
# Recuperação das colunas do modelo (Robustez)
|
| 229 |
+
try:
|
| 230 |
+
if hasattr(current_model, "feature_names_in_"): cols = current_model.feature_names_in_
|
| 231 |
+
elif hasattr(current_model, "feature_name_"): cols = current_model.feature_name_
|
| 232 |
+
else: cols = []
|
| 233 |
+
except: cols = []
|
| 234 |
+
|
| 235 |
+
# Fallback se não detectar colunas (usa padrão do dataset)
|
| 236 |
+
if len(cols) == 0:
|
| 237 |
+
cols = ['person_age', 'person_income', 'person_emp_length', 'loan_amnt',
|
| 238 |
+
'loan_int_rate', 'loan_percent_income', 'cb_person_cred_hist_length',
|
| 239 |
+
'person_home_ownership_MORTGAGE', 'person_home_ownership_OTHER',
|
| 240 |
+
'person_home_ownership_OWN', 'person_home_ownership_RENT',
|
| 241 |
+
'loan_intent_EDUCATION', 'loan_intent_HOMEIMPROVEMENT', 'loan_intent_MEDICAL',
|
| 242 |
+
'loan_intent_PERSONAL', 'loan_intent_VENTURE', 'loan_intent_DEBTCONSOLIDATION',
|
| 243 |
+
'loan_grade_A', 'loan_grade_B', 'loan_grade_C', 'loan_grade_D',
|
| 244 |
+
'loan_grade_E', 'loan_grade_F', 'loan_grade_G',
|
| 245 |
+
'cb_person_default_on_file_Y']
|
| 246 |
+
|
| 247 |
+
df_input = pd.DataFrame(0, index=[0], columns=cols)
|
| 248 |
+
for c in data_dict:
|
| 249 |
+
if c in df_input.columns: df_input[c] = data_dict[c]
|
| 250 |
+
|
| 251 |
+
# One-Hot Manual
|
| 252 |
+
map_home = {'ALUGUEL': 'RENT', 'PRÓPRIA': 'OWN', 'FINANCIADA': 'MORTGAGE', 'OUTROS': 'OTHER'}
|
| 253 |
+
k_h = f"person_home_ownership_{map_home.get(home, 'OTHER')}"
|
| 254 |
+
if k_h in df_input.columns: df_input[k_h] = 1
|
| 255 |
+
|
| 256 |
+
map_int = {"PESSOAL": "PERSONAL", "EDUCAÇÃO": "EDUCATION", "MÉDICO": "MEDICAL", "VENTURE": "VENTURE", "REFORMA": "HOMEIMPROVEMENT", "DÍVIDA": "DEBTCONSOLIDATION"}
|
| 257 |
+
k_i = f"loan_intent_{map_int.get(intent, 'PERSONAL')}"
|
| 258 |
+
if k_i in df_input.columns: df_input[k_i] = 1
|
| 259 |
+
|
| 260 |
+
k_g = f"loan_grade_{grade}"
|
| 261 |
+
if k_g in df_input.columns: df_input[k_g] = 1
|
| 262 |
+
|
| 263 |
+
if default_hist == "Sim" and "cb_person_default_on_file_Y" in df_input.columns:
|
| 264 |
+
df_input["cb_person_default_on_file_Y"] = 1
|
| 265 |
+
|
| 266 |
+
# Resultado
|
| 267 |
+
proba = current_model.predict_proba(df_input)[0][1]
|
| 268 |
+
status = "REPROVADO" if proba > 0.5 else "APROVADO"
|
| 269 |
+
|
| 270 |
+
c_status, c_prob = st.columns(2)
|
| 271 |
+
if status == "APROVADO":
|
| 272 |
+
c_status.success(f"### {status}")
|
| 273 |
+
else:
|
| 274 |
+
c_status.error(f"### {status}")
|
| 275 |
+
c_prob.metric("Probabilidade de Risco", f"{proba:.1%}")
|
| 276 |
+
|
| 277 |
+
st.progress(proba)
|
| 278 |
+
|
| 279 |
+
# SHAP (Explicabilidade)
|
| 280 |
+
modelos_arvore = ['LightGBM', 'XGBoost', 'Random Forest', 'Decision Tree', 'Gradient Boosting', 'AdaBoost']
|
| 281 |
+
eh_arvore = any(x in model_name for x in modelos_arvore)
|
| 282 |
+
|
| 283 |
+
if eh_arvore:
|
| 284 |
+
st.markdown("**Por que essa decisão? (SHAP Waterfall)**")
|
| 285 |
+
try:
|
| 286 |
+
explainer = shap.TreeExplainer(current_model)
|
| 287 |
+
shap_values = explainer(df_input)
|
| 288 |
+
if len(shap_values.shape) == 3: shap_values = shap_values[:, :, 1]
|
| 289 |
+
|
| 290 |
+
fig_shap = plt.figure(figsize=(8, 3))
|
| 291 |
+
shap.plots.waterfall(shap_values[0], show=False, max_display=7)
|
| 292 |
+
st.pyplot(fig_shap)
|
| 293 |
+
except:
|
| 294 |
+
st.warning("Não foi possível gerar a explicação visual para este caso.")
|
| 295 |
+
else:
|
| 296 |
+
st.info("Visualização SHAP disponível apenas para modelos baseados em Árvore.")
|
| 297 |
+
|
| 298 |
+
# =========================================================
|
| 299 |
+
# ABA IV: CLUSTERIZAÇÃO (Mantida)
|
| 300 |
+
# =========================================================
|
| 301 |
+
with tab3:
|
| 302 |
+
st.header("IV. Segmentação de Clientes")
|
| 303 |
+
if 'Cluster' in df.columns:
|
| 304 |
+
st.markdown("**Perfis Identificados (K-Means):**")
|
| 305 |
+
st.dataframe(df.groupby('Cluster')[['person_age', 'person_income', 'loan_amnt', 'loan_status']].mean().style.format({'person_income': 'R$ {:,.2f}', 'loan_status': '{:.1%}'}), use_container_width=True)
|
| 306 |
+
|
| 307 |
+
fig_clus = px.scatter(df, x='person_income', y='loan_amnt', color='Cluster',
|
| 308 |
+
title="Clusterização: Renda vs Empréstimo", range_x=[0, 200000])
|
| 309 |
+
st.plotly_chart(fig_clus, use_container_width=True)
|
| 310 |
+
else:
|
| 311 |
+
st.warning("Clusterização não disponível.")
|
| 312 |
+
|
| 313 |
+
# =========================================================
|
| 314 |
+
# ABA V: RECOMENDAÇÕES (Mantida)
|
| 315 |
+
# =========================================================
|
| 316 |
+
with tab4:
|
| 317 |
+
st.header("V. Recomendações Gerenciais")
|
| 318 |
+
st.markdown("""
|
| 319 |
+
### Plano de Ação Estratégico
|
| 320 |
+
* **Esteira Automática:** Aprovação direta para risco < 20% (LightGBM).
|
| 321 |
+
* **Mesa de Crédito:** Análise manual para risco entre 20-60%.
|
| 322 |
+
* **Proteção:** Bloqueio imediato para risco > 60%.
|
| 323 |
+
* **Segmentação:** Ofertas personalizadas para o cluster 'Premium' (Juros reduzidos).
|
| 324 |
+
""")
|
| 325 |
+
st.caption("Prova Final - Eng. Produção")
|