joaogabrielsouza commited on
Commit
ae43eb7
·
1 Parent(s): 7b49dc1

Nova Correção: sincroniza local com Teste_Hipoteses

Browse files
Dashboard_Teste_de_Hipoteses.py DELETED
@@ -1,130 +0,0 @@
1
- #!/usr/bin/env python
2
- # coding: utf-8
3
-
4
- # ![MARCADOR.png](attachment:MARCADOR.png)
5
-
6
- # # BI - Teste de Hipóteses
7
-
8
- # ## Bibliotecas
9
-
10
- # In[1]:
11
-
12
-
13
- import streamlit as st
14
- import pandas as pd
15
- import numpy as np
16
- import plotly.express as px
17
- import plotly.graph_objects as go
18
- from PIL import Image
19
- import seaborn as sns
20
- import matplotlib.pyplot as plt
21
- from scipy import stats
22
- from statsmodels.formula.api import ols
23
- import statsmodels.api as sm
24
- from bioinfokit.analys import stat
25
- import subprocess
26
-
27
-
28
- # ### Dashboard
29
-
30
- # In[2]:
31
-
32
-
33
- # Configuração da página
34
- st.set_page_config(page_title="Teste de Hipótese - Exemplo Interativo",
35
- layout="wide",
36
- initial_sidebar_state="expanded")
37
-
38
- # Slider CSS customization for green color
39
- st.markdown(
40
- """
41
- <style>
42
- .stSlider > div > div > div > div > div > div {
43
- background-color: #4CAF50 !important; /* Verde para o slider */
44
- }
45
- </style>
46
- """,
47
- unsafe_allow_html=True,
48
- )
49
-
50
- # Carregar as logos
51
- logo_unb = Image.open("Logo/MARCADOR.png")
52
-
53
-
54
- # Título e Logos
55
- col1, col2, col3 = st.columns([1, 6, 1])
56
- with col1:
57
- st.image(logo_unb, use_column_width=True)
58
- with col2:
59
- st.markdown("<h1 style='text-align: center; color: #003366;'>Simulador Acadêmico de Testes de Hipótese</h1>",
60
- unsafe_allow_html=True)
61
- st.markdown("<h3 style='text-align: center; color: #003366;'>Professor João Gabriel de Moraes Souza</h3>",
62
- unsafe_allow_html=True) # Inserir nome do professor
63
- with col3:
64
- st.image(logo_unb, use_column_width=True)
65
-
66
- st.markdown("---")
67
-
68
- # Criação de abas
69
- tabs = st.tabs(["Simulações Teóricas"])
70
-
71
- # Aba 1: Simulações Teóricas
72
- with tabs[0]:
73
- st.subheader("Teste de Hipótese para Proporção de Testes Positivos de COVID-19")
74
-
75
- # Sliders para definir os parâmetros do teste (apenas na aba de simulações teóricas)
76
- st.sidebar.markdown("### Parâmetros do Teste de Hipótese")
77
- p_pop = st.sidebar.slider("Proporção populacional esperada (H0)", min_value=0.0, max_value=1.0, value=0.1, step=0.01)
78
- p_sample = st.sidebar.slider("Proporção observada na amostra", min_value=0.0, max_value=1.0, value=0.12, step=0.01)
79
- n = st.sidebar.slider("Tamanho da amostra", min_value=100, max_value=10000, value=1000, step=10)
80
- alpha = st.sidebar.slider("Nível de significância (α)", min_value=0.01, max_value=0.10, value=0.05, step=0.01)
81
-
82
- # Cálculo do teste z para proporção
83
- se = np.sqrt(p_pop * (1 - p_pop) / n)
84
- z = (p_sample - p_pop) / se
85
- p_value = 2 * (1 - stats.norm.cdf(abs(z))) # Teste bilateral
86
-
87
- # Resultados
88
- st.write(f"**Estatística Z**: {z:.4f}")
89
- st.write(f"**Valor-p**: {p_value:.4f}")
90
- if p_value < alpha:
91
- st.write("**Conclusão**: Rejeitamos H0. A proporção observada é significativamente diferente da proporção esperada.")
92
- else:
93
- st.write("**Conclusão**: Não rejeitamos H0. A proporção observada não é significativamente diferente da proporção esperada.")
94
-
95
- # Gráfico da distribuição normal com regiões de aceitação/rejeição
96
- x = np.linspace(p_pop - 4*se, p_pop + 4*se, 1000)
97
- y = stats.norm.pdf(x, p_pop, se)
98
-
99
- fig = go.Figure()
100
-
101
- # Linha de densidade da distribuição
102
- fig.add_trace(go.Scatter(x=x, y=y, mode='lines', line=dict(color='blue'), name='Distribuição Normal'))
103
-
104
- # Adicionar linha para a proporção da amostra
105
- fig.add_vline(x=p_sample, line=dict(color='red', width=2), name='Proporção Observada')
106
-
107
- # Região crítica (baseado em alpha)
108
- z_critical = stats.norm.ppf(1 - alpha / 2)
109
- left_critical_value = p_pop - z_critical * se
110
- right_critical_value = p_pop + z_critical * se
111
- fig.add_vrect(x0=left_critical_value, x1=-4*se+p_pop, fillcolor="red", opacity=0.2, line_width=0)
112
- fig.add_vrect(x0=right_critical_value, x1=4*se+p_pop, fillcolor="red", opacity=0.2, line_width=0)
113
-
114
- # Layout do gráfico
115
- fig.update_layout(title="Distribuição Normal e Região Crítica",
116
- xaxis_title="Valores",
117
- yaxis_title="Densidade",
118
- showlegend=False,
119
- plot_bgcolor="white")
120
-
121
- st.plotly_chart(fig, use_container_width=True)
122
-
123
- # Exibir explicações
124
- st.markdown("### Explicação:")
125
- st.write("O teste de hipótese avalia se a proporção de testes positivos de COVID-19 na amostra difere significativamente da proporção esperada na população.")
126
- st.write("Usamos o valor-p para decidir se rejeitamos ou não a hipótese nula (H0). Se o valor-p for menor que o nível de significância (α), rejeitamos H0.")
127
-
128
-
129
-
130
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Dashboard_Teste_de_Hipoteses_online.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding: utf-8
3
+
4
+ # ![MARCADOR.png](attachment:6a5bbf7a-f8d3-47a9-ba39-ab0469dd97f3.png)
5
+
6
+ # # BI - Teste de Hipóteses
7
+
8
+ # ## Bibliotecas
9
+
10
+ # In[1]:
11
+
12
+
13
+ import streamlit as st
14
+ import pandas as pd
15
+ import geopandas as gpd
16
+ import matplotlib.pyplot as plt
17
+ import seaborn as sns
18
+ import plotly.express as px
19
+ import plotly.graph_objects as go
20
+ from PIL import Image
21
+ from scipy import stats
22
+ from scipy.stats import shapiro, levene, kruskal, mannwhitneyu, wilcoxon
23
+ from statsmodels.formula.api import ols
24
+ import statsmodels.api as sm
25
+ from statsmodels.stats.multicomp import pairwise_tukeyhsd
26
+ from wordcloud import WordCloud
27
+ import numpy as np
28
+ import subprocess
29
+
30
+
31
+ # ### Dashboard
32
+
33
+ # In[2]:
34
+
35
+
36
+ # Configuração da página
37
+ st.set_page_config(
38
+ page_title="Teste de Hipótese & Chocolate",
39
+ layout="wide",
40
+ initial_sidebar_state="expanded"
41
+ )
42
+
43
+ # CSS para slider verde
44
+ st.markdown("""
45
+ <style>
46
+ .stSlider > div > div > div > div > div > div {
47
+ background-color: #4CAF50 !important;
48
+ }
49
+ </style>
50
+ """, unsafe_allow_html=True)
51
+
52
+ # Carregar logo
53
+ logo = Image.open("Logo/MARCADOR.png")
54
+
55
+ # Cabeçalho
56
+ col1, col2, col3 = st.columns([1,6,1])
57
+ with col1:
58
+ st.image(logo, use_column_width=True)
59
+ with col2:
60
+ st.markdown("<h1 style='text-align:center;color:#003366;'>Simulador de Testes de Hipótese</h1>", unsafe_allow_html=True)
61
+ st.markdown("<h3 style='text-align:center;color:#003366;'>Professor João Gabriel de Moraes Souza</h3>", unsafe_allow_html=True)
62
+ with col3:
63
+ st.image(logo, use_column_width=True)
64
+
65
+ st.markdown("---")
66
+
67
+ # Abas
68
+ tabs = st.tabs(["Simulações Teóricas", "Análise de Chocolate"])
69
+
70
+ # Aba 1: Simulações Teóricas
71
+ with tabs[0]:
72
+ st.subheader("Teste de Hipótese para Proporção de Testes Positivos de COVID-19")
73
+ st.sidebar.markdown("### Parâmetros do Teste")
74
+ p_pop = st.sidebar.slider("Proporção populacional (H0)", 0.0, 1.0, 0.1, 0.01)
75
+ p_sample = st.sidebar.slider("Proporção amostral", 0.0, 1.0, 0.12,0.01)
76
+ n = st.sidebar.slider("Tamanho da amostra", 100, 10000, 1000, 10)
77
+ alpha = st.sidebar.slider("Nível de significância (α)", 0.01, 0.10, 0.05, 0.01)
78
+
79
+ se = np.sqrt(p_pop*(1-p_pop)/n)
80
+ z = (p_sample - p_pop)/se
81
+ p_value = 2*(1 - stats.norm.cdf(abs(z)))
82
+
83
+ st.write(f"**Z** = {z:.4f}")
84
+ st.write(f"**p-valor** = {p_value:.4f}")
85
+ if p_value < alpha:
86
+ st.write("**Rejeitamos H0**: diferença significativa.")
87
+ else:
88
+ st.write("**Não rejeitamos H0**: sem diferença significativa.")
89
+
90
+ # Gráfico
91
+ x = np.linspace(p_pop-4*se, p_pop+4*se, 1000)
92
+ y = stats.norm.pdf(x, p_pop, se)
93
+ fig = go.Figure()
94
+ fig.add_trace(go.Scatter(x=x, y=y, mode="lines", line=dict(color="blue")))
95
+ fig.add_vline(x=p_sample, line=dict(color="red", width=2))
96
+ zc = stats.norm.ppf(1-alpha/2)
97
+ fig.add_vrect(x0=p_pop-zc*se, x1=p_pop+zc*se, fillcolor="red", opacity=0.2, line_width=0)
98
+ fig.update_layout(
99
+ title="Distribuição Normal e Região Crítica",
100
+ xaxis_title="Proporção", yaxis_title="Densidade",
101
+ showlegend=False, plot_bgcolor="white"
102
+ )
103
+ st.plotly_chart(fig, use_container_width=True)
104
+
105
+ st.markdown("**Descrição**: Teste bilateral de proporções usando valor-p.")
106
+
107
+ # Aba 2: Análise de Chocolate
108
+ with tabs[1]:
109
+ st.subheader("Testes de Hipótese e ANOVA em Dados de Chocolate")
110
+ st.markdown("---")
111
+
112
+ # 1) Carregar dados
113
+ df = pd.read_csv("Dados/flavors_of_cacao.csv")
114
+ st.markdown("#### Dados Brutos")
115
+ st.dataframe(df)
116
+
117
+ # 2) Renomear colunas
118
+ df.columns = [
119
+ "company","bean_bar_origin","ref","date",
120
+ "percent","location","rating","beantype","origin"
121
+ ]
122
+ st.markdown("#### Colunas Renomeadas")
123
+ st.dataframe(df.head())
124
+
125
+ # 3) Mapa: empresas por país
126
+ grp_loc = df.groupby("location").size().reset_index(name="count")
127
+ url = "https://raw.githubusercontent.com/datasets/geo-countries/master/data/countries.geojson"
128
+ world = gpd.read_file(url).rename(columns={"ADMIN":"name"})
129
+ mapa = world.merge(grp_loc, how="left", left_on="name", right_on="location")
130
+ fig_map, ax_map = plt.subplots(figsize=(8,4))
131
+ mapa.boundary.plot(ax=ax_map, edgecolor="gray", linewidth=0.5)
132
+ mapa.plot(column="count", ax=ax_map, cmap="OrRd", legend=True,
133
+ missing_kwds={"color":"lightgrey"})
134
+ ax_map.axis("off")
135
+ st.pyplot(fig_map)
136
+
137
+ # 4) Scatter: média por origem (count>=5)
138
+ grp_ori = (
139
+ df.groupby("origin")
140
+ .agg(count=("rating","size"), mean_rating=("rating","mean"))
141
+ .reset_index()
142
+ )
143
+ fil_ori = grp_ori.query("count>=5")
144
+ fig_sc, ax_sc = plt.subplots()
145
+ fig_sc = px.scatter(
146
+ fil_ori, x="mean_rating", y="origin",
147
+ size="count", color="origin",
148
+ title="Avaliação Média vs Origem",
149
+ labels={"mean_rating":"Avaliação Média","origin":"Origem"}
150
+ )
151
+ st.plotly_chart(fig_sc, use_container_width=True)
152
+
153
+ # 5) WordCloud de empresas
154
+ wc = WordCloud(width=800, height=300, background_color="white")
155
+ freqs = df["company"].value_counts().to_dict()
156
+ wc_img = wc.generate_from_frequencies(freqs)
157
+ fig_wc, ax_wc = plt.subplots(figsize=(8,3))
158
+ ax_wc.imshow(wc_img, interpolation="bilinear")
159
+ ax_wc.axis("off")
160
+ st.pyplot(fig_wc)
161
+
162
+ # 6) ANOVA e Tukey
163
+ paises = ["Brazil","France","U.S.A.","Canada","Ecuador","Peru","Venezuela"]
164
+ filt = df[df.location.isin(paises)]
165
+ melt = pd.melt(filt, id_vars=["location"], value_vars=["rating"])
166
+ model = ols("value ~ C(location)", data=melt).fit()
167
+ anova = sm.stats.anova_lm(model, typ=2)
168
+ st.markdown("#### ANOVA")
169
+ st.dataframe(anova)
170
+
171
+ tukey = pairwise_tukeyhsd(endog=melt.value, groups=melt.location, alpha=0.05)
172
+ st.markdown("#### Tukey HSD")
173
+ st.text(tukey.summary())
174
+
175
+ # 7) Diagnóstico de resíduos
176
+ std_res = model.get_influence().resid_studentized_internal
177
+ fig_qq = sm.qqplot(std_res, line="45", fit=True)
178
+ plt.title("QQ-plot Resíduos Padronizados")
179
+ st.pyplot(fig_qq)
180
+
181
+ fig_h, ax_h = plt.subplots()
182
+ ax_h.hist(model.resid, bins="auto", ec="black")
183
+ ax_h.set_title("Histograma dos Resíduos")
184
+ ax_h.set_xlabel("Resíduos"); ax_h.set_ylabel("Frequência")
185
+ st.pyplot(fig_h)
186
+
187
+ # 8) Testes de premissas
188
+ st.markdown("#### Testes de Premissas")
189
+ w, p_sh = shapiro(model.resid)
190
+ st.write(f"Shapiro-Wilk: estatística={w:.3f}, p-valor={p_sh:.3f}")
191
+ grupos = [filt.query("location==@loc").rating for loc in paises]
192
+ w_lev, p_lev = levene(*grupos)
193
+ st.write(f"Levene: estatística={w_lev:.3f}, p-valor={p_lev:.3f}")
194
+
195
+ kw_stat, kw_p = kruskal(*grupos)
196
+ st.write(f"Kruskal-Wallis: estatística={kw_stat:.3f}, p-valor={kw_p:.3f}")
197
+
198
+
199
+ # In[3]:
200
+
201
+
202
+ # Converte o notebook 'Dashboard_Distribuições.ipynb' para um script Python
203
+ subprocess.run(["jupyter", "nbconvert", "--to", "script", "Dashboard_Teste_de_Hipoteses.ipynb"])
204
+
README.md CHANGED
@@ -5,6 +5,6 @@ colorFrom: green
5
  colorTo: blue
6
  sdk: streamlit
7
  sdk_version: "1.32.0"
8
- app_file: Dashboard_Teste_de_Hipoteses.py
9
  pinned: false
10
  ---
 
5
  colorTo: blue
6
  sdk: streamlit
7
  sdk_version: "1.32.0"
8
+ app_file: Dashboard_Teste_de_Hipoteses_online.py
9
  pinned: false
10
  ---