File size: 3,125 Bytes
8db92d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import streamlit as st
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier

st.set_page_config(page_title="🌸 Iris Playground", page_icon="🌸")

st.title("🌸 Iris ML Playground — zero upload, 100% diversão!")
st.caption("Treinamos um modelo **na hora** usando o dataset Iris do scikit-learn. Ajuste os controles e veja a predição ao vivo.")

# Load dataset
data = load_iris()
X, y = data.data, data.target
feature_names = data.feature_names
target_names = data.target_names

with st.sidebar:
    st.header("⚙️ Configurações do Modelo")
    model_name = st.selectbox("Algoritmo", ["k-NN (K Vizinhos)", "Random Forest"])
    if model_name.startswith("k-NN"):
        k = st.slider("k (nº de vizinhos)", 1, 15, 5, 1)
        model = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=k))
    else:
        n = st.slider("Árvores (n_estimators)", 10, 300, 150, 10)
        model = RandomForestClassifier(n_estimators=n, random_state=42)

    st.divider()
    st.subheader("📏 Medidas da flor (cm)")
    sepal_length = st.slider("Comprimento da Sépala", 4.0, 8.0, 5.8, 0.1)
    sepal_width  = st.slider("Largura da Sépala",    2.0, 4.5, 3.0, 0.1)
    petal_length = st.slider("Comprimento da Pétala", 1.0, 7.0, 4.2, 0.1)
    petal_width  = st.slider("Largura da Pétala",     0.1, 2.5, 1.3, 0.1)

# Train model (quick!)
scores = cross_val_score(model, X, y, cv=5)
model.fit(X, y)

# Predict
sample = np.array([[sepal_length, sepal_width, petal_length, petal_width]])
proba = None
if hasattr(model, "predict_proba"):
    try:
        proba = model.predict_proba(sample)[0]
    except Exception:
        proba = None

pred = model.predict(sample)[0]
name = target_names[pred]

EMOJI = {"setosa":"🌱", "versicolor":"🌿", "virginica":"🌺"}
emoji = EMOJI.get(name, "🌸")

col1, col2 = st.columns(2)
with col1:
    st.metric("🎯 Acurácia (CV 5-fold)", f"{scores.mean()*100:,.2f}%")
with col2:
    st.metric("📊 Desvio-padrão", f"{scores.std()*100:,.2f}%")

st.success(f"**Predição:** {emoji} **{name.title()}**")

if proba is not None:
    st.write("**Confiança por classe:**")
    for i, cls in enumerate(target_names):
        bar = "▓" * int(proba[i] * 20)
        st.write(f"- {cls.title()}: {proba[i]*100:5.1f}%  {bar}")

with st.expander("💡 O que está acontecendo aqui?"):
    st.markdown(
        """
        - Carregamos o dataset **Iris** embutido no `scikit-learn` (sem upload!).
        - Treinamos um modelo simples (*k-NN* ou *Random Forest*) **na hora**.
        - Você ajusta as medidas da flor e o app **prevê a espécie**.
        - Mostramos a **acurácia média** via validação cruzada (CV 5-fold).
        - Tudo roda em segundos — perfeito para demonstração em aula.
        """
    )

st.caption("Feito com Streamlit • Dataset: Fisher's Iris (via scikit-learn) • Sem arquivos externos.")