Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,22 +9,23 @@ from sklearn.datasets import make_moons, make_circles, make_classification, make
|
|
| 9 |
# Set Streamlit page title
|
| 10 |
st.set_page_config(page_title="Neural Network Trainer", layout="wide")
|
| 11 |
|
| 12 |
-
# Session State for Training Controls
|
| 13 |
if "epoch" not in st.session_state:
|
| 14 |
st.session_state.epoch = 0
|
| 15 |
-
st.session_state.losses = []
|
| 16 |
if "running" not in st.session_state:
|
| 17 |
st.session_state.running = False
|
|
|
|
|
|
|
| 18 |
|
| 19 |
-
#
|
| 20 |
st.markdown("### Training Controls")
|
| 21 |
-
col1, col2, col3, col4, col5 = st.columns(
|
| 22 |
|
| 23 |
with col1:
|
| 24 |
if st.button("↩️ Reset"):
|
| 25 |
st.session_state.epoch = 0
|
| 26 |
-
st.session_state.losses = []
|
| 27 |
st.session_state.running = False
|
|
|
|
| 28 |
with col2:
|
| 29 |
if st.button("▶️ Train"):
|
| 30 |
st.session_state.running = True
|
|
@@ -34,27 +35,70 @@ with col3:
|
|
| 34 |
with col4:
|
| 35 |
activation = st.selectbox("Activation", ["ReLU", "Sigmoid", "Tanh"])
|
| 36 |
with col5:
|
|
|
|
|
|
|
| 37 |
learning_rate = st.selectbox("Learning Rate", [0.0001, 0.001, 0.01, 0.03, 0.1])
|
| 38 |
|
| 39 |
if st.session_state.running:
|
| 40 |
-
time.sleep(1)
|
| 41 |
st.session_state.epoch += 1
|
| 42 |
-
st.session_state.
|
| 43 |
|
| 44 |
-
#
|
| 45 |
-
st.
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
def generate_data():
|
| 52 |
if dataset_option == "Moons":
|
| 53 |
X, y = make_moons(n_samples=1000, noise=noise)
|
| 54 |
elif dataset_option == "Circles":
|
| 55 |
X, y = make_circles(n_samples=1000, noise=noise)
|
| 56 |
elif dataset_option == "Blobs":
|
| 57 |
-
X, y = make_blobs(n_samples=1000, centers=2, cluster_std=noise
|
| 58 |
else:
|
| 59 |
theta = np.sqrt(np.random.rand(1000)) * 2 * np.pi
|
| 60 |
r = theta
|
|
@@ -64,66 +108,35 @@ def generate_data():
|
|
| 64 |
|
| 65 |
X, y = generate_data()
|
| 66 |
|
| 67 |
-
#
|
| 68 |
-
st.
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
x1 = st.checkbox("X₁", value=True)
|
| 73 |
-
x2 = st.checkbox("X₂", value=True)
|
| 74 |
-
selected_features = [i for i, selected in enumerate([x1, x2]) if selected]
|
| 75 |
-
X = X[:, selected_features] if selected_features else np.zeros((X.shape[0], 1))
|
| 76 |
|
| 77 |
-
#
|
| 78 |
def draw_neural_network():
|
| 79 |
graph = graphviz.Digraph()
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
graph.node("Output", "Output", shape="circle", style="filled", fillcolor="lightgreen")
|
| 87 |
-
|
|
|
|
| 88 |
return graph
|
| 89 |
|
| 90 |
-
|
| 91 |
-
st.graphviz_chart(draw_neural_network())
|
| 92 |
-
|
| 93 |
-
# Decision Region Plot
|
| 94 |
-
def plot_decision_regions():
|
| 95 |
-
xx, yy = np.meshgrid(np.linspace(X[:, 0].min() - 1, X[:, 0].max() + 1, 100),
|
| 96 |
-
np.linspace(X[:, 1].min() - 1, X[:, 1].max() + 1, 100))
|
| 97 |
-
Z = np.random.choice([0, 1], size=xx.shape) # Placeholder for model predictions
|
| 98 |
-
fig, ax = plt.subplots()
|
| 99 |
-
ax.contourf(xx, yy, Z, alpha=0.3, cmap="plasma")
|
| 100 |
-
sns.scatterplot(x=X[:, 0], y=X[:, 1], hue=y, palette="plasma", edgecolor="k", ax=ax)
|
| 101 |
-
st.pyplot(fig)
|
| 102 |
-
|
| 103 |
-
with col_plot:
|
| 104 |
-
st.header("Decision Region")
|
| 105 |
-
plot_decision_regions()
|
| 106 |
-
|
| 107 |
-
# Loss Plot
|
| 108 |
-
def plot_loss():
|
| 109 |
-
fig, ax = plt.subplots()
|
| 110 |
-
ax.plot(range(len(st.session_state.losses)), st.session_state.losses, marker='o', linestyle='-')
|
| 111 |
-
ax.set_xlabel("Epoch")
|
| 112 |
-
ax.set_ylabel("Loss")
|
| 113 |
-
ax.set_title("Epoch vs Loss")
|
| 114 |
-
st.pyplot(fig)
|
| 115 |
-
|
| 116 |
-
st.header("Training Progress")
|
| 117 |
-
plot_loss()
|
| 118 |
-
|
| 119 |
-
# Dataset Visualization
|
| 120 |
-
st.sidebar.subheader("Dataset Visualization")
|
| 121 |
-
fig, ax = plt.subplots()
|
| 122 |
-
sns.scatterplot(x=X[:, 0], y=X[:, 1], hue=y, palette="plasma", edgecolor="k", ax=ax)
|
| 123 |
-
st.sidebar.pyplot(fig)
|
| 124 |
|
| 125 |
-
#
|
| 126 |
if st.session_state.running:
|
| 127 |
-
st.write("🚀 Training
|
| 128 |
elif not st.session_state.running and st.session_state.epoch > 0:
|
| 129 |
-
st.write("⏸️ Training
|
|
|
|
| 9 |
# Set Streamlit page title
|
| 10 |
st.set_page_config(page_title="Neural Network Trainer", layout="wide")
|
| 11 |
|
| 12 |
+
# ================= Session State for Training Controls =================
|
| 13 |
if "epoch" not in st.session_state:
|
| 14 |
st.session_state.epoch = 0
|
|
|
|
| 15 |
if "running" not in st.session_state:
|
| 16 |
st.session_state.running = False
|
| 17 |
+
if "loss_history" not in st.session_state:
|
| 18 |
+
st.session_state.loss_history = []
|
| 19 |
|
| 20 |
+
# ================= TRAINING CONTROL PANEL (Top) =================
|
| 21 |
st.markdown("### Training Controls")
|
| 22 |
+
col1, col2, col3, col4, col5, col6 = st.columns(6)
|
| 23 |
|
| 24 |
with col1:
|
| 25 |
if st.button("↩️ Reset"):
|
| 26 |
st.session_state.epoch = 0
|
|
|
|
| 27 |
st.session_state.running = False
|
| 28 |
+
st.session_state.loss_history = []
|
| 29 |
with col2:
|
| 30 |
if st.button("▶️ Train"):
|
| 31 |
st.session_state.running = True
|
|
|
|
| 35 |
with col4:
|
| 36 |
activation = st.selectbox("Activation", ["ReLU", "Sigmoid", "Tanh"])
|
| 37 |
with col5:
|
| 38 |
+
problem_type = st.selectbox("Problem Type", ["Classification", "Regression"])
|
| 39 |
+
with col6:
|
| 40 |
learning_rate = st.selectbox("Learning Rate", [0.0001, 0.001, 0.01, 0.03, 0.1])
|
| 41 |
|
| 42 |
if st.session_state.running:
|
| 43 |
+
time.sleep(1)
|
| 44 |
st.session_state.epoch += 1
|
| 45 |
+
st.session_state.loss_history.append(np.exp(-0.1 * st.session_state.epoch) + np.random.uniform(0, 0.05))
|
| 46 |
|
| 47 |
+
# ================= MAIN LAYOUT =================
|
| 48 |
+
col_features, col_hidden, col_plot = st.columns([2, 2, 3])
|
| 49 |
+
|
| 50 |
+
# ========== FEATURES PANEL (Left) ========== #
|
| 51 |
+
with col_features:
|
| 52 |
+
st.header("FEATURES")
|
| 53 |
+
st.write("Select input features:")
|
| 54 |
+
x1 = st.checkbox("X₁", value=True)
|
| 55 |
+
x2 = st.checkbox("X₂", value=True)
|
| 56 |
+
|
| 57 |
+
# ========== HIDDEN LAYERS PANEL (Middle) ========== #
|
| 58 |
+
with col_hidden:
|
| 59 |
+
st.header("HIDDEN LAYERS")
|
| 60 |
+
hidden_layers = st.slider("Number of Hidden Layers", 1, 7, 2)
|
| 61 |
+
neurons = [st.slider(f"Neurons in Layer {i+1}", 1, 20, 4) for i in range(hidden_layers)]
|
| 62 |
+
|
| 63 |
+
# ========== DECISION REGION PLOT (Right) ========== #
|
| 64 |
+
with col_plot:
|
| 65 |
+
st.header("Decision Region & Loss Plot")
|
| 66 |
+
fig, ax = plt.subplots()
|
| 67 |
+
x_min, x_max = -2, 2
|
| 68 |
+
y_min, y_max = -2, 2
|
| 69 |
+
xx, yy = np.meshgrid(np.linspace(x_min, x_max, 100), np.linspace(y_min, y_max, 100))
|
| 70 |
+
zz = np.sin(xx) * np.cos(yy) # Placeholder function
|
| 71 |
+
sns.heatmap(zz, cmap="coolwarm", alpha=0.5, ax=ax)
|
| 72 |
+
ax.set_title("Decision Region")
|
| 73 |
+
st.pyplot(fig)
|
| 74 |
|
| 75 |
+
# Loss Plot
|
| 76 |
+
fig, ax = plt.subplots()
|
| 77 |
+
ax.plot(range(len(st.session_state.loss_history)), st.session_state.loss_history, marker="o")
|
| 78 |
+
ax.set_title("Epoch vs. Loss")
|
| 79 |
+
ax.set_xlabel("Epoch")
|
| 80 |
+
ax.set_ylabel("Loss")
|
| 81 |
+
st.pyplot(fig)
|
| 82 |
+
|
| 83 |
+
# ================= DATASET SELECTION (Sidebar) =================
|
| 84 |
+
st.sidebar.header("DATA")
|
| 85 |
+
dataset_option = st.sidebar.radio(
|
| 86 |
+
"Which dataset do you want to use?",
|
| 87 |
+
("Moons", "Circles", "Spiral", "Blobs"),
|
| 88 |
+
index=2
|
| 89 |
+
)
|
| 90 |
+
train_ratio = st.sidebar.slider("Ratio of training to test data:", 10, 90, 50, format="%d%%")
|
| 91 |
+
noise = st.sidebar.slider("Noise:", 0.0, 1.0, 0.1, step=0.1)
|
| 92 |
+
batch_size = st.sidebar.slider("Batch size:", 1, 100, 10)
|
| 93 |
+
|
| 94 |
+
# ================= DATASET GENERATION =================
|
| 95 |
def generate_data():
|
| 96 |
if dataset_option == "Moons":
|
| 97 |
X, y = make_moons(n_samples=1000, noise=noise)
|
| 98 |
elif dataset_option == "Circles":
|
| 99 |
X, y = make_circles(n_samples=1000, noise=noise)
|
| 100 |
elif dataset_option == "Blobs":
|
| 101 |
+
X, y = make_blobs(n_samples=1000, centers=2, cluster_std=noise)
|
| 102 |
else:
|
| 103 |
theta = np.sqrt(np.random.rand(1000)) * 2 * np.pi
|
| 104 |
r = theta
|
|
|
|
| 108 |
|
| 109 |
X, y = generate_data()
|
| 110 |
|
| 111 |
+
# =================== DISPLAY DATA PLOT ===================
|
| 112 |
+
st.sidebar.subheader("Dataset Visualization")
|
| 113 |
+
fig, ax = plt.subplots()
|
| 114 |
+
sns.scatterplot(x=X[:, 0], y=X[:, 1], hue=y, palette="plasma", ax=ax)
|
| 115 |
+
st.sidebar.pyplot(fig)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
|
| 117 |
+
# =================== DRAW NEURAL NETWORK ===================
|
| 118 |
def draw_neural_network():
|
| 119 |
graph = graphviz.Digraph()
|
| 120 |
+
graph.node("X1", "X₁", shape="circle", style="filled", fillcolor="lightblue")
|
| 121 |
+
graph.node("X2", "X₂", shape="circle", style="filled", fillcolor="lightblue")
|
| 122 |
+
prev_layer = ["X1", "X2"]
|
| 123 |
+
for i, num_neurons in enumerate(neurons):
|
| 124 |
+
current_layer = [f"H{i+1}{j+1}" for j in range(num_neurons)]
|
| 125 |
+
for neuron in current_layer:
|
| 126 |
+
graph.node(neuron, neuron, shape="circle", style="filled", fillcolor="lightyellow")
|
| 127 |
+
for prev in prev_layer:
|
| 128 |
+
for curr in current_layer:
|
| 129 |
+
graph.edge(prev, curr)
|
| 130 |
+
prev_layer = current_layer
|
| 131 |
graph.node("Output", "Output", shape="circle", style="filled", fillcolor="lightgreen")
|
| 132 |
+
for neuron in prev_layer:
|
| 133 |
+
graph.edge(neuron, "Output")
|
| 134 |
return graph
|
| 135 |
|
| 136 |
+
st.graphviz_chart(draw_neural_network())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
|
| 138 |
+
# =================== TRAINING STATUS ===================
|
| 139 |
if st.session_state.running:
|
| 140 |
+
st.write("🚀 Training started...")
|
| 141 |
elif not st.session_state.running and st.session_state.epoch > 0:
|
| 142 |
+
st.write("⏸️ Training paused.")
|