trohith89 commited on
Commit
9293c8b
·
verified ·
1 Parent(s): dde03ea

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -56
app.py CHANGED
@@ -4,7 +4,12 @@ import matplotlib.pyplot as plt
4
  import seaborn as sns
5
  import graphviz
6
  import time
 
 
 
 
7
  from sklearn.datasets import make_moons, make_circles, make_classification, make_blobs
 
8
 
9
  # Set Streamlit page title
10
  st.set_page_config(page_title="Neural Network Trainer", layout="wide")
@@ -21,7 +26,7 @@ if "test_loss_history" not in st.session_state:
21
 
22
  # ================= TRAINING CONTROL PANEL (Top) =================
23
  st.markdown("### Training Controls")
24
- col1, col2, col3, col4, col5, col6, col7 = st.columns(7)
25
 
26
  with col1:
27
  if st.button("↩️ Reset"):
@@ -43,12 +48,11 @@ with col6:
43
  learning_rate = st.selectbox("Learning Rate", [0.0001, 0.001, 0.01, 0.03, 0.1])
44
  with col7:
45
  num_epochs = st.slider("Epochs", 1, 100, 10)
46
-
47
- if st.session_state.running:
48
- time.sleep(1)
49
- st.session_state.epoch += 1
50
- st.session_state.train_loss_history.append(np.exp(-0.1 * st.session_state.epoch) + np.random.uniform(0, 0.05))
51
- st.session_state.test_loss_history.append(np.exp(-0.1 * st.session_state.epoch) + np.random.uniform(0, 0.05) + 0.02)
52
 
53
  # ================= MAIN LAYOUT =================
54
  col_features, col_hidden, col_plot = st.columns([2, 2, 3])
@@ -66,39 +70,6 @@ with col_hidden:
66
  hidden_layers = st.slider("Number of Hidden Layers", 1, 7, 2)
67
  neurons = [st.slider(f"Neurons in Layer {i+1}", 1, 20, 4) for i in range(hidden_layers)]
68
 
69
- # ========== DECISION REGION PLOT (Right) ========== #
70
- with col_plot:
71
- st.header("Decision Region & Loss Plot")
72
- fig, ax = plt.subplots()
73
- x_min, x_max = -2, 2
74
- y_min, y_max = -2, 2
75
- xx, yy = np.meshgrid(np.linspace(x_min, x_max, 100), np.linspace(y_min, y_max, 100))
76
- zz = np.sin(xx) * np.cos(yy) # Placeholder function
77
- sns.heatmap(zz, cmap="coolwarm", alpha=0.5, ax=ax)
78
- ax.set_title("Decision Region")
79
- st.pyplot(fig)
80
-
81
- # Loss Plot
82
- fig, ax = plt.subplots()
83
- ax.plot(range(len(st.session_state.train_loss_history)), st.session_state.train_loss_history, marker="o", label="Train Loss")
84
- ax.plot(range(len(st.session_state.test_loss_history)), st.session_state.test_loss_history, marker="s", label="Test Loss")
85
- ax.set_title("Epoch vs. Loss")
86
- ax.set_xlabel("Epoch")
87
- ax.set_ylabel("Loss")
88
- ax.legend()
89
- st.pyplot(fig)
90
-
91
- # ================= DATASET SELECTION (Sidebar) =================
92
- st.sidebar.header("DATA")
93
- dataset_option = st.sidebar.radio(
94
- "Which dataset do you want to use?",
95
- ("Moons", "Circles", "Spiral", "Blobs"),
96
- index=2
97
- )
98
- train_ratio = st.sidebar.slider("Ratio of training to test data:", 10, 90, 50, format="%d%%")
99
- noise = st.sidebar.slider("Noise:", 0.0, 1.0, 0.1, step=0.1)
100
- batch_size = st.sidebar.slider("Batch size:", 1, 100, 10)
101
-
102
  # ================= DATASET GENERATION =================
103
  def generate_data():
104
  if dataset_option == "Moons":
@@ -108,21 +79,48 @@ def generate_data():
108
  elif dataset_option == "Blobs":
109
  X, y = make_blobs(n_samples=1000, centers=2, cluster_std=noise)
110
  else:
111
- theta = np.sqrt(np.random.rand(1000)) * 2 * np.pi
112
- r = theta
113
- X = np.array([r * np.cos(theta), r * np.sin(theta)]).T
114
- y = (theta % (2 * np.pi)) > np.pi
115
  return X, y
116
 
117
  X, y = generate_data()
 
 
 
 
 
 
 
 
 
 
 
118
 
119
- # =================== DISPLAY DATA PLOT ===================
120
- st.sidebar.subheader("Dataset Visualization")
121
- fig, ax = plt.subplots()
122
- sns.scatterplot(x=X[:, 0], y=X[:, 1], hue=y, palette="plasma", ax=ax)
123
- st.sidebar.pyplot(fig)
124
 
125
- # =================== DRAW NEURAL NETWORK ===================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  def draw_neural_network():
127
  graph = graphviz.Digraph()
128
  graph.node("X1", "X₁", shape="circle", style="filled", fillcolor="lightblue")
@@ -142,9 +140,3 @@ def draw_neural_network():
142
  return graph
143
 
144
  st.graphviz_chart(draw_neural_network())
145
-
146
- # =================== TRAINING STATUS ===================
147
- if st.session_state.running:
148
- st.write("🚀 Training started...")
149
- elif not st.session_state.running and st.session_state.epoch > 0:
150
- st.write("⏸️ Training paused.")
 
4
  import seaborn as sns
5
  import graphviz
6
  import time
7
+ import tensorflow as tf
8
+ from tensorflow import keras
9
+ from tensorflow.keras import layers
10
+ from sklearn.model_selection import train_test_split
11
  from sklearn.datasets import make_moons, make_circles, make_classification, make_blobs
12
+ from mlxtend.plotting import plot_decision_regions
13
 
14
  # Set Streamlit page title
15
  st.set_page_config(page_title="Neural Network Trainer", layout="wide")
 
26
 
27
  # ================= TRAINING CONTROL PANEL (Top) =================
28
  st.markdown("### Training Controls")
29
+ col1, col2, col3, col4, col5, col6, col7, col8, col9 = st.columns(9)
30
 
31
  with col1:
32
  if st.button("↩️ Reset"):
 
48
  learning_rate = st.selectbox("Learning Rate", [0.0001, 0.001, 0.01, 0.03, 0.1])
49
  with col7:
50
  num_epochs = st.slider("Epochs", 1, 100, 10)
51
+ with col8:
52
+ batch_size = st.slider("Batch Size", 1, 100, 10)
53
+ with col9:
54
+ dataset_option = st.selectbox("Select Dataset", ["Moons", "Circles", "Blobs", "Classification"])
55
+ noise = st.slider("Noise Level", 0.0, 0.5, 0.2)
 
56
 
57
  # ================= MAIN LAYOUT =================
58
  col_features, col_hidden, col_plot = st.columns([2, 2, 3])
 
70
  hidden_layers = st.slider("Number of Hidden Layers", 1, 7, 2)
71
  neurons = [st.slider(f"Neurons in Layer {i+1}", 1, 20, 4) for i in range(hidden_layers)]
72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  # ================= DATASET GENERATION =================
74
  def generate_data():
75
  if dataset_option == "Moons":
 
79
  elif dataset_option == "Blobs":
80
  X, y = make_blobs(n_samples=1000, centers=2, cluster_std=noise)
81
  else:
82
+ X, y = make_classification(n_samples=1000, n_features=2, n_classes=2, n_clusters_per_class=1, n_redundant=0, flip_y=noise)
 
 
 
83
  return X, y
84
 
85
  X, y = generate_data()
86
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
87
+
88
+ # ========== TRAINING ANN ========== #
89
+ def build_ann():
90
+ model = keras.Sequential()
91
+ model.add(layers.Input(shape=(X.shape[1],)))
92
+ for units in neurons:
93
+ model.add(layers.Dense(units, activation=activation.lower()))
94
+ model.add(layers.Dense(1, activation="sigmoid" if problem_type == "Classification" else "linear"))
95
+ model.compile(optimizer=keras.optimizers.Adam(learning_rate), loss="binary_crossentropy" if problem_type == "Classification" else "mse")
96
+ return model
97
 
98
+ if st.session_state.running:
99
+ model = build_ann()
100
+ history = model.fit(X_train, y_train, epochs=num_epochs, batch_size=batch_size, validation_data=(X_test, y_test), verbose=0)
101
+ st.session_state.train_loss_history = history.history["loss"]
102
+ st.session_state.test_loss_history = history.history["val_loss"]
103
 
104
+ # ========== LOSS PLOT ========== #
105
+ with col_plot:
106
+ st.header("Loss Plot")
107
+ fig, ax = plt.subplots()
108
+ ax.plot(range(1, len(st.session_state.train_loss_history) + 1), st.session_state.train_loss_history, marker="o", label="Train Loss")
109
+ ax.plot(range(1, len(st.session_state.test_loss_history) + 1), st.session_state.test_loss_history, marker="s", label="Test Loss")
110
+ ax.set_title("Epoch vs. Loss")
111
+ ax.set_xlabel("Epoch")
112
+ ax.set_ylabel("Loss")
113
+ ax.legend()
114
+ st.pyplot(fig)
115
+
116
+ # =================== DECISION REGION =================== #
117
+ if problem_type == "Classification":
118
+ fig, ax = plt.subplots()
119
+ plot_decision_regions(X_train, y_train, clf=model, ax=ax)
120
+ ax.set_title("Decision Region")
121
+ st.pyplot(fig)
122
+
123
+ # =================== DRAW NEURAL NETWORK =================== #
124
  def draw_neural_network():
125
  graph = graphviz.Digraph()
126
  graph.node("X1", "X₁", shape="circle", style="filled", fillcolor="lightblue")
 
140
  return graph
141
 
142
  st.graphviz_chart(draw_neural_network())