Spaces:
Sleeping
Sleeping
Upload 3 files
Browse files- AmesHousing.csv +0 -0
- app.py +238 -0
- requirements.txt +8 -3
AmesHousing.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
app.py
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Requisitos:
|
| 2 |
+
# pip install streamlit pandas numpy scipy statsmodels scikit-posthocs matplotlib seaborn
|
| 3 |
+
|
| 4 |
+
import warnings
|
| 5 |
+
warnings.filterwarnings("ignore")
|
| 6 |
+
|
| 7 |
+
import streamlit as st
|
| 8 |
+
import pandas as pd
|
| 9 |
+
import numpy as np
|
| 10 |
+
import matplotlib.pyplot as plt
|
| 11 |
+
import seaborn as sns
|
| 12 |
+
|
| 13 |
+
from scipy import stats
|
| 14 |
+
import statsmodels.api as sm
|
| 15 |
+
from statsmodels.formula.api import ols
|
| 16 |
+
from statsmodels.stats.multicomp import pairwise_tukeyhsd
|
| 17 |
+
from statsmodels.stats.oneway import anova_oneway # Necessário para Welch ANOVA
|
| 18 |
+
|
| 19 |
+
import scikit_posthocs as sp # Necessário para Dunn Post-hoc
|
| 20 |
+
|
| 21 |
+
# 1. Configuração da Página e Título
|
| 22 |
+
st.set_page_config(layout="wide")
|
| 23 |
+
st.title("🏡 Análise Comparativa de Preços de Imóveis (Ames Housing)")
|
| 24 |
+
st.markdown("""
|
| 25 |
+
Dashboard interativo para explorar a relação entre variáveis categóricas
|
| 26 |
+
(Bairro, Qualidade, Lareiras) e o **SalePrice** (Preço de Venda)
|
| 27 |
+
usando Análise de Variância (ANOVA) e testes não-paramétricos.
|
| 28 |
+
""")
|
| 29 |
+
|
| 30 |
+
# 2. Definição das Colunas/Caminhos
|
| 31 |
+
Y_COL = "SalePrice"
|
| 32 |
+
CAT_COLS = ["Neighborhood", "OverallQual", "Fireplaces"]
|
| 33 |
+
# ATENÇÃO: Substitua o caminho abaixo pelo caminho correto do seu arquivo CSV
|
| 34 |
+
DATA_PATH = r"C:\Users\felip\Downloads\AmesHousing.csv.csv"
|
| 35 |
+
|
| 36 |
+
# -----------------------------------------------------------
|
| 37 |
+
# 1) Carregar e Pré-processar Dataset com Caching
|
| 38 |
+
# -----------------------------------------------------------
|
| 39 |
+
@st.cache_data # Crucial para performance!
|
| 40 |
+
def load_and_preprocess_data(file_path, y_col, cat_cols):
|
| 41 |
+
"""Carrega, pré-processa e retorna o DataFrame."""
|
| 42 |
+
try:
|
| 43 |
+
df = pd.read_csv(file_path, low_memory=False)
|
| 44 |
+
except FileNotFoundError:
|
| 45 |
+
st.error(f"Erro: Arquivo não encontrado no caminho: {file_path}")
|
| 46 |
+
return pd.DataFrame()
|
| 47 |
+
|
| 48 |
+
# Seu código original de pré-processamento
|
| 49 |
+
if "Id" in df.columns:
|
| 50 |
+
df = df.drop(columns=["Id"])
|
| 51 |
+
|
| 52 |
+
# Verifica a existência das colunas
|
| 53 |
+
missing_cols = [c for c in [y_col] + cat_cols if c not in df.columns]
|
| 54 |
+
if missing_cols:
|
| 55 |
+
st.error(f"Colunas esperadas não encontradas no CSV: {', '.join(missing_cols)}")
|
| 56 |
+
return pd.DataFrame()
|
| 57 |
+
|
| 58 |
+
# Seleção de colunas, remoção de NA e conversão de tipos
|
| 59 |
+
df = df[[y_col] + cat_cols].copy()
|
| 60 |
+
df = df.dropna(subset=[y_col] + cat_cols)
|
| 61 |
+
df["Neighborhood"] = df["Neighborhood"].astype(str)
|
| 62 |
+
df["Fireplaces"] = df["Fireplaces"].astype(str)
|
| 63 |
+
df["OverallQual"] = df["OverallQual"].astype(str) # Tratar como string para ANOVA
|
| 64 |
+
|
| 65 |
+
return df
|
| 66 |
+
|
| 67 |
+
# --- Chamada da função de carregamento ---
|
| 68 |
+
df = load_and_preprocess_data(DATA_PATH, Y_COL, CAT_COLS)
|
| 69 |
+
|
| 70 |
+
if df.empty:
|
| 71 |
+
st.stop()
|
| 72 |
+
|
| 73 |
+
# -----------------------------------------------------------
|
| 74 |
+
# 3) Funções auxiliares de teste (Mantidas)
|
| 75 |
+
# -----------------------------------------------------------
|
| 76 |
+
|
| 77 |
+
def check_normality_by_group(data, group_col, value_col, alpha=0.05):
|
| 78 |
+
"""Shapiro-Wilk por grupo; retorna DataFrame com p-values e decisão"""
|
| 79 |
+
results = []
|
| 80 |
+
groups = data[group_col].unique()
|
| 81 |
+
for g in sorted(groups):
|
| 82 |
+
vals = data.loc[data[group_col]==g, value_col].values
|
| 83 |
+
# Shapiro requer n between 3 and 5000
|
| 84 |
+
if len(vals) < 3:
|
| 85 |
+
p = np.nan
|
| 86 |
+
stat = np.nan
|
| 87 |
+
decision = "n<3"
|
| 88 |
+
else:
|
| 89 |
+
if len(vals) > 5000:
|
| 90 |
+
vals_sample = np.random.choice(vals, 5000, replace=False)
|
| 91 |
+
else:
|
| 92 |
+
vals_sample = vals
|
| 93 |
+
stat, p = stats.shapiro(vals_sample)
|
| 94 |
+
decision = "normal" if p > alpha else "not_normal"
|
| 95 |
+
results.append({"group": g, "n": len(vals), "shapiro_stat": stat, "shapiro_p": p, "decision": decision})
|
| 96 |
+
return pd.DataFrame(results)
|
| 97 |
+
|
| 98 |
+
def levene_test(data, group_col, value_col):
|
| 99 |
+
"""Levene test para homocedasticidade."""
|
| 100 |
+
groups = [data.loc[data[group_col]==g, value_col].values for g in data[group_col].unique()]
|
| 101 |
+
stat, p = stats.levene(*groups, center='median')
|
| 102 |
+
return stat, p
|
| 103 |
+
|
| 104 |
+
def anderson_darling_overall(data, value_col):
|
| 105 |
+
"""Anderson-Darling test para normalidade global."""
|
| 106 |
+
res = stats.anderson(data[value_col].values, dist='norm')
|
| 107 |
+
return res
|
| 108 |
+
|
| 109 |
+
# ------------------------------------------------------------------
|
| 110 |
+
# 4. Lógica Principal: Interatividade e Análise
|
| 111 |
+
# ------------------------------------------------------------------
|
| 112 |
+
|
| 113 |
+
# 4.1. Seletor de Variável na Sidebar (Interatividade)
|
| 114 |
+
st.sidebar.header("Variável a Analisar")
|
| 115 |
+
|
| 116 |
+
selected_cat = st.sidebar.selectbox(
|
| 117 |
+
"Selecione a Variável Categórica:",
|
| 118 |
+
options=CAT_COLS,
|
| 119 |
+
help="Escolha qual variável de agrupamento será analisada em relação ao SalePrice."
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
# Definir as variáveis para a análise (substitui o loop for)
|
| 123 |
+
cat = selected_cat
|
| 124 |
+
y_col = Y_COL
|
| 125 |
+
|
| 126 |
+
st.header(f"Análise: {cat} vs {y_col}")
|
| 127 |
+
st.markdown("---")
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
# Boxplot
|
| 131 |
+
st.subheader("1. Visualização: Boxplot")
|
| 132 |
+
st.markdown(f"Distribuição de `{y_col}` por categoria em `{cat}` (ordenado pela mediana).")
|
| 133 |
+
|
| 134 |
+
# Garante que o gráfico seja desenhado em uma nova figura para o Streamlit
|
| 135 |
+
fig, ax = plt.subplots(figsize=(10, 6))
|
| 136 |
+
order = df.groupby(cat)[y_col].median().sort_values(ascending=False).index
|
| 137 |
+
sns.boxplot(x=cat, y=y_col, data=df, order=order, ax=ax)
|
| 138 |
+
ax.set_title(f"{y_col} por {cat}")
|
| 139 |
+
plt.xticks(rotation=45)
|
| 140 |
+
plt.tight_layout()
|
| 141 |
+
|
| 142 |
+
st.pyplot(fig) # Comando Streamlit para exibir o gráfico
|
| 143 |
+
|
| 144 |
+
# Testes de pressupostos
|
| 145 |
+
st.subheader("2. Testes de Pressupostos (Homogeneidade e Normalidade)")
|
| 146 |
+
|
| 147 |
+
# Normalidade
|
| 148 |
+
st.markdown("##### Teste de Normalidade (Shapiro-Wilk) por Grupo")
|
| 149 |
+
sh = check_normality_by_group(df, cat, y_col)
|
| 150 |
+
st.dataframe(sh.head(20), use_container_width=True)
|
| 151 |
+
|
| 152 |
+
# Anderson-Darling (Global)
|
| 153 |
+
ad = anderson_darling_overall(df, y_col)
|
| 154 |
+
st.info(f"**Anderson-Darling (Global):** stat={ad.statistic:.4f}. Valores críticos: {ad.critical_values} (Níveis de Significância: {ad.significance_level}%)")
|
| 155 |
+
|
| 156 |
+
# Homocedasticidade (Levene)
|
| 157 |
+
st.markdown("##### Teste de Homocedasticidade (Levene)")
|
| 158 |
+
stat_levene, p_levene = levene_test(df, cat, y_col)
|
| 159 |
+
st.write(f"**Levene test (center=median):** Estatística={stat_levene:.4f}, p-valor={p_levene:.4f}")
|
| 160 |
+
|
| 161 |
+
# --------------------------------------------------------------------
|
| 162 |
+
# 3. Análise Estatística (ANOVA / Welch / Kruskal)
|
| 163 |
+
# --------------------------------------------------------------------
|
| 164 |
+
|
| 165 |
+
st.subheader("3. Análise Estatística e Post-Hoc")
|
| 166 |
+
|
| 167 |
+
# ANOVA clássica (one-way)
|
| 168 |
+
try:
|
| 169 |
+
model = ols(f"{y_col} ~ C({cat})", data=df).fit()
|
| 170 |
+
anova_table = sm.stats.anova_lm(model, typ=2)
|
| 171 |
+
st.markdown("##### ANOVA (Type II) results:")
|
| 172 |
+
st.dataframe(anova_table)
|
| 173 |
+
|
| 174 |
+
anova_p = anova_table.loc[f"C({cat})", "PR(>F)"] if f"C({cat})" in anova_table.index else anova_table.iloc[0,3]
|
| 175 |
+
except Exception as e:
|
| 176 |
+
st.error(f"Erro ao rodar ANOVA clássica: {e}")
|
| 177 |
+
anova_p = 1.0 # Define um p-valor alto para não rodar o Tukey
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
# Lógica de Testes Robustos / Não-Paramétricos
|
| 181 |
+
non_normal_groups = sh[sh["decision"]=="not_normal"]
|
| 182 |
+
prop_non_normal = len(non_normal_groups) / len(sh)
|
| 183 |
+
|
| 184 |
+
col1, col2 = st.columns(2)
|
| 185 |
+
|
| 186 |
+
with col1:
|
| 187 |
+
# Teste de Homocedasticidade
|
| 188 |
+
if p_levene < 0.05:
|
| 189 |
+
st.warning("⚠️ **Alerta:** Levene $p < 0.05$ (Variâncias Heterogêneas). Aplicando **Welch ANOVA**.")
|
| 190 |
+
try:
|
| 191 |
+
welch_res = anova_oneway(df[y_col], df[cat], use_var='unequal')
|
| 192 |
+
st.code(f"Welch ANOVA: F={welch_res.fvalue:.4f}, p={welch_res.pvalue:.4f}")
|
| 193 |
+
except Exception as e:
|
| 194 |
+
st.error(f"Erro ao rodar anova_oneway: {e}")
|
| 195 |
+
else:
|
| 196 |
+
st.success("✅ **Pressuposto OK:** Variâncias homogêneas (Levene $p \ge 0.05$).")
|
| 197 |
+
|
| 198 |
+
with col2:
|
| 199 |
+
# Teste de Normalidade / Kruskal-Wallis
|
| 200 |
+
if prop_non_normal > 0.3:
|
| 201 |
+
st.warning(f"⚠️ **Alerta:** {prop_non_normal:.0%} dos grupos rejeitam normalidade. Aplicando **Kruskal-Wallis** (Teste não-paramétrico).")
|
| 202 |
+
groups = [df.loc[df[cat]==g, y_col].values for g in df[cat].unique()]
|
| 203 |
+
try:
|
| 204 |
+
kw_stat, kw_p = stats.kruskal(*groups)
|
| 205 |
+
st.code(f"Kruskal-Wallis: Stat={kw_stat:.4f}, p={kw_p:.6f}")
|
| 206 |
+
if kw_p < 0.05:
|
| 207 |
+
st.info("Kruskal-Wallis indica diferença significativa.")
|
| 208 |
+
|
| 209 |
+
# Post-hoc Dunn
|
| 210 |
+
st.markdown("###### Post-hoc Dunn (Bonferroni)")
|
| 211 |
+
dunn = sp.posthoc_dunn(df, val_col=y_col, group_col=cat, p_adjust='bonferroni')
|
| 212 |
+
st.dataframe(dunn, use_container_width=True)
|
| 213 |
+
except Exception as e:
|
| 214 |
+
st.error(f"Erro ao rodar Kruskal-Wallis: {e}")
|
| 215 |
+
else:
|
| 216 |
+
st.success(f"✅ **Pressuposto OK:** Baixa rejeição de normalidade ({prop_non_normal:.0%}).")
|
| 217 |
+
|
| 218 |
+
# Teste Post-hoc Tukey (se ANOVA clássica for significativa)
|
| 219 |
+
if anova_p < 0.05:
|
| 220 |
+
st.markdown("##### Post-hoc Tukey HSD (Se ANOVA Signif.)")
|
| 221 |
+
st.info("ANOVA clássica indica diferenças. Aplicando Tukey HSD.")
|
| 222 |
+
tukey = pairwise_tukeyhsd(endog=df[y_col], groups=df[cat], alpha=0.05)
|
| 223 |
+
st.text(tukey.summary()) # st.text é melhor para summaries de modelos
|
| 224 |
+
else:
|
| 225 |
+
st.info("ANOVA NÃO indicou diferenças estatisticamente significativas entre categorias.")
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
# --------------------------------------------------------------------
|
| 229 |
+
# 4. Resumo Final
|
| 230 |
+
# --------------------------------------------------------------------
|
| 231 |
+
|
| 232 |
+
st.subheader("4. Resumo por Categoria")
|
| 233 |
+
st.markdown("Medidas descritivas do preço de venda agrupadas pela categoria selecionada, ordenadas pela média.")
|
| 234 |
+
summary = df.groupby(cat)[y_col].agg(['count','mean','median','std']).sort_values('mean', ascending=False)
|
| 235 |
+
st.dataframe(summary, use_container_width=True)
|
| 236 |
+
|
| 237 |
+
st.markdown("---")
|
| 238 |
+
st.success("Análise concluída. Utilize o seletor na barra lateral para trocar de variável.")
|
requirements.txt
CHANGED
|
@@ -1,3 +1,8 @@
|
|
| 1 |
-
|
| 2 |
-
pandas
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
streamlit
|
| 2 |
+
pandas
|
| 3 |
+
numpy
|
| 4 |
+
scipy
|
| 5 |
+
statsmodels
|
| 6 |
+
scikit-posthocs
|
| 7 |
+
matplotlib
|
| 8 |
+
seaborn
|