Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,18 +3,19 @@ import networkx as nx
|
|
| 3 |
import pandas as pd
|
| 4 |
import numpy as np
|
| 5 |
import matplotlib.pyplot as plt
|
|
|
|
| 6 |
from sklearn.datasets import make_blobs, make_circles, make_moons
|
| 7 |
from sklearn.preprocessing import StandardScaler
|
| 8 |
from mlxtend.plotting import plot_decision_regions
|
| 9 |
import tensorflow as tf
|
| 10 |
from keras.models import Sequential
|
| 11 |
-
from keras.layers import Input, Dense
|
| 12 |
from keras.optimizers import SGD
|
| 13 |
from keras.losses import MeanSquaredError, BinaryCrossentropy
|
| 14 |
from keras.regularizers import l2, l1
|
| 15 |
from keras.callbacks import Callback
|
| 16 |
|
| 17 |
-
# Set wide layout and
|
| 18 |
st.set_page_config(layout="wide")
|
| 19 |
st.markdown("""
|
| 20 |
<style>
|
|
@@ -32,17 +33,20 @@ st.markdown("""
|
|
| 32 |
.stButton>button {
|
| 33 |
background-color: #555;
|
| 34 |
color: white;
|
| 35 |
-
border:
|
| 36 |
border-radius: 5px;
|
| 37 |
padding: 5px 10px;
|
| 38 |
font-size: 14px;
|
|
|
|
| 39 |
}
|
| 40 |
.stButton>button:hover {
|
| 41 |
background-color: #777;
|
|
|
|
| 42 |
}
|
| 43 |
.stSelectbox, .stSlider {
|
| 44 |
background-color: #333;
|
| 45 |
color: white;
|
|
|
|
| 46 |
border-radius: 5px;
|
| 47 |
padding: 5px;
|
| 48 |
}
|
|
@@ -54,11 +58,14 @@ st.markdown("""
|
|
| 54 |
.control-bar {
|
| 55 |
background-color: #1e2126;
|
| 56 |
padding: 10px;
|
| 57 |
-
border
|
|
|
|
|
|
|
| 58 |
}
|
| 59 |
.panel {
|
| 60 |
background-color: #2e3238;
|
| 61 |
padding: 10px;
|
|
|
|
| 62 |
border-radius: 5px;
|
| 63 |
margin: 10px 0;
|
| 64 |
}
|
|
@@ -85,10 +92,11 @@ def reset_session():
|
|
| 85 |
st.session_state.num_hidden_layers = 2
|
| 86 |
st.session_state.hidden_layer_neurons = [4, 2]
|
| 87 |
|
| 88 |
-
#
|
| 89 |
with st.container():
|
| 90 |
st.markdown('<div class="control-bar">', unsafe_allow_html=True)
|
| 91 |
-
|
|
|
|
| 92 |
with col1:
|
| 93 |
problem_type = st.selectbox("Problem Type", ["Classification", "Regression"])
|
| 94 |
with col2:
|
|
@@ -100,6 +108,9 @@ with st.container():
|
|
| 100 |
activation = st.selectbox("Activation", ["ReLU", "Sigmoid", "Tanh"], index=2)
|
| 101 |
with col5:
|
| 102 |
batch_size = st.slider("Batch Size", 1, 30, 10)
|
|
|
|
|
|
|
|
|
|
| 103 |
with col6:
|
| 104 |
noise_level = st.slider("Noise", 0, 50, 0, step=5)
|
| 105 |
with col7:
|
|
@@ -108,6 +119,8 @@ with st.container():
|
|
| 108 |
reg_rate = st.selectbox("Reg Rate", [0.0, 0.001, 0.01, 0.1, 1], index=0)
|
| 109 |
with col9:
|
| 110 |
train_ratio = st.slider("Train %", 10, 90, 50, 10) / 100
|
|
|
|
|
|
|
| 111 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 112 |
|
| 113 |
# Dataset generation
|
|
@@ -144,18 +157,21 @@ features = {
|
|
| 144 |
selected_features = [f for f in features.keys() if st.session_state.get(f, f in ["X1", "X2"])]
|
| 145 |
selected_data = np.column_stack([features[f] for f in selected_features])
|
| 146 |
|
|
|
|
|
|
|
|
|
|
| 147 |
# Main layout
|
| 148 |
col_left, col_center, col_right = st.columns([1, 2, 1])
|
| 149 |
|
| 150 |
-
# Left panel: Dataset
|
| 151 |
with col_left:
|
| 152 |
st.markdown('<div class="panel">', unsafe_allow_html=True)
|
| 153 |
st.subheader("Data")
|
| 154 |
fig, ax = plt.subplots(figsize=(3, 3))
|
| 155 |
if problem_type == "Classification":
|
| 156 |
-
|
| 157 |
else:
|
| 158 |
-
|
| 159 |
ax.set_xticks([])
|
| 160 |
ax.set_yticks([])
|
| 161 |
ax.set_facecolor("#333")
|
|
@@ -165,59 +181,53 @@ with col_left:
|
|
| 165 |
st.checkbox(feature, value=feature in ["X1", "X2"], key=feature)
|
| 166 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 167 |
|
| 168 |
-
# Center panel: Network Visualization
|
| 169 |
with col_center:
|
| 170 |
st.markdown('<div class="panel">', unsafe_allow_html=True)
|
| 171 |
st.subheader("Network")
|
| 172 |
|
| 173 |
def draw_nn(features, hidden_neurons):
|
| 174 |
G = nx.DiGraph()
|
| 175 |
-
|
| 176 |
-
# Define layers
|
| 177 |
input_layer = features
|
| 178 |
hidden_layers = [[f"H{i+1}_{j+1}" for j in range(n)] for i, n in enumerate(hidden_neurons)]
|
| 179 |
output_layer = ["Output"]
|
| 180 |
all_layers = [input_layer] + hidden_layers + [output_layer]
|
| 181 |
|
| 182 |
-
# Add nodes with layer attribute
|
| 183 |
node_colors = {}
|
| 184 |
for layer_idx, layer in enumerate(all_layers):
|
| 185 |
for node in layer:
|
| 186 |
G.add_node(node, layer=layer_idx)
|
| 187 |
if layer_idx == 0:
|
| 188 |
-
node_colors[node] = "#90EE90"
|
| 189 |
elif layer_idx == len(all_layers) - 1:
|
| 190 |
-
node_colors[node] = "#FFA07A"
|
| 191 |
else:
|
| 192 |
-
node_colors[node] = "#87CEFA"
|
| 193 |
|
| 194 |
-
# Add edges (fully connected)
|
| 195 |
for i in range(len(all_layers) - 1):
|
| 196 |
for node1 in all_layers[i]:
|
| 197 |
for node2 in all_layers[i + 1]:
|
| 198 |
G.add_edge(node1, node2)
|
| 199 |
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
for node in pos:
|
| 205 |
-
pos[node][1] *= 2 # Increase vertical spacing
|
| 206 |
|
| 207 |
-
# Draw the network
|
| 208 |
fig, ax = plt.subplots(figsize=(8, 4))
|
| 209 |
ax.set_facecolor("#252830")
|
| 210 |
nx.draw(
|
| 211 |
-
G,
|
| 212 |
-
with_labels=True,
|
| 213 |
-
node_color=[node_colors[node] for node in G.nodes()],
|
| 214 |
-
edge_color="white",
|
| 215 |
-
node_size=600,
|
| 216 |
-
font_size=8,
|
| 217 |
-
font_color="black",
|
| 218 |
-
font_weight="bold",
|
| 219 |
-
edgecolors="black",
|
| 220 |
-
width=0
|
|
|
|
| 221 |
ax=ax
|
| 222 |
)
|
| 223 |
plt.title("Neural Network Structure", color="white", fontsize=12, pad=10)
|
|
@@ -246,7 +256,7 @@ with col_center:
|
|
| 246 |
for i in range(st.session_state.num_hidden_layers):
|
| 247 |
col1, col2, col3 = st.columns([1, 2, 1])
|
| 248 |
with col1:
|
| 249 |
-
st.button("
|
| 250 |
with col2:
|
| 251 |
st.write(f"Layer {i+1}: {st.session_state.hidden_layer_neurons[i]}")
|
| 252 |
with col3:
|
|
@@ -298,12 +308,26 @@ with col_right:
|
|
| 298 |
with col1:
|
| 299 |
plt.figure(figsize=(3, 3))
|
| 300 |
if problem_type == "Classification":
|
| 301 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
else:
|
| 303 |
y_pred = self.model.predict(self.X, verbose=0)
|
| 304 |
plt.scatter(self.X[:, 0], self.y, c="blue", alpha=0.5)
|
| 305 |
plt.plot(self.X[:, 0], y_pred, "r-", linewidth=2)
|
| 306 |
plt.gca().set_facecolor("#333")
|
|
|
|
|
|
|
| 307 |
st.pyplot(plt)
|
| 308 |
with col2:
|
| 309 |
fig, ax = plt.subplots(figsize=(3, 3))
|
|
@@ -317,7 +341,4 @@ with col_right:
|
|
| 317 |
model = create_model(len(selected_features), st.session_state.hidden_layer_neurons)
|
| 318 |
callback = OutputCallback(selected_data, cv)
|
| 319 |
model.fit(selected_data, cv, epochs=999999, batch_size=batch_size, validation_split=1-train_ratio, callbacks=[callback], verbose=0)
|
| 320 |
-
st.markdown('</div>', unsafe_allow_html=True)
|
| 321 |
-
|
| 322 |
-
if st.button("Reset", key="reset_global"):
|
| 323 |
-
reset_session()
|
|
|
|
| 3 |
import pandas as pd
|
| 4 |
import numpy as np
|
| 5 |
import matplotlib.pyplot as plt
|
| 6 |
+
import seaborn as sns
|
| 7 |
from sklearn.datasets import make_blobs, make_circles, make_moons
|
| 8 |
from sklearn.preprocessing import StandardScaler
|
| 9 |
from mlxtend.plotting import plot_decision_regions
|
| 10 |
import tensorflow as tf
|
| 11 |
from keras.models import Sequential
|
| 12 |
+
from keras.layers import Input, Dense
|
| 13 |
from keras.optimizers import SGD
|
| 14 |
from keras.losses import MeanSquaredError, BinaryCrossentropy
|
| 15 |
from keras.regularizers import l2, l1
|
| 16 |
from keras.callbacks import Callback
|
| 17 |
|
| 18 |
+
# Set wide layout and updated CSS
|
| 19 |
st.set_page_config(layout="wide")
|
| 20 |
st.markdown("""
|
| 21 |
<style>
|
|
|
|
| 33 |
.stButton>button {
|
| 34 |
background-color: #555;
|
| 35 |
color: white;
|
| 36 |
+
border: 2px solid #777;
|
| 37 |
border-radius: 5px;
|
| 38 |
padding: 5px 10px;
|
| 39 |
font-size: 14px;
|
| 40 |
+
font-weight: bold;
|
| 41 |
}
|
| 42 |
.stButton>button:hover {
|
| 43 |
background-color: #777;
|
| 44 |
+
border-color: #999;
|
| 45 |
}
|
| 46 |
.stSelectbox, .stSlider {
|
| 47 |
background-color: #333;
|
| 48 |
color: white;
|
| 49 |
+
border: 2px solid #777;
|
| 50 |
border-radius: 5px;
|
| 51 |
padding: 5px;
|
| 52 |
}
|
|
|
|
| 58 |
.control-bar {
|
| 59 |
background-color: #1e2126;
|
| 60 |
padding: 10px;
|
| 61 |
+
border: 2px solid #333;
|
| 62 |
+
border-radius: 5px;
|
| 63 |
+
margin-bottom: 10px;
|
| 64 |
}
|
| 65 |
.panel {
|
| 66 |
background-color: #2e3238;
|
| 67 |
padding: 10px;
|
| 68 |
+
border: 2px solid #777;
|
| 69 |
border-radius: 5px;
|
| 70 |
margin: 10px 0;
|
| 71 |
}
|
|
|
|
| 92 |
st.session_state.num_hidden_layers = 2
|
| 93 |
st.session_state.hidden_layer_neurons = [4, 2]
|
| 94 |
|
| 95 |
+
# Two-row top control bar
|
| 96 |
with st.container():
|
| 97 |
st.markdown('<div class="control-bar">', unsafe_allow_html=True)
|
| 98 |
+
# Row 1
|
| 99 |
+
col1, col2, col3, col4, col5 = st.columns(5)
|
| 100 |
with col1:
|
| 101 |
problem_type = st.selectbox("Problem Type", ["Classification", "Regression"])
|
| 102 |
with col2:
|
|
|
|
| 108 |
activation = st.selectbox("Activation", ["ReLU", "Sigmoid", "Tanh"], index=2)
|
| 109 |
with col5:
|
| 110 |
batch_size = st.slider("Batch Size", 1, 30, 10)
|
| 111 |
+
|
| 112 |
+
# Row 2
|
| 113 |
+
col6, col7, col8, col9, col10 = st.columns(5)
|
| 114 |
with col6:
|
| 115 |
noise_level = st.slider("Noise", 0, 50, 0, step=5)
|
| 116 |
with col7:
|
|
|
|
| 119 |
reg_rate = st.selectbox("Reg Rate", [0.0, 0.001, 0.01, 0.1, 1], index=0)
|
| 120 |
with col9:
|
| 121 |
train_ratio = st.slider("Train %", 10, 90, 50, 10) / 100
|
| 122 |
+
with col10:
|
| 123 |
+
st.button("Reset", key="reset_global", on_click=reset_session)
|
| 124 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 125 |
|
| 126 |
# Dataset generation
|
|
|
|
| 157 |
selected_features = [f for f in features.keys() if st.session_state.get(f, f in ["X1", "X2"])]
|
| 158 |
selected_data = np.column_stack([features[f] for f in selected_features])
|
| 159 |
|
| 160 |
+
if problem_type == "Classification":
|
| 161 |
+
cv = cv.astype(int)
|
| 162 |
+
|
| 163 |
# Main layout
|
| 164 |
col_left, col_center, col_right = st.columns([1, 2, 1])
|
| 165 |
|
| 166 |
+
# Left panel: Dataset with Seaborn
|
| 167 |
with col_left:
|
| 168 |
st.markdown('<div class="panel">', unsafe_allow_html=True)
|
| 169 |
st.subheader("Data")
|
| 170 |
fig, ax = plt.subplots(figsize=(3, 3))
|
| 171 |
if problem_type == "Classification":
|
| 172 |
+
sns.scatterplot(x=fv[:, 0], y=fv[:, 1], hue=cv, palette="coolwarm", edgecolor="k", alpha=0.7, ax=ax, legend=False)
|
| 173 |
else:
|
| 174 |
+
sns.scatterplot(x=fv[:, 0], y=cv, color="blue", edgecolor="k", alpha=0.7, ax=ax)
|
| 175 |
ax.set_xticks([])
|
| 176 |
ax.set_yticks([])
|
| 177 |
ax.set_facecolor("#333")
|
|
|
|
| 181 |
st.checkbox(feature, value=feature in ["X1", "X2"], key=feature)
|
| 182 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 183 |
|
| 184 |
+
# Center panel: Horizontal Network Visualization
|
| 185 |
with col_center:
|
| 186 |
st.markdown('<div class="panel">', unsafe_allow_html=True)
|
| 187 |
st.subheader("Network")
|
| 188 |
|
| 189 |
def draw_nn(features, hidden_neurons):
|
| 190 |
G = nx.DiGraph()
|
|
|
|
|
|
|
| 191 |
input_layer = features
|
| 192 |
hidden_layers = [[f"H{i+1}_{j+1}" for j in range(n)] for i, n in enumerate(hidden_neurons)]
|
| 193 |
output_layer = ["Output"]
|
| 194 |
all_layers = [input_layer] + hidden_layers + [output_layer]
|
| 195 |
|
|
|
|
| 196 |
node_colors = {}
|
| 197 |
for layer_idx, layer in enumerate(all_layers):
|
| 198 |
for node in layer:
|
| 199 |
G.add_node(node, layer=layer_idx)
|
| 200 |
if layer_idx == 0:
|
| 201 |
+
node_colors[node] = "#90EE90"
|
| 202 |
elif layer_idx == len(all_layers) - 1:
|
| 203 |
+
node_colors[node] = "#FFA07A"
|
| 204 |
else:
|
| 205 |
+
node_colors[node] = "#87CEFA"
|
| 206 |
|
|
|
|
| 207 |
for i in range(len(all_layers) - 1):
|
| 208 |
for node1 in all_layers[i]:
|
| 209 |
for node2 in all_layers[i + 1]:
|
| 210 |
G.add_edge(node1, node2)
|
| 211 |
|
| 212 |
+
pos = nx.multipartite_layout(G, subset_key="layer", align="vertical")
|
| 213 |
+
pos_rotated = {node: (-y, x) for node, (x, y) in pos.items()}
|
| 214 |
+
for node in pos_rotated:
|
| 215 |
+
pos_rotated[node] = (pos_rotated[node][0] * 2, pos_rotated[node][1] * 2)
|
|
|
|
|
|
|
| 216 |
|
|
|
|
| 217 |
fig, ax = plt.subplots(figsize=(8, 4))
|
| 218 |
ax.set_facecolor("#252830")
|
| 219 |
nx.draw(
|
| 220 |
+
G, pos_rotated,
|
| 221 |
+
with_labels=True,
|
| 222 |
+
node_color=[node_colors[node] for node in G.nodes()],
|
| 223 |
+
edge_color="white",
|
| 224 |
+
node_size=600,
|
| 225 |
+
font_size=8,
|
| 226 |
+
font_color="black",
|
| 227 |
+
font_weight="bold",
|
| 228 |
+
edgecolors="black",
|
| 229 |
+
width=1.0,
|
| 230 |
+
arrows=True,
|
| 231 |
ax=ax
|
| 232 |
)
|
| 233 |
plt.title("Neural Network Structure", color="white", fontsize=12, pad=10)
|
|
|
|
| 256 |
for i in range(st.session_state.num_hidden_layers):
|
| 257 |
col1, col2, col3 = st.columns([1, 2, 1])
|
| 258 |
with col1:
|
| 259 |
+
st.button("−", key=f"dec_{i}", on_click=decrease_neurons, args=(i,)) # Unicode minus
|
| 260 |
with col2:
|
| 261 |
st.write(f"Layer {i+1}: {st.session_state.hidden_layer_neurons[i]}")
|
| 262 |
with col3:
|
|
|
|
| 308 |
with col1:
|
| 309 |
plt.figure(figsize=(3, 3))
|
| 310 |
if problem_type == "Classification":
|
| 311 |
+
y_pred_proba = self.model.predict(self.X, verbose=0)
|
| 312 |
+
y_pred = (y_pred_proba > 0.5).astype(int).ravel()
|
| 313 |
+
try:
|
| 314 |
+
plot_decision_regions(self.X, self.y, clf=self.model, legend=2)
|
| 315 |
+
except Exception as e:
|
| 316 |
+
st.warning(f"Decision region plot failed: {e}")
|
| 317 |
+
xx, yy = np.meshgrid(np.linspace(self.X[:, 0].min(), self.X[:, 0].max(), 100),
|
| 318 |
+
np.linspace(self.X[:, 1].min(), self.X[:, 1].max(), 100))
|
| 319 |
+
grid = np.c_[xx.ravel(), yy.ravel()]
|
| 320 |
+
Z = self.model.predict(grid, verbose=0)
|
| 321 |
+
Z = (Z > 0.5).astype(int).reshape(xx.shape)
|
| 322 |
+
plt.contourf(xx, yy, Z, alpha=0.3, cmap="coolwarm")
|
| 323 |
+
plt.scatter(self.X[:, 0], self.X[:, 1], c=self.y, cmap="coolwarm", edgecolors="k", alpha=0.7)
|
| 324 |
else:
|
| 325 |
y_pred = self.model.predict(self.X, verbose=0)
|
| 326 |
plt.scatter(self.X[:, 0], self.y, c="blue", alpha=0.5)
|
| 327 |
plt.plot(self.X[:, 0], y_pred, "r-", linewidth=2)
|
| 328 |
plt.gca().set_facecolor("#333")
|
| 329 |
+
plt.xticks([])
|
| 330 |
+
plt.yticks([])
|
| 331 |
st.pyplot(plt)
|
| 332 |
with col2:
|
| 333 |
fig, ax = plt.subplots(figsize=(3, 3))
|
|
|
|
| 341 |
model = create_model(len(selected_features), st.session_state.hidden_layer_neurons)
|
| 342 |
callback = OutputCallback(selected_data, cv)
|
| 343 |
model.fit(selected_data, cv, epochs=999999, batch_size=batch_size, validation_split=1-train_ratio, callbacks=[callback], verbose=0)
|
| 344 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
|
|
|
|
|
|
|
|