Spaces:
Sleeping
Sleeping
ricardoadriano commited on
Commit ·
c4616a2
1
Parent(s): c59760d
pasta dados
Browse files- Dados/AmesHousing.csv +0 -0
- dados +0 -0
- requirements.txt +10 -3
- src/streamlit_app.py +165 -38
Dados/AmesHousing.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
dados
DELETED
|
File without changes
|
requirements.txt
CHANGED
|
@@ -1,3 +1,10 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pandas==1.5.3
|
| 2 |
+
geopandas==0.10.2
|
| 3 |
+
matplotlib==3.6.3
|
| 4 |
+
seaborn==0.11.2
|
| 5 |
+
plotly==5.3.0
|
| 6 |
+
Pillow==9.2.0
|
| 7 |
+
scipy==1.9.3
|
| 8 |
+
statsmodels==0.13.5
|
| 9 |
+
wordcloud==1.9.2
|
| 10 |
+
numpy==1.24.0
|
src/streamlit_app.py
CHANGED
|
@@ -1,40 +1,167 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
|
| 7 |
-
#
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
"""
|
| 15 |
-
|
| 16 |
-
num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
|
| 17 |
-
num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
|
| 18 |
-
|
| 19 |
-
indices = np.linspace(0, 1, num_points)
|
| 20 |
-
theta = 2 * np.pi * num_turns * indices
|
| 21 |
-
radius = indices
|
| 22 |
-
|
| 23 |
-
x = radius * np.cos(theta)
|
| 24 |
-
y = radius * np.sin(theta)
|
| 25 |
-
|
| 26 |
-
df = pd.DataFrame({
|
| 27 |
-
"x": x,
|
| 28 |
-
"y": y,
|
| 29 |
-
"idx": indices,
|
| 30 |
-
"rand": np.random.randn(num_points),
|
| 31 |
-
})
|
| 32 |
-
|
| 33 |
-
st.altair_chart(alt.Chart(df, height=700, width=700)
|
| 34 |
-
.mark_point(filled=True)
|
| 35 |
-
.encode(
|
| 36 |
-
x=alt.X("x", axis=None),
|
| 37 |
-
y=alt.Y("y", axis=None),
|
| 38 |
-
color=alt.Color("idx", legend=None, scale=alt.Scale()),
|
| 39 |
-
size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
|
| 40 |
-
))
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# coding: utf-8
|
| 3 |
+
|
| 4 |
+
# =====================================================
|
| 5 |
+
# Dashboard - Testes de Hipóteses com AmesHousing
|
| 6 |
+
# =====================================================
|
| 7 |
+
|
| 8 |
import streamlit as st
|
| 9 |
+
import pandas as pd
|
| 10 |
+
import matplotlib.pyplot as plt
|
| 11 |
+
import seaborn as sns
|
| 12 |
+
import plotly.express as px
|
| 13 |
+
import numpy as np
|
| 14 |
+
|
| 15 |
+
from scipy import stats
|
| 16 |
+
from scipy.stats import shapiro, levene, kruskal
|
| 17 |
+
from statsmodels.formula.api import ols
|
| 18 |
+
import statsmodels.api as sm
|
| 19 |
+
|
| 20 |
+
# -----------------------------------------------------
|
| 21 |
+
# Configuração da Página
|
| 22 |
+
# -----------------------------------------------------
|
| 23 |
+
st.set_page_config(
|
| 24 |
+
page_title="Dashboard - Testes de Hipóteses com AmesHousing",
|
| 25 |
+
layout="wide",
|
| 26 |
+
initial_sidebar_state="expanded"
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
st.markdown("<h1 style='text-align:center;color:#003366;'>Simulador de Testes de Hipótese</h1>", unsafe_allow_html=True)
|
| 30 |
+
st.markdown("<h3 style='text-align:center;color:#003366;'>Análise do Dataset AmesHousing</h3>", unsafe_allow_html=True)
|
| 31 |
+
st.markdown("---")
|
| 32 |
+
|
| 33 |
+
# -----------------------------------------------------
|
| 34 |
+
# Abas do Dashboard
|
| 35 |
+
# -----------------------------------------------------
|
| 36 |
+
tabs = st.tabs(["Simulações Teóricas", "Análise AmesHousing"])
|
| 37 |
+
|
| 38 |
+
# -----------------------------------------------------
|
| 39 |
+
# Aba 1: Simulações Teóricas (mantida)
|
| 40 |
+
# -----------------------------------------------------
|
| 41 |
+
with tabs[0]:
|
| 42 |
+
st.subheader("Teste de Hipótese para Proporção de Testes Positivos de COVID-19")
|
| 43 |
+
|
| 44 |
+
st.sidebar.markdown("### Parâmetros do Teste (Proporção)")
|
| 45 |
+
p_pop = st.sidebar.slider("Proporção populacional (H0)", 0.0, 1.0, 0.1, 0.01, key="p_pop")
|
| 46 |
+
p_sample = st.sidebar.slider("Proporção amostral", 0.0, 1.0, 0.12, 0.01, key="p_sample")
|
| 47 |
+
n = st.sidebar.slider("Tamanho da amostra", 100, 10000, 1000, 10, key="n_sample")
|
| 48 |
+
alpha_prop = st.sidebar.slider("Nível de significância (α)", 0.01, 0.10, 0.05, 0.01, key="alpha_prop")
|
| 49 |
+
|
| 50 |
+
se = np.sqrt(p_pop*(1-p_pop)/n)
|
| 51 |
+
z = (p_sample - p_pop)/se
|
| 52 |
+
p_value = 2*(1 - stats.norm.cdf(abs(z)))
|
| 53 |
+
|
| 54 |
+
st.write(f"**Z** = {z:.4f}")
|
| 55 |
+
st.write(f"**p-valor** = {p_value:.4f}")
|
| 56 |
+
if p_value < alpha_prop:
|
| 57 |
+
st.write("**Rejeitamos H0**: diferença significativa.")
|
| 58 |
+
else:
|
| 59 |
+
st.write("**Não rejeitamos H0**: sem diferença significativa.")
|
| 60 |
+
|
| 61 |
+
# -----------------------------------------------------
|
| 62 |
+
# Aba 2: Análise AmesHousing
|
| 63 |
+
# -----------------------------------------------------
|
| 64 |
+
with tabs[1]:
|
| 65 |
+
st.subheader("Análise de Variância - AmesHousing Dataset")
|
| 66 |
+
st.markdown("---")
|
| 67 |
+
|
| 68 |
+
# Upload ou leitura local
|
| 69 |
+
uploaded_file = st.file_uploader("Carregue o arquivo AmesHousing.csv", type=["csv"])
|
| 70 |
+
if uploaded_file is not None:
|
| 71 |
+
casa_data = pd.read_csv(uploaded_file)
|
| 72 |
+
else:
|
| 73 |
+
try:
|
| 74 |
+
casa_data = pd.read_csv("Dados/AmesHousing.csv")
|
| 75 |
+
except:
|
| 76 |
+
st.error("⚠️ Carregue o arquivo AmesHousing.csv para continuar.")
|
| 77 |
+
st.stop()
|
| 78 |
+
|
| 79 |
+
# Renomear colunas para evitar problemas com espaços
|
| 80 |
+
casa_data.columns = casa_data.columns.str.strip().str.replace(" ", "_")
|
| 81 |
+
|
| 82 |
+
# -------------------------------------------------
|
| 83 |
+
# Análise Exploratória
|
| 84 |
+
# -------------------------------------------------
|
| 85 |
+
st.markdown("### Distribuição do Preço de Venda")
|
| 86 |
+
fig, ax = plt.subplots(figsize=(8,5))
|
| 87 |
+
sns.histplot(casa_data['SalePrice'], kde=True, ax=ax)
|
| 88 |
+
ax.set_title("Distribuição do Preço de Venda")
|
| 89 |
+
st.pyplot(fig)
|
| 90 |
+
|
| 91 |
+
# Boxplots
|
| 92 |
+
st.markdown("### Boxplots das Variáveis Selecionadas")
|
| 93 |
+
variavel = st.selectbox("Escolha a variável categórica para comparar preços:",
|
| 94 |
+
["Neighborhood","Garage_Type","Fireplaces"])
|
| 95 |
+
|
| 96 |
+
fig2, ax2 = plt.subplots(figsize=(12,6))
|
| 97 |
+
sns.boxplot(x=variavel, y="SalePrice", data=casa_data, ax=ax2)
|
| 98 |
+
plt.xticks(rotation=90)
|
| 99 |
+
ax2.set_title(f"Preço de Venda por {variavel}")
|
| 100 |
+
st.pyplot(fig2)
|
| 101 |
+
|
| 102 |
+
# Scatter interativo (média de preço por bairro)
|
| 103 |
+
st.markdown("### Preço Médio de Venda por Bairro")
|
| 104 |
+
bairro_grouped = casa_data.groupby('Neighborhood').agg(
|
| 105 |
+
count=('SalePrice','size'),
|
| 106 |
+
mean_price=('SalePrice','mean')
|
| 107 |
+
).reset_index()
|
| 108 |
+
|
| 109 |
+
bairro_filtered = bairro_grouped[bairro_grouped['count'] >= 5]
|
| 110 |
+
fig3 = px.scatter(
|
| 111 |
+
bairro_filtered,
|
| 112 |
+
x='mean_price',
|
| 113 |
+
y='Neighborhood',
|
| 114 |
+
size='count',
|
| 115 |
+
color='Neighborhood',
|
| 116 |
+
title='Preço Médio de Venda vs Bairro (Ames, Iowa)',
|
| 117 |
+
labels={'mean_price': 'Preço Médio de Venda', 'Neighborhood':'Bairro'},
|
| 118 |
+
opacity=0.8
|
| 119 |
+
)
|
| 120 |
+
st.plotly_chart(fig3, use_container_width=True)
|
| 121 |
+
|
| 122 |
+
# -------------------------------------------------
|
| 123 |
+
# ANOVA
|
| 124 |
+
# -------------------------------------------------
|
| 125 |
+
st.markdown("### ANOVA para Neighborhood, Garage_Type e Fireplaces")
|
| 126 |
+
alpha = st.sidebar.slider("Nível de significância (α) - ANOVA AmesHousing",
|
| 127 |
+
0.01,0.10,0.05,0.01,key="alpha_ames")
|
| 128 |
+
|
| 129 |
+
modelos = {
|
| 130 |
+
"Neighborhood": ols('SalePrice ~ C(Neighborhood)', data=casa_data).fit(),
|
| 131 |
+
"Garage_Type": ols('SalePrice ~ C(Garage_Type)', data=casa_data).fit(),
|
| 132 |
+
"Fireplaces": ols('SalePrice ~ C(Fireplaces)', data=casa_data).fit()
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
for nome, modelo in modelos.items():
|
| 136 |
+
st.markdown(f"#### ANOVA - {nome}")
|
| 137 |
+
anova = sm.stats.anova_lm(modelo, typ=2)
|
| 138 |
+
st.dataframe(anova)
|
| 139 |
+
|
| 140 |
+
# -------------------------------------------------
|
| 141 |
+
# Validação dos Pressupostos
|
| 142 |
+
# -------------------------------------------------
|
| 143 |
+
st.markdown("### Validação dos Pressupostos da ANOVA")
|
| 144 |
+
|
| 145 |
+
st.markdown("#### Teste de Normalidade (Shapiro-Wilk)")
|
| 146 |
+
for nome, modelo in modelos.items():
|
| 147 |
+
residuos = modelo.resid
|
| 148 |
+
stat, p = shapiro(residuos.dropna())
|
| 149 |
+
st.write(f"{nome}: estatística={stat:.3f}, p={p:.3f} ➡️ "
|
| 150 |
+
+ ("resíduos normais" if p >= alpha else "violação de normalidade"))
|
| 151 |
+
|
| 152 |
+
st.markdown("#### Teste de Homocedasticidade (Levene)")
|
| 153 |
+
for nome in ["Neighborhood","Garage_Type","Fireplaces"]:
|
| 154 |
+
grupos = [grupo["SalePrice"].dropna() for _, grupo in casa_data.groupby(nome)]
|
| 155 |
+
stat, p = levene(*grupos)
|
| 156 |
+
st.write(f"{nome}: estatística={stat:.3f}, p={p:.3f} ➡️ "
|
| 157 |
+
+ ("variâncias iguais" if p >= alpha else "variâncias diferentes"))
|
| 158 |
|
| 159 |
+
# -------------------------------------------------
|
| 160 |
+
# Kruskal-Wallis
|
| 161 |
+
# -------------------------------------------------
|
| 162 |
+
st.markdown("### Teste não-paramétrico (Kruskal-Wallis)")
|
| 163 |
+
for nome in ["Neighborhood","Garage_Type","Fireplaces"]:
|
| 164 |
+
grupos = [grupo["SalePrice"].dropna() for _, grupo in casa_data.groupby(nome)]
|
| 165 |
+
stat, p = kruskal(*grupos)
|
| 166 |
+
st.write(f"{nome}: estatística={stat:.3f}, p={p:.3f} ➡️ "
|
| 167 |
+
+ ("diferenças significativas" if p < alpha else "sem diferença significativa"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|