Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -127,16 +127,15 @@ with tab1:
|
|
| 127 |
st.warning(f"Não foi possível gerar o gráfico para esta variável. Erro: {e}")
|
| 128 |
|
| 129 |
# =========================================================
|
| 130 |
-
# ABA II: AVALIAÇÃO + SIMULADOR (
|
| 131 |
# =========================================================
|
| 132 |
with tab2:
|
| 133 |
st.header("II. Construção e Avaliação dos Modelos")
|
| 134 |
|
| 135 |
# 1. SELEÇÃO DO MODELO
|
| 136 |
-
# Recupera a lista de modelos disponíveis no arquivo carregado
|
| 137 |
model_names = list(sistema["modelos"].keys())
|
| 138 |
|
| 139 |
-
# Filtros de Categoria
|
| 140 |
cats = ["Todos", "Boosting", "Árvores", "Outros"]
|
| 141 |
cat_filter = st.radio("Filtrar Família do Algoritmo:", cats, horizontal=True)
|
| 142 |
|
|
@@ -149,18 +148,16 @@ with tab2:
|
|
| 149 |
|
| 150 |
selected_model_name = st.selectbox("Selecione o Modelo para Análise:", model_names)
|
| 151 |
|
| 152 |
-
#
|
| 153 |
dados_modelo = sistema["modelos"][selected_model_name]
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
y_proba_saved = dados_modelo["y_proba"] # Vetor para ROC
|
| 159 |
-
current_model_obj = dados_modelo["modelo"] # O OBJETO DO MODELO (Correção do NameError!)
|
| 160 |
|
| 161 |
st.markdown("---")
|
| 162 |
|
| 163 |
-
# 2. DASHBOARD DE PERFORMANCE (
|
| 164 |
c1, c2, c3 = st.columns([1, 1, 1.5])
|
| 165 |
|
| 166 |
with c1:
|
|
@@ -184,115 +181,103 @@ with tab2:
|
|
| 184 |
plt.grid(alpha=0.3)
|
| 185 |
st.pyplot(fig_roc)
|
| 186 |
else:
|
| 187 |
-
st.info("ROC indisponível
|
| 188 |
|
| 189 |
with c3:
|
| 190 |
-
st.subheader("
|
| 191 |
k1, k2 = st.columns(2)
|
| 192 |
-
k1.metric("Recall (Risco)", f"{metrics['Recall']:.1%}"
|
| 193 |
k2.metric("AUC Global", f"{metrics['AUC']:.3f}")
|
| 194 |
-
|
| 195 |
k3, k4 = st.columns(2)
|
| 196 |
k3.metric("Acurácia", f"{metrics['Acurácia']:.1%}")
|
| 197 |
k4.metric("F1-Score", f"{metrics['F1-Score']:.1%}")
|
| 198 |
-
|
| 199 |
-
st.info(f"**Análise:** O modelo selecionado ({selected_model_name}) detecta **{metrics['Recall']:.1%}** dos casos de risco.")
|
| 200 |
|
| 201 |
-
# 3. DIVISOR
|
| 202 |
st.divider()
|
| 203 |
|
| 204 |
-
#
|
| 205 |
-
st.subheader("🔮 Simulador de Predição (
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
# Inputs do Formulário
|
| 209 |
col_input, col_res = st.columns([1, 1.5])
|
| 210 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
with col_input:
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
if st.button("Executar Simulação", type="primary"):
|
| 227 |
-
# A. PREPARAR OS DADOS (Feature Engineering)
|
| 228 |
percent_income = loan_amnt / income
|
| 229 |
-
|
| 230 |
-
# Dados brutos
|
| 231 |
raw_data = {
|
| 232 |
-
'person_age': age,
|
| 233 |
-
'
|
| 234 |
-
'person_emp_length': emp_length,
|
| 235 |
-
'loan_amnt': loan_amnt,
|
| 236 |
-
'loan_int_rate': int_rate,
|
| 237 |
-
'loan_percent_income': percent_income,
|
| 238 |
'cb_person_cred_hist_length': max(2, int(age - 20))
|
| 239 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 240 |
|
| 241 |
-
# B. GARANTIR AS COLUNAS CERTAS (Correção de Robustez)
|
| 242 |
-
# Tenta pegar as colunas do arquivo 'sistema_risco_completo.pkl'
|
| 243 |
-
try:
|
| 244 |
-
model_cols = sistema["X_test_sample"].columns
|
| 245 |
-
except:
|
| 246 |
-
# Se der erro, usa lista manual (fallback)
|
| 247 |
-
model_cols = ['person_age', 'person_income', 'person_emp_length', 'loan_amnt',
|
| 248 |
-
'loan_int_rate', 'loan_percent_income', 'cb_person_cred_hist_length',
|
| 249 |
-
'person_home_ownership_MORTGAGE', 'person_home_ownership_OTHER',
|
| 250 |
-
'person_home_ownership_OWN', 'person_home_ownership_RENT',
|
| 251 |
-
'loan_intent_DEBTCONSOLIDATION', 'loan_intent_EDUCATION',
|
| 252 |
-
'loan_intent_HOMEIMPROVEMENT', 'loan_intent_MEDICAL',
|
| 253 |
-
'loan_intent_PERSONAL', 'loan_intent_VENTURE',
|
| 254 |
-
'loan_grade_A', 'loan_grade_B', 'loan_grade_C', 'loan_grade_D',
|
| 255 |
-
'loan_grade_E', 'loan_grade_F', 'loan_grade_G',
|
| 256 |
-
'cb_person_default_on_file_Y']
|
| 257 |
-
|
| 258 |
-
# Cria DF zerado com a estrutura correta
|
| 259 |
df_input = pd.DataFrame(0, index=[0], columns=model_cols)
|
| 260 |
-
|
| 261 |
-
# Preenche numéricos
|
| 262 |
for c in raw_data:
|
| 263 |
if c in df_input.columns: df_input[c] = raw_data[c]
|
| 264 |
|
| 265 |
-
#
|
| 266 |
-
# Moradia
|
| 267 |
map_home = {'ALUGUEL': 'RENT', 'PRÓPRIA': 'OWN', 'FINANCIADA': 'MORTGAGE', 'OUTROS': 'OTHER'}
|
| 268 |
key_h = f"person_home_ownership_{map_home[home.split()[0]]}"
|
| 269 |
if key_h in df_input.columns: df_input[key_h] = 1
|
| 270 |
|
| 271 |
-
# Motivo
|
| 272 |
map_int = {"PESSOAL": "PERSONAL", "EDUCAÇÃO": "EDUCATION", "MÉDICO": "MEDICAL", "VENTURE": "VENTURE", "REFORMA": "HOMEIMPROVEMENT", "DÍVIDA": "DEBTCONSOLIDATION"}
|
| 273 |
key_i = f"loan_intent_{map_int[intent]}"
|
| 274 |
if key_i in df_input.columns: df_input[key_i] = 1
|
| 275 |
|
| 276 |
-
# Grade
|
| 277 |
key_g = f"loan_grade_{grade}"
|
| 278 |
if key_g in df_input.columns: df_input[key_g] = 1
|
| 279 |
|
| 280 |
-
# Histórico
|
| 281 |
if default_hist == "Sim" and "cb_person_default_on_file_Y" in df_input.columns:
|
| 282 |
df_input["cb_person_default_on_file_Y"] = 1
|
| 283 |
-
|
| 284 |
-
#
|
| 285 |
-
try:
|
| 286 |
-
|
| 287 |
-
proba = current_model_obj.predict_proba(df_input)[0][1]
|
| 288 |
-
except:
|
| 289 |
-
# Se for SVM ou outro sem proba, usa predict e finge 0 ou 1
|
| 290 |
pred = current_model_obj.predict(df_input)[0]
|
| 291 |
proba = 1.0 if pred == 1 else 0.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 293 |
status = "REPROVADO" if proba > 0.5 else "APROVADO"
|
| 294 |
|
| 295 |
-
# D. EXIBIÇÃO
|
| 296 |
c_res1, c_res2 = st.columns(2)
|
| 297 |
if status == "APROVADO":
|
| 298 |
c_res1.success(f"## ✅ {status}")
|
|
@@ -302,21 +287,22 @@ with tab2:
|
|
| 302 |
|
| 303 |
st.progress(float(proba))
|
| 304 |
|
| 305 |
-
#
|
| 306 |
modelos_arvore = ['LightGBM', 'XGBoost', 'Random Forest', 'Decision Tree', 'Gradient', 'Ada']
|
| 307 |
-
if any(x in
|
| 308 |
-
st.markdown("**Por que
|
| 309 |
try:
|
| 310 |
explainer = shap.TreeExplainer(current_model_obj)
|
| 311 |
-
shap_values = explainer(df_input)
|
| 312 |
if len(shap_values.shape) == 3: shap_values = shap_values[:, :, 1]
|
| 313 |
|
| 314 |
fig_shap = plt.figure(figsize=(8, 3))
|
| 315 |
shap.plots.waterfall(shap_values[0], show=False, max_display=7)
|
| 316 |
st.pyplot(fig_shap)
|
| 317 |
except Exception as e:
|
| 318 |
-
st.warning(
|
| 319 |
-
|
|
|
|
| 320 |
# =========================================================
|
| 321 |
# ABA IV: CLUSTERIZAÇÃO (Mantida)
|
| 322 |
# =========================================================
|
|
|
|
| 127 |
st.warning(f"Não foi possível gerar o gráfico para esta variável. Erro: {e}")
|
| 128 |
|
| 129 |
# =========================================================
|
| 130 |
+
# ABA II: AVALIAÇÃO + SIMULADOR ESTÁVEL (COM st.form)
|
| 131 |
# =========================================================
|
| 132 |
with tab2:
|
| 133 |
st.header("II. Construção e Avaliação dos Modelos")
|
| 134 |
|
| 135 |
# 1. SELEÇÃO DO MODELO
|
|
|
|
| 136 |
model_names = list(sistema["modelos"].keys())
|
| 137 |
|
| 138 |
+
# Filtros de Categoria
|
| 139 |
cats = ["Todos", "Boosting", "Árvores", "Outros"]
|
| 140 |
cat_filter = st.radio("Filtrar Família do Algoritmo:", cats, horizontal=True)
|
| 141 |
|
|
|
|
| 148 |
|
| 149 |
selected_model_name = st.selectbox("Selecione o Modelo para Análise:", model_names)
|
| 150 |
|
| 151 |
+
# Recuperação dos dados
|
| 152 |
dados_modelo = sistema["modelos"][selected_model_name]
|
| 153 |
+
metrics = dados_modelo["metrics"]
|
| 154 |
+
y_pred_saved = dados_modelo["y_pred"]
|
| 155 |
+
y_proba_saved = dados_modelo["y_proba"]
|
| 156 |
+
current_model_obj = dados_modelo["modelo"]
|
|
|
|
|
|
|
| 157 |
|
| 158 |
st.markdown("---")
|
| 159 |
|
| 160 |
+
# 2. DASHBOARD DE PERFORMANCE (Estático - Não treme)
|
| 161 |
c1, c2, c3 = st.columns([1, 1, 1.5])
|
| 162 |
|
| 163 |
with c1:
|
|
|
|
| 181 |
plt.grid(alpha=0.3)
|
| 182 |
st.pyplot(fig_roc)
|
| 183 |
else:
|
| 184 |
+
st.info("ROC indisponível.")
|
| 185 |
|
| 186 |
with c3:
|
| 187 |
+
st.subheader("KPIs do Modelo")
|
| 188 |
k1, k2 = st.columns(2)
|
| 189 |
+
k1.metric("Recall (Risco)", f"{metrics['Recall']:.1%}")
|
| 190 |
k2.metric("AUC Global", f"{metrics['AUC']:.3f}")
|
|
|
|
| 191 |
k3, k4 = st.columns(2)
|
| 192 |
k3.metric("Acurácia", f"{metrics['Acurácia']:.1%}")
|
| 193 |
k4.metric("F1-Score", f"{metrics['F1-Score']:.1%}")
|
|
|
|
|
|
|
| 194 |
|
|
|
|
| 195 |
st.divider()
|
| 196 |
|
| 197 |
+
# 3. SIMULADOR OTIMIZADO (AQUI ESTÁ A CORREÇÃO DO TREMOR)
|
| 198 |
+
st.subheader("🔮 Simulador de Predição (Estável)")
|
| 199 |
+
|
|
|
|
|
|
|
| 200 |
col_input, col_res = st.columns([1, 1.5])
|
| 201 |
|
| 202 |
+
# Variável de estado para guardar o resultado mesmo se a tela piscar
|
| 203 |
+
if 'simulacao_resultado' not in st.session_state:
|
| 204 |
+
st.session_state['simulacao_resultado'] = None
|
| 205 |
+
|
| 206 |
with col_input:
|
| 207 |
+
# --- O SEGREDO: st.form ---
|
| 208 |
+
# Tudo que está aqui dentro NÃO recarrega a página enquanto você digita/arrasta
|
| 209 |
+
with st.form("form_simulador"):
|
| 210 |
+
st.markdown("**Dados do Cliente**")
|
| 211 |
+
income = st.number_input("Renda Anual (R$)", 4000, 2000000, 65000, step=1000)
|
| 212 |
+
loan_amnt = st.number_input("Valor Empréstimo (R$)", 1000, 35000, 15000, step=500)
|
| 213 |
+
int_rate = st.slider("Taxa de Juros (%)", 5.0, 25.0, 11.0, step=0.1)
|
| 214 |
+
age = st.number_input("Idade", 18, 80, 25)
|
| 215 |
+
emp_length = st.number_input("Anos de Emprego", 0.0, 60.0, 2.0)
|
| 216 |
+
|
| 217 |
+
home = st.selectbox("Moradia", ["ALUGUEL", "PRÓPRIA", "FINANCIADA", "OUTROS"])
|
| 218 |
+
intent = st.selectbox("Motivo", ["PESSOAL", "EDUCAÇÃO", "MÉDICO", "VENTURE", "REFORMA", "DÍVIDA"])
|
| 219 |
+
grade = st.selectbox("Grade de Risco", ["A", "B", "C", "D", "E", "F", "G"])
|
| 220 |
+
default_hist = st.selectbox("Histórico de Calote?", ["Não", "Sim"])
|
| 221 |
+
|
| 222 |
+
# O Botão de submissão fica DENTRO do form
|
| 223 |
+
submit_button = st.form_submit_button("Executar Simulação", type="primary")
|
| 224 |
|
| 225 |
+
if submit_button:
|
| 226 |
+
# LÓGICA DE CÁLCULO (Só roda quando clica no botão)
|
|
|
|
|
|
|
|
|
|
| 227 |
percent_income = loan_amnt / income
|
|
|
|
|
|
|
| 228 |
raw_data = {
|
| 229 |
+
'person_age': age, 'person_income': income, 'person_emp_length': emp_length,
|
| 230 |
+
'loan_amnt': loan_amnt, 'loan_int_rate': int_rate, 'loan_percent_income': percent_income,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
'cb_person_cred_hist_length': max(2, int(age - 20))
|
| 232 |
}
|
| 233 |
+
|
| 234 |
+
# Recuperação de colunas (Fallback robusto)
|
| 235 |
+
try: model_cols = sistema["X_test_sample"].columns
|
| 236 |
+
except:
|
| 237 |
+
model_cols = ['person_age', 'person_income', 'person_emp_length', 'loan_amnt', 'loan_int_rate', 'loan_percent_income', 'cb_person_cred_hist_length', 'person_home_ownership_MORTGAGE', 'person_home_ownership_OTHER', 'person_home_ownership_OWN', 'person_home_ownership_RENT', 'loan_intent_DEBTCONSOLIDATION', 'loan_intent_EDUCATION', 'loan_intent_HOMEIMPROVEMENT', 'loan_intent_MEDICAL', 'loan_intent_PERSONAL', 'loan_intent_VENTURE', 'loan_grade_A', 'loan_grade_B', 'loan_grade_C', 'loan_grade_D', 'loan_grade_E', 'loan_grade_F', 'loan_grade_G', 'cb_person_default_on_file_Y']
|
| 238 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
df_input = pd.DataFrame(0, index=[0], columns=model_cols)
|
|
|
|
|
|
|
| 240 |
for c in raw_data:
|
| 241 |
if c in df_input.columns: df_input[c] = raw_data[c]
|
| 242 |
|
| 243 |
+
# One-Hot Manual
|
|
|
|
| 244 |
map_home = {'ALUGUEL': 'RENT', 'PRÓPRIA': 'OWN', 'FINANCIADA': 'MORTGAGE', 'OUTROS': 'OTHER'}
|
| 245 |
key_h = f"person_home_ownership_{map_home[home.split()[0]]}"
|
| 246 |
if key_h in df_input.columns: df_input[key_h] = 1
|
| 247 |
|
|
|
|
| 248 |
map_int = {"PESSOAL": "PERSONAL", "EDUCAÇÃO": "EDUCATION", "MÉDICO": "MEDICAL", "VENTURE": "VENTURE", "REFORMA": "HOMEIMPROVEMENT", "DÍVIDA": "DEBTCONSOLIDATION"}
|
| 249 |
key_i = f"loan_intent_{map_int[intent]}"
|
| 250 |
if key_i in df_input.columns: df_input[key_i] = 1
|
| 251 |
|
|
|
|
| 252 |
key_g = f"loan_grade_{grade}"
|
| 253 |
if key_g in df_input.columns: df_input[key_g] = 1
|
| 254 |
|
|
|
|
| 255 |
if default_hist == "Sim" and "cb_person_default_on_file_Y" in df_input.columns:
|
| 256 |
df_input["cb_person_default_on_file_Y"] = 1
|
| 257 |
+
|
| 258 |
+
# Predição
|
| 259 |
+
try: proba = current_model_obj.predict_proba(df_input)[0][1]
|
| 260 |
+
except:
|
|
|
|
|
|
|
|
|
|
| 261 |
pred = current_model_obj.predict(df_input)[0]
|
| 262 |
proba = 1.0 if pred == 1 else 0.0
|
| 263 |
+
|
| 264 |
+
# Salva no Session State para persistir e não piscar
|
| 265 |
+
st.session_state['simulacao_resultado'] = {
|
| 266 |
+
'proba': proba,
|
| 267 |
+
'df_input': df_input,
|
| 268 |
+
'model_name': selected_model_name
|
| 269 |
+
}
|
| 270 |
|
| 271 |
+
# 4. EXIBIÇÃO DO RESULTADO (Fora do Form)
|
| 272 |
+
with col_res:
|
| 273 |
+
st.markdown("### Resultado da Análise")
|
| 274 |
+
|
| 275 |
+
# Só mostra se tiver resultado calculado
|
| 276 |
+
if st.session_state['simulacao_resultado']:
|
| 277 |
+
res = st.session_state['simulacao_resultado']
|
| 278 |
+
proba = res['proba']
|
| 279 |
status = "REPROVADO" if proba > 0.5 else "APROVADO"
|
| 280 |
|
|
|
|
| 281 |
c_res1, c_res2 = st.columns(2)
|
| 282 |
if status == "APROVADO":
|
| 283 |
c_res1.success(f"## ✅ {status}")
|
|
|
|
| 287 |
|
| 288 |
st.progress(float(proba))
|
| 289 |
|
| 290 |
+
# SHAP (Explicabilidade)
|
| 291 |
modelos_arvore = ['LightGBM', 'XGBoost', 'Random Forest', 'Decision Tree', 'Gradient', 'Ada']
|
| 292 |
+
if any(x in res['model_name'] for x in modelos_arvore):
|
| 293 |
+
st.markdown(f"**Por que o {res['model_name']} decidiu assim?**")
|
| 294 |
try:
|
| 295 |
explainer = shap.TreeExplainer(current_model_obj)
|
| 296 |
+
shap_values = explainer(res['df_input'])
|
| 297 |
if len(shap_values.shape) == 3: shap_values = shap_values[:, :, 1]
|
| 298 |
|
| 299 |
fig_shap = plt.figure(figsize=(8, 3))
|
| 300 |
shap.plots.waterfall(shap_values[0], show=False, max_display=7)
|
| 301 |
st.pyplot(fig_shap)
|
| 302 |
except Exception as e:
|
| 303 |
+
st.warning("Visualização indisponível.")
|
| 304 |
+
else:
|
| 305 |
+
st.info("👈 Preencha o formulário e clique em 'Executar' para ver o resultado.")
|
| 306 |
# =========================================================
|
| 307 |
# ABA IV: CLUSTERIZAÇÃO (Mantida)
|
| 308 |
# =========================================================
|