Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,301 +5,125 @@ import matplotlib.pyplot as plt
|
|
| 5 |
import seaborn as sns
|
| 6 |
import shap
|
| 7 |
import numpy as np
|
| 8 |
-
import plotly.express as px
|
|
|
|
| 9 |
|
| 10 |
-
# --- CONFIGURAÇÃO
|
| 11 |
st.set_page_config(page_title="CrediFast Risk System", layout="wide")
|
| 12 |
-
|
| 13 |
st.title("🏦 CrediFast: Sistema Integrado de Análise de Risco")
|
| 14 |
-
st.markdown("Dashboard interativo para a Prova Final de Sistemas de Informação - Engenharia de Produção")
|
| 15 |
|
| 16 |
-
# --- CARREGAMENTO ---
|
| 17 |
@st.cache_data
|
| 18 |
def load_data():
|
| 19 |
return pd.read_csv("dados_credito_clean.csv")
|
| 20 |
|
| 21 |
@st.cache_resource
|
| 22 |
-
def
|
| 23 |
-
|
|
|
|
| 24 |
|
| 25 |
try:
|
| 26 |
df = load_data()
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
except FileNotFoundError:
|
| 29 |
-
st.error("
|
| 30 |
st.stop()
|
| 31 |
|
| 32 |
-
# ---
|
| 33 |
-
tab1, tab2, tab3, tab4 = st.tabs([
|
| 34 |
-
"I. Diagnóstico Inicial",
|
| 35 |
-
"II & III. Modelagem & SHAP",
|
| 36 |
-
"IV. Clusterização",
|
| 37 |
-
"V. Recomendações"
|
| 38 |
-
])
|
| 39 |
|
| 40 |
-
#
|
| 41 |
-
# ABA I: DIAGNÓSTICO E TRATAMENTO (O que você pediu)
|
| 42 |
-
# =========================================================
|
| 43 |
with tab1:
|
| 44 |
-
st.header("I. Diagnóstico Inicial
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
col_kpi1.metric("Total de Registros", f"{df.shape[0]:,}")
|
| 48 |
-
col_kpi2.metric("Variáveis (Colunas)", df.shape[1])
|
| 49 |
-
col_kpi3.metric("Taxa Global de Calote", f"{df['loan_status'].mean():.1%}")
|
| 50 |
-
|
| 51 |
-
st.divider()
|
| 52 |
-
|
| 53 |
-
# 1. Visualização dos Dados
|
| 54 |
-
st.subheader("1. Visualização da Base de Dados (Processada)")
|
| 55 |
-
st.dataframe(df.head(10), use_container_width=True)
|
| 56 |
-
with st.expander("Ver Estatísticas Descritivas (Describe)"):
|
| 57 |
-
st.dataframe(df.describe())
|
| 58 |
-
|
| 59 |
-
# 2. Relatório de Tratamento
|
| 60 |
-
st.subheader("2. Relatório de Tratamento de Dados")
|
| 61 |
-
st.info("""
|
| 62 |
-
**Processos de Limpeza e Imputação Realizados no Código:**
|
| 63 |
-
|
| 64 |
-
1. **Tratamento de Nulos (`Missing Values`):**
|
| 65 |
-
* `person_emp_length`: Preenchido com a **Mediana** (devido à presença de outliers que distorciam a média).
|
| 66 |
-
* `loan_int_rate`: Preenchido com a **Média por Grau (Loan Grade)**. Assumiu-se que a taxa de juros é correlacionada com a nota de crédito.
|
| 67 |
-
|
| 68 |
-
2. **Remoção de Outliers e Inconsistências:**
|
| 69 |
-
* Foram removidos registros com **Idade > 100 anos**.
|
| 70 |
-
* Foram removidos casos biologicamente impossíveis onde **Tempo de Emprego > Idade**.
|
| 71 |
-
|
| 72 |
-
3. **Engenharia de Features:**
|
| 73 |
-
* Criação de variáveis Dummy (One-Hot Encoding) para colunas categóricas.
|
| 74 |
-
* Aplicação de **SMOTE** (Synthetic Minority Over-sampling Technique) nos dados de treino para corrigir o desbalanceamento da classe 'Default'.
|
| 75 |
-
""")
|
| 76 |
-
|
| 77 |
-
st.divider()
|
| 78 |
-
|
| 79 |
-
# 3. Gráfico Interativo de Distribuição
|
| 80 |
-
st.subheader("3. Análise Exploratória Interativa")
|
| 81 |
-
st.markdown("Selecione qualquer variável para visualizar sua distribuição em relação ao Risco de Crédito.")
|
| 82 |
-
|
| 83 |
-
# Seletor de Variáveis
|
| 84 |
-
# Filtramos para mostrar primeiro as colunas mais interessantes
|
| 85 |
-
colunas_pri = ['person_age', 'person_income', 'loan_amnt', 'loan_int_rate', 'loan_percent_income', 'loan_grade', 'person_home_ownership']
|
| 86 |
-
# Adiciona o resto das colunas que não estão na lista prioritária
|
| 87 |
-
outras_cols = [c for c in df.columns if c not in colunas_pri and c != 'loan_status']
|
| 88 |
-
opcoes = colunas_pri + outras_cols
|
| 89 |
-
|
| 90 |
-
var_selected = st.selectbox("Escolha a Variável para Análise:", opcoes)
|
| 91 |
-
|
| 92 |
-
# Lógica de Plotagem Inteligente (Plotly)
|
| 93 |
-
try:
|
| 94 |
-
# Se for numérica com muitos valores únicos -> Histograma
|
| 95 |
-
if pd.api.types.is_numeric_dtype(df[var_selected]) and df[var_selected].nunique() > 10:
|
| 96 |
-
fig = px.histogram(
|
| 97 |
-
df,
|
| 98 |
-
x=var_selected,
|
| 99 |
-
color="loan_status",
|
| 100 |
-
marginal="box", # Adiciona boxplot no topo
|
| 101 |
-
nbins=50,
|
| 102 |
-
title=f"Distribuição de '{var_selected}' por Status do Empréstimo",
|
| 103 |
-
labels={"loan_status": "Calote (0=Não, 1=Sim)"},
|
| 104 |
-
color_discrete_sequence=["#1f77b4", "#d62728"], # Azul (Bom), Vermelho (Ruim)
|
| 105 |
-
opacity=0.7,
|
| 106 |
-
barmode="overlay"
|
| 107 |
-
)
|
| 108 |
-
# Se for categórica ou numérica discreta (ex: Grade) -> Gráfico de Barras
|
| 109 |
-
else:
|
| 110 |
-
# Conta a frequência
|
| 111 |
-
df_count = df.groupby([var_selected, 'loan_status']).size().reset_index(name='Contagem')
|
| 112 |
-
fig = px.bar(
|
| 113 |
-
df_count,
|
| 114 |
-
x=var_selected,
|
| 115 |
-
y='Contagem',
|
| 116 |
-
color='loan_status',
|
| 117 |
-
barmode='group',
|
| 118 |
-
title=f"Frequência de '{var_selected}' por Status",
|
| 119 |
-
color_discrete_sequence=["#1f77b4", "#d62728"]
|
| 120 |
-
)
|
| 121 |
-
|
| 122 |
-
st.plotly_chart(fig, use_container_width=True)
|
| 123 |
-
|
| 124 |
-
except Exception as e:
|
| 125 |
-
st.warning(f"Não foi possível gerar o gráfico para esta variável. Erro: {e}")
|
| 126 |
|
| 127 |
# =========================================================
|
| 128 |
-
# ABA II
|
| 129 |
# =========================================================
|
| 130 |
with tab2:
|
| 131 |
-
st.header("II.
|
| 132 |
|
| 133 |
-
#
|
| 134 |
-
|
| 135 |
|
| 136 |
-
|
|
|
|
|
|
|
| 137 |
|
| 138 |
-
|
| 139 |
-
|
|
|
|
|
|
|
| 140 |
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
else:
|
| 156 |
-
st.
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
st.
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
age = st.number_input("Idade", 18, 80, 25)
|
| 167 |
-
emp_length = st.number_input("Anos Emprego", 0.0, 60.0, 2.0)
|
| 168 |
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
with col_sim:
|
| 175 |
-
st.markdown("### 🔮 Predição em Tempo Real")
|
| 176 |
-
|
| 177 |
-
if st.button("Executar Análise de Risco", type="primary"):
|
| 178 |
-
# ... (Lógica de montagem do DF igual ao anterior) ...
|
| 179 |
-
# Recriando o input_df rapidamente aqui
|
| 180 |
-
percent_income = loan_amnt / income
|
| 181 |
-
data_dict = {
|
| 182 |
-
'person_age': age, 'person_income': income, 'person_emp_length': emp_length,
|
| 183 |
-
'loan_amnt': loan_amnt, 'loan_int_rate': int_rate, 'loan_percent_income': percent_income,
|
| 184 |
-
'cb_person_cred_hist_length': max(2, int(age - 20))
|
| 185 |
-
}
|
| 186 |
-
|
| 187 |
-
# Tenta recuperar colunas do modelo
|
| 188 |
-
try:
|
| 189 |
-
if hasattr(current_model, "feature_names_in_"): cols = current_model.feature_names_in_
|
| 190 |
-
elif hasattr(current_model, "feature_name_"): cols = current_model.feature_name_
|
| 191 |
-
else: cols = [] # Fallback
|
| 192 |
-
except: cols = []
|
| 193 |
-
|
| 194 |
-
# Fallback manual das colunas se vazio (Importante para garantir robustez)
|
| 195 |
-
if len(cols) == 0:
|
| 196 |
-
cols = ['person_age', 'person_income', 'person_emp_length', 'loan_amnt',
|
| 197 |
-
'loan_int_rate', 'loan_percent_income', 'cb_person_cred_hist_length',
|
| 198 |
-
'person_home_ownership_MORTGAGE', 'person_home_ownership_OTHER',
|
| 199 |
-
'person_home_ownership_OWN', 'person_home_ownership_RENT',
|
| 200 |
-
'loan_intent_EDUCATION', 'loan_intent_HOMEIMPROVEMENT', 'loan_intent_MEDICAL',
|
| 201 |
-
'loan_intent_PERSONAL', 'loan_intent_VENTURE', 'loan_intent_DEBTCONSOLIDATION',
|
| 202 |
-
'loan_grade_A', 'loan_grade_B', 'loan_grade_C', 'loan_grade_D',
|
| 203 |
-
'loan_grade_E', 'loan_grade_F', 'loan_grade_G',
|
| 204 |
-
'cb_person_default_on_file_Y']
|
| 205 |
-
|
| 206 |
-
df_input = pd.DataFrame(0, index=[0], columns=cols)
|
| 207 |
-
for c in data_dict:
|
| 208 |
-
if c in df_input.columns: df_input[c] = data_dict[c]
|
| 209 |
-
|
| 210 |
-
# Mapeamentos
|
| 211 |
-
map_home = {'ALUGUEL': 'RENT', 'PRÓPRIA': 'OWN', 'FINANCIADA': 'MORTGAGE', 'OUTROS': 'OTHER'}
|
| 212 |
-
k_h = f"person_home_ownership_{map_home.get(home, 'OTHER')}"
|
| 213 |
-
if k_h in df_input.columns: df_input[k_h] = 1
|
| 214 |
-
|
| 215 |
-
map_int = {"PESSOAL": "PERSONAL", "EDUCAÇÃO": "EDUCATION", "MÉDICO": "MEDICAL", "VENTURE": "VENTURE", "REFORMA": "HOMEIMPROVEMENT", "DÍVIDA": "DEBTCONSOLIDATION"}
|
| 216 |
-
k_i = f"loan_intent_{map_int.get(intent, 'PERSONAL')}"
|
| 217 |
-
if k_i in df_input.columns: df_input[k_i] = 1
|
| 218 |
-
|
| 219 |
-
k_g = f"loan_grade_{grade}"
|
| 220 |
-
if k_g in df_input.columns: df_input[k_g] = 1
|
| 221 |
-
|
| 222 |
-
if default_hist == "Sim" and "cb_person_default_on_file_Y" in df_input.columns:
|
| 223 |
-
df_input["cb_person_default_on_file_Y"] = 1
|
| 224 |
-
|
| 225 |
-
# PREDIÇÃO
|
| 226 |
-
proba = current_model.predict_proba(df_input)[0][1]
|
| 227 |
-
status = "REPROVADO" if proba > 0.5 else "APROVADO"
|
| 228 |
-
|
| 229 |
-
# Mostrador Visual
|
| 230 |
-
c_res1, c_res2 = st.columns(2)
|
| 231 |
-
if status == "APROVADO":
|
| 232 |
-
c_res1.success(f"### ✅ {status}")
|
| 233 |
-
else:
|
| 234 |
-
c_res1.error(f"### ❌ {status}")
|
| 235 |
-
c_res2.metric("Score de Risco (Probabilidade)", f"{proba:.1%}")
|
| 236 |
-
|
| 237 |
-
st.progress(proba)
|
| 238 |
-
|
| 239 |
-
# SHAP
|
| 240 |
-
st.markdown("#### 🔎 Explicabilidade (SHAP)")
|
| 241 |
-
modelos_arvore = ['LightGBM', 'XGBoost', 'Random Forest', 'Decision Tree', 'Gradient Boosting', 'AdaBoost']
|
| 242 |
-
eh_arvore = any(x in model_name for x in modelos_arvore)
|
| 243 |
-
|
| 244 |
-
if eh_arvore:
|
| 245 |
-
try:
|
| 246 |
-
explainer = shap.TreeExplainer(current_model)
|
| 247 |
-
shap_values = explainer(df_input)
|
| 248 |
-
if len(shap_values.shape) == 3: shap_values = shap_values[:, :, 1]
|
| 249 |
-
|
| 250 |
-
fig_shap = plt.figure(figsize=(10, 4))
|
| 251 |
-
shap.plots.waterfall(shap_values[0], show=False, max_display=7)
|
| 252 |
-
st.pyplot(fig_shap)
|
| 253 |
-
except:
|
| 254 |
-
st.warning("Erro ao gerar SHAP.")
|
| 255 |
-
else:
|
| 256 |
-
st.info("SHAP visual disponível apenas para modelos de Árvore.")
|
| 257 |
-
|
| 258 |
-
# =========================================================
|
| 259 |
-
# ABA IV: CLUSTERIZAÇÃO (Mantida do anterior)
|
| 260 |
-
# =========================================================
|
| 261 |
-
with tab3:
|
| 262 |
-
st.header("IV. Segmentação de Clientes (Clusters)")
|
| 263 |
-
if 'Cluster' in df.columns:
|
| 264 |
-
st.markdown("Perfies identificados via **K-Means**:")
|
| 265 |
-
cols_cluster_view = ['person_age', 'person_income', 'loan_amnt', 'loan_status']
|
| 266 |
-
# Tabela formatada
|
| 267 |
-
st.dataframe(df.groupby('Cluster')[cols_cluster_view].mean().style.format({'person_income': 'R$ {:,.2f}', 'loan_status': '{:.1%}'}), use_container_width=True)
|
| 268 |
-
|
| 269 |
-
st.subheader("Visualização Interativa dos Clusters")
|
| 270 |
-
# Scatter Plotly Interativo
|
| 271 |
-
fig_clus = px.scatter(
|
| 272 |
-
df, x='person_income', y='loan_amnt', color='Cluster',
|
| 273 |
-
title="Distribuição: Renda vs Empréstimo (por Cluster)",
|
| 274 |
-
hover_data=['person_age', 'loan_grade'],
|
| 275 |
-
range_x=[0, 200000] # Limite visual para facilitar
|
| 276 |
-
)
|
| 277 |
-
st.plotly_chart(fig_clus, use_container_width=True)
|
| 278 |
-
else:
|
| 279 |
-
st.warning("Clusterização não encontrada nos dados.")
|
| 280 |
|
| 281 |
-
#
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
with tab4:
|
| 285 |
-
st.header("V. Recomendações Gerenciais")
|
| 286 |
-
|
| 287 |
-
st.markdown("""
|
| 288 |
-
### 🚀 Plano de Ação Baseado em Dados
|
| 289 |
-
|
| 290 |
-
**1. Esteira de Crédito Híbrida (Modelo LightGBM)**
|
| 291 |
-
* **Faixa Verde (Risco < 20%):** Aprovação Automática. Foco em agilidade.
|
| 292 |
-
* **Faixa Cinza (20% - 60%):** Análise Humana. Solicitar comprovantes adicionais.
|
| 293 |
-
* **Faixa Vermelha (Risco > 60%):** Reprovação Automática. Proteção de capital.
|
| 294 |
-
|
| 295 |
-
**2. Políticas por Segmento (Clusters)**
|
| 296 |
-
* **Cluster Premium:** Ofertar taxas reduzidas para fidelização.
|
| 297 |
-
* **Cluster Jovem:** Limite de crédito reduzido inicial para construção de histórico.
|
| 298 |
-
* **Cluster Alavancado:** Bloqueio preventivo de novos créditos.
|
| 299 |
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
""")
|
| 304 |
|
| 305 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
import seaborn as sns
|
| 6 |
import shap
|
| 7 |
import numpy as np
|
| 8 |
+
import plotly.express as px
|
| 9 |
+
from sklearn.metrics import confusion_matrix, roc_curve, auc
|
| 10 |
|
| 11 |
+
# --- CONFIGURAÇÃO ---
|
| 12 |
st.set_page_config(page_title="CrediFast Risk System", layout="wide")
|
|
|
|
| 13 |
st.title("🏦 CrediFast: Sistema Integrado de Análise de Risco")
|
|
|
|
| 14 |
|
| 15 |
+
# --- CARREGAMENTO OTIMIZADO ---
|
| 16 |
@st.cache_data
|
| 17 |
def load_data():
|
| 18 |
return pd.read_csv("dados_credito_clean.csv")
|
| 19 |
|
| 20 |
@st.cache_resource
|
| 21 |
+
def load_system():
|
| 22 |
+
# Carrega o PACOTE COMPLETO (Modelos + Predições Prontas)
|
| 23 |
+
return joblib.load("sistema_risco_completo.pkl")
|
| 24 |
|
| 25 |
try:
|
| 26 |
df = load_data()
|
| 27 |
+
sistema = load_system()
|
| 28 |
+
|
| 29 |
+
# Desempacota
|
| 30 |
+
dict_modelos = sistema["modelos"]
|
| 31 |
+
y_test_real = sistema["y_test_real"]
|
| 32 |
+
# Pega nomes das colunas de uma amostra salva (mais seguro que hardcode)
|
| 33 |
+
feature_names = sistema["X_test_sample"].columns.tolist()
|
| 34 |
+
|
| 35 |
except FileNotFoundError:
|
| 36 |
+
st.error("⚠️ Arquivo 'sistema_risco_completo.pkl' não encontrado. Gere-o no notebook.")
|
| 37 |
st.stop()
|
| 38 |
|
| 39 |
+
# --- TABS ---
|
| 40 |
+
tab1, tab2, tab3, tab4 = st.tabs(["I. Diagnóstico", "II. Avaliação de Modelos", "IV. Clusterização", "V. Recomendações"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
+
# ... (ABA I MANTIDA IGUAL) ...
|
|
|
|
|
|
|
| 43 |
with tab1:
|
| 44 |
+
st.header("I. Diagnóstico Inicial")
|
| 45 |
+
st.metric("Total Clientes", len(df))
|
| 46 |
+
# ... (Seu código da Aba 1 aqui) ...
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
# =========================================================
|
| 49 |
+
# ABA II: AVALIAÇÃO INSTANTÂNEA (OTIMIZADA)
|
| 50 |
# =========================================================
|
| 51 |
with tab2:
|
| 52 |
+
st.header("II. Performance dos Modelos (Pré-Calculada)")
|
| 53 |
|
| 54 |
+
# 1. SELEÇÃO
|
| 55 |
+
model_names = list(dict_modelos.keys())
|
| 56 |
|
| 57 |
+
# Filtro de Categoria (Opcional, mas ajuda a organizar)
|
| 58 |
+
cats = ["Todos", "Boosting", "Árvores", "Outros"]
|
| 59 |
+
cat_filter = st.radio("Filtrar Tipo:", cats, horizontal=True)
|
| 60 |
|
| 61 |
+
if cat_filter == "Boosting":
|
| 62 |
+
model_names = [m for m in model_names if any(x in m for x in ['Light', 'XGB', 'Gradient', 'Ada'])]
|
| 63 |
+
elif cat_filter == "Árvores":
|
| 64 |
+
model_names = [m for m in model_names if 'Tree' in m or 'Forest' in m]
|
| 65 |
|
| 66 |
+
selected_model_name = st.selectbox("Selecione o Modelo para Análise Detalhada:", model_names)
|
| 67 |
+
|
| 68 |
+
# RECUPERA OS DADOS PRONTOS (Zero processamento!)
|
| 69 |
+
dados_modelo = dict_modelos[selected_model_name]
|
| 70 |
+
metrics = dados_modelo["metrics"]
|
| 71 |
+
y_pred_saved = dados_modelo["y_pred"]
|
| 72 |
+
y_proba_saved = dados_modelo["y_proba"]
|
| 73 |
+
current_model_obj = dados_modelo["modelo"] # Guardamos o objeto para o simulador
|
| 74 |
+
|
| 75 |
+
st.markdown("---")
|
| 76 |
+
|
| 77 |
+
# 2. DASHBOARD DE METRICAS
|
| 78 |
+
c1, c2, c3 = st.columns([1, 1, 2])
|
| 79 |
+
|
| 80 |
+
with c1:
|
| 81 |
+
st.subheader("Matriz de Confusão")
|
| 82 |
+
cm = confusion_matrix(y_test_real, y_pred_saved)
|
| 83 |
+
fig_cm = plt.figure(figsize=(5, 4))
|
| 84 |
+
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', cbar=False,
|
| 85 |
+
xticklabels=['Bom', 'Ruim'], yticklabels=['Bom', 'Ruim'])
|
| 86 |
+
plt.xlabel('Predito')
|
| 87 |
+
plt.ylabel('Real')
|
| 88 |
+
st.pyplot(fig_cm)
|
| 89 |
|
| 90 |
+
with c2:
|
| 91 |
+
st.subheader("Curva ROC")
|
| 92 |
+
if len(np.unique(y_test_real)) > 1:
|
| 93 |
+
fpr, tpr, _ = roc_curve(y_test_real, y_proba_saved)
|
| 94 |
+
fig_roc = plt.figure(figsize=(5, 4))
|
| 95 |
+
plt.plot(fpr, tpr, color='#ff7f0e', lw=2, label=f'AUC = {metrics["AUC"]:.3f}')
|
| 96 |
+
plt.plot([0, 1], [0, 1], color='navy', linestyle='--')
|
| 97 |
+
plt.legend(loc="lower right")
|
| 98 |
+
plt.grid(alpha=0.3)
|
| 99 |
+
st.pyplot(fig_roc)
|
| 100 |
else:
|
| 101 |
+
st.info("ROC indisponível")
|
| 102 |
+
|
| 103 |
+
with c3:
|
| 104 |
+
st.subheader("Indicadores de Performance")
|
| 105 |
+
# Mostra como KPIs grandes
|
| 106 |
+
k1, k2, k3, k4 = st.columns(4)
|
| 107 |
+
k1.metric("Recall (Risco)", f"{metrics['Recall']:.1%}", help="Capacidade de detectar calote")
|
| 108 |
+
k2.metric("Acurácia", f"{metrics['Acurácia']:.1%}")
|
| 109 |
+
k3.metric("F1-Score", f"{metrics['F1-Score']:.1%}")
|
| 110 |
+
k4.metric("AUC Global", f"{metrics['AUC']:.3f}")
|
|
|
|
|
|
|
| 111 |
|
| 112 |
+
st.markdown("**Interpretação:**")
|
| 113 |
+
if metrics['Recall'] > 0.80:
|
| 114 |
+
st.success(f"Este modelo é **Excelente** em detectar fraudes (Recall de {metrics['Recall']:.1%}). Ideal para proteção de capital.")
|
| 115 |
+
else:
|
| 116 |
+
st.warning(f"Este modelo deixa passar {1-metrics['Recall']:.1%} dos inadimplentes. Cuidado.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
+
# 3. SIMULADOR (Usa o objeto do modelo guardado)
|
| 119 |
+
st.divider()
|
| 120 |
+
st.subheader("🔮 Simulador Individual (Predição ao Vivo)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
+
# ... (Aqui entra o código do formulário de input que já fizemos) ...
|
| 123 |
+
# DICA: Use a variável 'feature_names' que carregamos lá em cima
|
| 124 |
+
# para criar o DataFrame de input com as colunas certas automaticamente!
|
|
|
|
| 125 |
|
| 126 |
+
# Exemplo simplificado de como usar feature_names no simulador:
|
| 127 |
+
# df_input = pd.DataFrame(0, index=[0], columns=feature_names)
|
| 128 |
+
# ... preenche os dados ...
|
| 129 |
+
# proba = current_model_obj.predict_proba(df_input)[0][1]
|