trohith89 commited on
Commit
e5ccdee
·
verified ·
1 Parent(s): 5028ce0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -22
app.py CHANGED
@@ -3,18 +3,18 @@ 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_circles
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 BinaryCrossentropy
14
  from keras.regularizers import l2, l1
15
  from keras.callbacks import Callback
16
 
17
- # Set wide layout and apply TensorFlow Playground-inspired CSS
18
  st.set_page_config(layout="wide")
19
  st.markdown("""
20
  <style>
@@ -65,11 +65,11 @@ st.markdown("""
65
  </style>
66
  """, unsafe_allow_html=True)
67
 
68
- # Session state initialization (matching URL defaults)
69
  if "training" not in st.session_state:
70
  st.session_state.training = False
71
  if "num_hidden_layers" not in st.session_state:
72
- st.session_state.num_hidden_layers = 2 # Default: 4,2
73
  if "hidden_layer_neurons" not in st.session_state:
74
  st.session_state.hidden_layer_neurons = [4, 2]
75
  if "prev_params" not in st.session_state:
@@ -83,27 +83,52 @@ def reset_session():
83
  # Top control bar
84
  with st.container():
85
  st.markdown('<div class="control-bar">', unsafe_allow_html=True)
86
- col1, col2, col3, col4, col5, col6, col7, col8 = st.columns(8)
87
  with col1:
88
- dataset_type = st.selectbox("Dataset", ["Circle", "Gaussian"], index=0, label_visibility="collapsed")
89
  with col2:
90
- learning_rate = st.selectbox("Learning Rate", [0.0001, 0.001, 0.03, 0.1, 0.3, 1], index=2, label_visibility="collapsed")
 
91
  with col3:
92
- activation = st.selectbox("Activation", ["ReLU", "Sigmoid", "Tanh"], index=2, label_visibility="collapsed")
93
  with col4:
94
- batch_size = st.slider("Batch Size", 1, 30, 10, label_visibility="collapsed")
95
  with col5:
96
- noise_level = st.slider("Noise", 0, 50, 0, step=5, label_visibility="collapsed")
97
  with col6:
98
- reg_type = st.selectbox("Regularization", ["None", "L1", "L2"], index=0, label_visibility="collapsed")
99
  with col7:
100
- reg_rate = st.selectbox("Reg Rate", [0.0, 0.001, 0.01, 0.1, 1], index=0, label_visibility="collapsed")
101
  with col8:
 
 
102
  train_ratio = st.slider("Train %", 10, 90, 50, 10, label_visibility="collapsed") / 100
103
  st.markdown('</div>', unsafe_allow_html=True)
104
 
105
- # Dataset generation (Circle as default)
106
- fv, cv = make_circles(n_samples=800, shuffle=True, noise=noise_level / 250, factor=0.2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  std = StandardScaler()
108
  X = std.fit_transform(fv)
109
  x1, x2 = X[:, 0], X[:, 1]
@@ -114,7 +139,7 @@ features = {
114
  selected_features = [f for f in features.keys() if st.session_state.get(f, f in ["X1", "X2"])]
115
  selected_data = np.column_stack([features[f] for f in selected_features])
116
 
117
- # Main layout with three panels
118
  col_left, col_center, col_right = st.columns([1, 2, 1])
119
 
120
  # Left panel: Dataset and Features
@@ -122,7 +147,10 @@ with col_left:
122
  st.markdown('<div class="panel">', unsafe_allow_html=True)
123
  st.subheader("Data")
124
  fig, ax = plt.subplots(figsize=(3, 3))
125
- ax.scatter(fv[:, 0], fv[:, 1], c=cv, cmap="coolwarm", edgecolors="k", alpha=0.7)
 
 
 
126
  ax.set_xticks([])
127
  ax.set_yticks([])
128
  ax.set_facecolor("#333")
@@ -209,11 +237,13 @@ with col_right:
209
  reg = l1(reg_rate) if reg_type == "L1" else l2(reg_rate) if reg_type == "L2" else None
210
  for n in neurons:
211
  model.add(Dense(n, activation=activation.lower(), kernel_regularizer=reg))
212
- model.add(Dense(1, activation="sigmoid"))
213
- model.compile(optimizer=SGD(learning_rate=learning_rate), loss=BinaryCrossentropy(), metrics=["accuracy"])
 
 
214
  return model
215
 
216
- class LossPlotCallback(tf.keras.callbacks.Callback):
217
  def __init__(self, X, y):
218
  super().__init__()
219
  self.X, self.y = X, y
@@ -228,7 +258,12 @@ with col_right:
228
  col1, col2 = st.columns(2)
229
  with col1:
230
  plt.figure(figsize=(3, 3))
231
- plot_decision_regions(self.X, self.y, clf=self.model)
 
 
 
 
 
232
  plt.gca().set_facecolor("#333")
233
  st.pyplot(plt)
234
  with col2:
@@ -241,7 +276,7 @@ with col_right:
241
 
242
  if st.session_state.training:
243
  model = create_model(len(selected_features), st.session_state.hidden_layer_neurons)
244
- callback = LossPlotCallback(selected_data, cv)
245
  model.fit(selected_data, cv, epochs=999999, batch_size=batch_size, validation_split=1-train_ratio, callbacks=[callback], verbose=0)
246
  st.markdown('</div>', unsafe_allow_html=True)
247
 
 
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 TensorFlow Playground CSS
18
  st.set_page_config(layout="wide")
19
  st.markdown("""
20
  <style>
 
65
  </style>
66
  """, unsafe_allow_html=True)
67
 
68
+ # Session state initialization
69
  if "training" not in st.session_state:
70
  st.session_state.training = False
71
  if "num_hidden_layers" not in st.session_state:
72
+ st.session_state.num_hidden_layers = 2
73
  if "hidden_layer_neurons" not in st.session_state:
74
  st.session_state.hidden_layer_neurons = [4, 2]
75
  if "prev_params" not in st.session_state:
 
83
  # Top control bar
84
  with st.container():
85
  st.markdown('<div class="control-bar">', unsafe_allow_html=True)
86
+ col1, col2, col3, col4, col5, col6, col7, col8, col9 = st.columns(9)
87
  with col1:
88
+ problem_type = st.selectbox("Problem", ["Classification", "Regression"], label_visibility="collapsed")
89
  with col2:
90
+ dataset_options = {"Classification": ["Blobs", "Circles", "Spirals", "XOR"], "Regression": ["Sine Wave"]}
91
+ dataset_type = st.selectbox("Dataset", dataset_options[problem_type], label_visibility="collapsed")
92
  with col3:
93
+ learning_rate = st.selectbox("Learning Rate", [0.0001, 0.001, 0.03, 0.1, 0.3, 1], index=2, label_visibility="collapsed")
94
  with col4:
95
+ activation = st.selectbox("Activation", ["ReLU", "Sigmoid", "Tanh"], index=2, label_visibility="collapsed")
96
  with col5:
97
+ batch_size = st.slider("Batch Size", 1, 30, 10, label_visibility="collapsed")
98
  with col6:
99
+ noise_level = st.slider("Noise", 0, 50, 0, step=5, label_visibility="collapsed")
100
  with col7:
101
+ reg_type = st.selectbox("Regularization", ["None", "L1", "L2"], index=0, label_visibility="collapsed")
102
  with col8:
103
+ reg_rate = st.selectbox("Reg Rate", [0.0, 0.001, 0.01, 0.1, 1], index=0, label_visibility="collapsed")
104
+ with col9:
105
  train_ratio = st.slider("Train %", 10, 90, 50, 10, label_visibility="collapsed") / 100
106
  st.markdown('</div>', unsafe_allow_html=True)
107
 
108
+ # Dataset generation
109
+ def generate_xor(n_samples):
110
+ X = np.random.rand(n_samples, 2) * 2 - 1 # Range [-1, 1]
111
+ y = np.logical_xor(X[:, 0] > 0, X[:, 1] > 0).astype(int)
112
+ return X, y
113
+
114
+ def generate_sine_wave(n_samples, noise):
115
+ X = np.linspace(-3, 3, n_samples).reshape(-1, 1)
116
+ y = np.sin(X) + np.random.normal(0, noise / 100, X.shape)
117
+ return np.hstack([X, X**2]), y.ravel() # Add X^2 as a second feature
118
+
119
+ if problem_type == "Classification":
120
+ if dataset_type == "Blobs":
121
+ fv, cv = make_blobs(n_samples=800, centers=2, n_features=2, cluster_std=1.5 + noise_level / 50, random_state=42)
122
+ elif dataset_type == "Circles":
123
+ fv, cv = make_circles(n_samples=800, noise=noise_level / 250, factor=0.2)
124
+ elif dataset_type == "Spirals":
125
+ fv, cv = make_moons(n_samples=800, noise=noise_level / 250)
126
+ elif dataset_type == "XOR":
127
+ fv, cv = generate_xor(800)
128
+ else: # Regression
129
+ fv, cv = generate_sine_wave(800, noise_level)
130
+
131
+ # Feature preprocessing
132
  std = StandardScaler()
133
  X = std.fit_transform(fv)
134
  x1, x2 = X[:, 0], X[:, 1]
 
139
  selected_features = [f for f in features.keys() if st.session_state.get(f, f in ["X1", "X2"])]
140
  selected_data = np.column_stack([features[f] for f in selected_features])
141
 
142
+ # Main layout
143
  col_left, col_center, col_right = st.columns([1, 2, 1])
144
 
145
  # Left panel: Dataset and Features
 
147
  st.markdown('<div class="panel">', unsafe_allow_html=True)
148
  st.subheader("Data")
149
  fig, ax = plt.subplots(figsize=(3, 3))
150
+ if problem_type == "Classification":
151
+ ax.scatter(fv[:, 0], fv[:, 1], c=cv, cmap="coolwarm", edgecolors="k", alpha=0.7)
152
+ else:
153
+ ax.scatter(fv[:, 0], cv, c="blue", alpha=0.7)
154
  ax.set_xticks([])
155
  ax.set_yticks([])
156
  ax.set_facecolor("#333")
 
237
  reg = l1(reg_rate) if reg_type == "L1" else l2(reg_rate) if reg_type == "L2" else None
238
  for n in neurons:
239
  model.add(Dense(n, activation=activation.lower(), kernel_regularizer=reg))
240
+ output_activation = "sigmoid" if problem_type == "Classification" else "linear"
241
+ loss = BinaryCrossentropy() if problem_type == "Classification" else MeanSquaredError()
242
+ model.add(Dense(1, activation=output_activation))
243
+ model.compile(optimizer=SGD(learning_rate=learning_rate), loss=loss, metrics=["accuracy" if problem_type == "Classification" else "mae"])
244
  return model
245
 
246
+ class OutputCallback(tf.keras.callbacks.Callback):
247
  def __init__(self, X, y):
248
  super().__init__()
249
  self.X, self.y = X, y
 
258
  col1, col2 = st.columns(2)
259
  with col1:
260
  plt.figure(figsize=(3, 3))
261
+ if problem_type == "Classification":
262
+ plot_decision_regions(self.X, self.y, clf=self.model)
263
+ else:
264
+ y_pred = self.model.predict(self.X, verbose=0)
265
+ plt.scatter(self.X[:, 0], self.y, c="blue", alpha=0.5)
266
+ plt.plot(self.X[:, 0], y_pred, "r-", linewidth=2)
267
  plt.gca().set_facecolor("#333")
268
  st.pyplot(plt)
269
  with col2:
 
276
 
277
  if st.session_state.training:
278
  model = create_model(len(selected_features), st.session_state.hidden_layer_neurons)
279
+ callback = OutputCallback(selected_data, cv)
280
  model.fit(selected_data, cv, epochs=999999, batch_size=batch_size, validation_split=1-train_ratio, callbacks=[callback], verbose=0)
281
  st.markdown('</div>', unsafe_allow_html=True)
282