Surendradjh commited on
Commit
ebaf7b8
·
verified ·
1 Parent(s): e8b5ae4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +226 -77
app.py CHANGED
@@ -1,3 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  import numpy as np
3
  import matplotlib.pyplot as plt
@@ -11,75 +136,51 @@ from sklearn.datasets import make_moons, make_circles, make_blobs
11
  from sklearn.model_selection import train_test_split
12
  from sklearn.preprocessing import StandardScaler
13
 
14
- # Sidebar - Dataset and Hyperparameters
15
- st.sidebar.title("🔧 Model Configuration")
 
 
16
 
17
- with st.sidebar.expander("🧠 Dataset Settings"):
18
- dataset = st.radio("Choose Dataset", ['Moons', 'Circles', 'Blobs'])
19
- noise = st.slider("Noise Level", 0.0, 0.2, 0.1)
20
- n_samples = st.slider("Number of Samples", 100, 1000, 300, step=50)
 
 
 
 
 
 
 
21
 
22
- with st.sidebar.expander("⚙️ Hyperparameters"):
23
- activation = st.selectbox("Activation Function", ['relu', 'sigmoid', 'tanh', 'elu'])
24
- lr = st.slider("Learning Rate", 0.001, 0.1, 0.01)
25
- split = st.slider("Train-Test Split", 0.1, 0.9, 0.2)
26
- batch = st.select_slider("Batch Size", options=list(range(8, 129, 8)), value=32)
27
- epochs = st.slider("Epochs", 10, 200, 50)
28
- num_neurons = st.slider("Neurons per Hidden Layer", 1, 100, 16)
29
- hidden_layers = st.slider("Number of Hidden Layers", 1, 5, 2)
30
 
31
- # Model selection radio
32
- model_choice = st.radio(
33
- "🛠 Choose Model Variation",
34
- ["Base Model", "EarlyStopping", "Dropout"]
35
- )
36
 
37
- dropout_rate = 0.3 # fixed dropout rate
 
 
 
 
 
 
38
 
39
- # Dataset generation
40
- if dataset == "Moons":
41
- x, y = make_moons(n_samples=n_samples, noise=noise, random_state=42)
42
- elif dataset == "Circles":
43
- x, y = make_circles(n_samples=n_samples, noise=noise, random_state=42)
44
- else:
45
- x, y = make_blobs(n_samples=n_samples, centers=2, cluster_std=1.5, random_state=42)
 
 
46
 
47
- scaler = StandardScaler()
48
- x = scaler.fit_transform(x)
49
 
50
- x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=split, random_state=27)
51
-
52
- # Build model
53
- def build_model(use_dropout=False):
54
- model = Sequential()
55
- model.add(Input(shape=(2,)))
56
- for _ in range(hidden_layers):
57
- model.add(Dense(units=num_neurons, activation=activation))
58
- if use_dropout:
59
- model.add(Dropout(dropout_rate))
60
- model.add(Dense(1, activation="sigmoid"))
61
- model.compile(optimizer=Adam(learning_rate=lr), loss='binary_crossentropy', metrics=['accuracy'])
62
- return model
63
-
64
- # Callback
65
- callbacks = [EarlyStopping(patience=10, restore_best_weights=True)] if model_choice == "EarlyStopping" else []
66
-
67
- # Choose dropout condition
68
- use_dropout = model_choice == "Dropout"
69
-
70
- # Train model
71
- model = build_model(use_dropout=use_dropout)
72
- history = model.fit(x_train, y_train,
73
- validation_data=(x_test, y_test),
74
- batch_size=batch,
75
- epochs=epochs,
76
- callbacks=callbacks,
77
- verbose=0)
78
-
79
- test_loss, test_acc = model.evaluate(x_test, y_test, verbose=0)
80
-
81
- # Plot decision boundary
82
- def plot_decision_boundary(model, title):
83
  x_min, x_max = x[:, 0].min() - 1, x[:, 0].max() + 1
84
  y_min, y_max = x[:, 1].min() - 1, x[:, 1].max() + 1
85
  xx, yy = np.meshgrid(np.linspace(x_min, x_max, 300),
@@ -87,36 +188,84 @@ def plot_decision_boundary(model, title):
87
  grid = np.c_[xx.ravel(), yy.ravel()]
88
  preds = model.predict(grid, verbose=0).reshape(xx.shape)
89
 
90
- fig, ax = plt.subplots(figsize=(7, 6))
91
  ax.contourf(xx, yy, preds, cmap='RdBu', alpha=0.6)
92
  ax.scatter(x[:, 0], x[:, 1], c=y, cmap='RdBu', edgecolors='k', s=25)
93
- ax.set_title(title)
94
  ax.set_xlabel("Feature 1")
95
  ax.set_ylabel("Feature 2")
96
  return fig
97
 
98
- # Plot training loss
99
- def plot_loss_curve(history, title):
100
  fig, ax = plt.subplots(figsize=(7, 4))
101
  ax.plot(history.history['loss'], label='Train Loss')
102
  ax.plot(history.history['val_loss'], label='Val Loss')
103
- ax.set_title(title)
104
  ax.set_xlabel("Epoch")
105
  ax.set_ylabel("Loss")
106
  ax.legend()
107
  return fig
108
 
109
- # Main UI
110
- st.title("🧪 Neural Network Regularization Explorer")
111
- st.markdown(f"### Currently Selected: **{model_choice}**")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
- st.success(f"**Test Accuracy:** {test_acc:.4f}")
114
- st.info(f"**Test Loss:** {test_loss:.4f}")
115
 
116
- # Plot dropdown
117
- plot_type = st.selectbox("📊 Select Plot to View", ["Decision Boundary", "Loss Curve"])
118
 
119
- if plot_type == "Decision Boundary":
120
- st.pyplot(plot_decision_boundary(model, f"{model_choice} Decision Boundary"))
121
  else:
122
- st.pyplot(plot_loss_curve(history, f"{model_choice} Loss Curve"))
 
1
+ # import streamlit as st
2
+ # import numpy as np
3
+ # import matplotlib.pyplot as plt
4
+
5
+ # from tensorflow.keras.models import Sequential
6
+ # from tensorflow.keras.layers import Dense, Input, Dropout
7
+ # from tensorflow.keras.optimizers import Adam
8
+ # from tensorflow.keras.callbacks import EarlyStopping
9
+
10
+ # from sklearn.datasets import make_moons, make_circles, make_blobs
11
+ # from sklearn.model_selection import train_test_split
12
+ # from sklearn.preprocessing import StandardScaler
13
+
14
+ # # Sidebar - Dataset and Hyperparameters
15
+ # st.sidebar.title("🔧 Model Configuration")
16
+
17
+ # with st.sidebar.expander("🧠 Dataset Settings"):
18
+ # dataset = st.radio("Choose Dataset", ['Moons', 'Circles', 'Blobs'])
19
+ # noise = st.slider("Noise Level", 0.0, 0.2, 0.1)
20
+ # n_samples = st.slider("Number of Samples", 100, 1000, 300, step=50)
21
+
22
+ # with st.sidebar.expander("⚙️ Hyperparameters"):
23
+ # activation = st.selectbox("Activation Function", ['relu', 'sigmoid', 'tanh', 'elu'])
24
+ # lr = st.slider("Learning Rate", 0.001, 0.1, 0.01)
25
+ # split = st.slider("Train-Test Split", 0.1, 0.9, 0.2)
26
+ # batch = st.select_slider("Batch Size", options=list(range(8, 129, 8)), value=32)
27
+ # epochs = st.slider("Epochs", 10, 200, 50)
28
+ # num_neurons = st.slider("Neurons per Hidden Layer", 1, 100, 16)
29
+ # hidden_layers = st.slider("Number of Hidden Layers", 1, 5, 2)
30
+
31
+ # # Model selection radio
32
+ # model_choice = st.radio(
33
+ # "🛠 Choose Model Variation",
34
+ # ["Base Model", "EarlyStopping", "Dropout"]
35
+ # )
36
+
37
+ # dropout_rate = 0.3 # fixed dropout rate
38
+
39
+ # # Dataset generation
40
+ # if dataset == "Moons":
41
+ # x, y = make_moons(n_samples=n_samples, noise=noise, random_state=42)
42
+ # elif dataset == "Circles":
43
+ # x, y = make_circles(n_samples=n_samples, noise=noise, random_state=42)
44
+ # else:
45
+ # x, y = make_blobs(n_samples=n_samples, centers=2, cluster_std=1.5, random_state=42)
46
+
47
+ # scaler = StandardScaler()
48
+ # x = scaler.fit_transform(x)
49
+
50
+ # x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=split, random_state=27)
51
+
52
+ # # Build model
53
+ # def build_model(use_dropout=False):
54
+ # model = Sequential()
55
+ # model.add(Input(shape=(2,)))
56
+ # for _ in range(hidden_layers):
57
+ # model.add(Dense(units=num_neurons, activation=activation))
58
+ # if use_dropout:
59
+ # model.add(Dropout(dropout_rate))
60
+ # model.add(Dense(1, activation="sigmoid"))
61
+ # model.compile(optimizer=Adam(learning_rate=lr), loss='binary_crossentropy', metrics=['accuracy'])
62
+ # return model
63
+
64
+ # # Callback
65
+ # callbacks = [EarlyStopping(patience=10, restore_best_weights=True)] if model_choice == "EarlyStopping" else []
66
+
67
+ # # Choose dropout condition
68
+ # use_dropout = model_choice == "Dropout"
69
+
70
+ # # Train model
71
+ # model = build_model(use_dropout=use_dropout)
72
+ # history = model.fit(x_train, y_train,
73
+ # validation_data=(x_test, y_test),
74
+ # batch_size=batch,
75
+ # epochs=epochs,
76
+ # callbacks=callbacks,
77
+ # verbose=0)
78
+
79
+ # test_loss, test_acc = model.evaluate(x_test, y_test, verbose=0)
80
+
81
+ # # Plot decision boundary
82
+ # def plot_decision_boundary(model, title):
83
+ # x_min, x_max = x[:, 0].min() - 1, x[:, 0].max() + 1
84
+ # y_min, y_max = x[:, 1].min() - 1, x[:, 1].max() + 1
85
+ # xx, yy = np.meshgrid(np.linspace(x_min, x_max, 300),
86
+ # np.linspace(y_min, y_max, 300))
87
+ # grid = np.c_[xx.ravel(), yy.ravel()]
88
+ # preds = model.predict(grid, verbose=0).reshape(xx.shape)
89
+
90
+ # fig, ax = plt.subplots(figsize=(7, 6))
91
+ # ax.contourf(xx, yy, preds, cmap='RdBu', alpha=0.6)
92
+ # ax.scatter(x[:, 0], x[:, 1], c=y, cmap='RdBu', edgecolors='k', s=25)
93
+ # ax.set_title(title)
94
+ # ax.set_xlabel("Feature 1")
95
+ # ax.set_ylabel("Feature 2")
96
+ # return fig
97
+
98
+ # # Plot training loss
99
+ # def plot_loss_curve(history, title):
100
+ # fig, ax = plt.subplots(figsize=(7, 4))
101
+ # ax.plot(history.history['loss'], label='Train Loss')
102
+ # ax.plot(history.history['val_loss'], label='Val Loss')
103
+ # ax.set_title(title)
104
+ # ax.set_xlabel("Epoch")
105
+ # ax.set_ylabel("Loss")
106
+ # ax.legend()
107
+ # return fig
108
+
109
+ # # Main UI
110
+ # st.title("🧪 Neural Network Regularization Explorer")
111
+ # st.markdown(f"### Currently Selected: **{model_choice}**")
112
+
113
+ # st.success(f"**Test Accuracy:** {test_acc:.4f}")
114
+ # st.info(f"**Test Loss:** {test_loss:.4f}")
115
+
116
+ # # Plot dropdown
117
+ # plot_type = st.selectbox("📊 Select Plot to View", ["Decision Boundary", "Loss Curve"])
118
+
119
+ # if plot_type == "Decision Boundary":
120
+ # st.pyplot(plot_decision_boundary(model, f"{model_choice} Decision Boundary"))
121
+ # else:
122
+ # st.pyplot(plot_loss_curve(history, f"{model_choice} Loss Curve"))
123
+
124
+
125
+
126
  import streamlit as st
127
  import numpy as np
128
  import matplotlib.pyplot as plt
 
136
  from sklearn.model_selection import train_test_split
137
  from sklearn.preprocessing import StandardScaler
138
 
139
+ # Caching utility
140
+ @st.cache_resource
141
+ def train_models(params):
142
+ models_data = {}
143
 
144
+ def build_model(use_dropout=False):
145
+ model = Sequential()
146
+ model.add(Input(shape=(2,)))
147
+ for _ in range(params['hidden_layers']):
148
+ model.add(Dense(params['num_neurons'], activation=params['activation']))
149
+ if use_dropout:
150
+ model.add(Dropout(params['dropout_rate']))
151
+ model.add(Dense(1, activation="sigmoid"))
152
+ model.compile(optimizer=Adam(learning_rate=params['lr']),
153
+ loss='binary_crossentropy', metrics=['accuracy'])
154
+ return model
155
 
156
+ callbacks = [EarlyStopping(patience=10, restore_best_weights=True)]
 
 
 
 
 
 
 
157
 
158
+ for mode in ['Base Model', 'EarlyStopping', 'Dropout']:
159
+ use_dropout = (mode == 'Dropout')
160
+ use_callbacks = callbacks if mode == 'EarlyStopping' else []
 
 
161
 
162
+ model = build_model(use_dropout)
163
+ history = model.fit(params['x_train'], params['y_train'],
164
+ validation_data=(params['x_test'], params['y_test']),
165
+ batch_size=params['batch'],
166
+ epochs=params['epochs'],
167
+ callbacks=use_callbacks,
168
+ verbose=0)
169
 
170
+ test_loss, test_acc = model.evaluate(params['x_test'], params['y_test'], verbose=0)
171
+ models_data[mode] = {
172
+ 'model': model,
173
+ 'history': history,
174
+ 'test_loss': test_loss,
175
+ 'test_acc': test_acc,
176
+ 'decision_fig': plot_decision_boundary(model, params['x'], params['y']),
177
+ 'loss_fig': plot_loss_curve(history)
178
+ }
179
 
180
+ return models_data
 
181
 
182
+ # Plotting functions
183
+ def plot_decision_boundary(model, x, y):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
  x_min, x_max = x[:, 0].min() - 1, x[:, 0].max() + 1
185
  y_min, y_max = x[:, 1].min() - 1, x[:, 1].max() + 1
186
  xx, yy = np.meshgrid(np.linspace(x_min, x_max, 300),
 
188
  grid = np.c_[xx.ravel(), yy.ravel()]
189
  preds = model.predict(grid, verbose=0).reshape(xx.shape)
190
 
191
+ fig, ax = plt.subplots(figsize=(7, 5))
192
  ax.contourf(xx, yy, preds, cmap='RdBu', alpha=0.6)
193
  ax.scatter(x[:, 0], x[:, 1], c=y, cmap='RdBu', edgecolors='k', s=25)
194
+ ax.set_title("Decision Boundary")
195
  ax.set_xlabel("Feature 1")
196
  ax.set_ylabel("Feature 2")
197
  return fig
198
 
199
+ def plot_loss_curve(history):
 
200
  fig, ax = plt.subplots(figsize=(7, 4))
201
  ax.plot(history.history['loss'], label='Train Loss')
202
  ax.plot(history.history['val_loss'], label='Val Loss')
203
+ ax.set_title("Loss Curve")
204
  ax.set_xlabel("Epoch")
205
  ax.set_ylabel("Loss")
206
  ax.legend()
207
  return fig
208
 
209
+ # UI: Sidebar Parameters
210
+ st.sidebar.title("Model Controls")
211
+
212
+ dataset = st.sidebar.selectbox("Dataset", ["Moons", "Circles", "Blobs"])
213
+ noise = st.sidebar.slider("Noise Level", 0.0, 0.2, 0.1)
214
+ n_samples = st.sidebar.slider("Number of Samples", 100, 1000, 300, step=50)
215
+
216
+ activation = st.sidebar.selectbox("Activation", ['relu', 'sigmoid', 'tanh', 'elu'])
217
+ lr = st.sidebar.slider("Learning Rate", 0.001, 0.1, 0.01)
218
+ split = st.sidebar.slider("Train-Test Split", 0.1, 0.9, 0.2)
219
+ batch = st.sidebar.select_slider("Batch Size", list(range(8, 129, 8)), value=32)
220
+ epochs = st.sidebar.slider("Epochs", 10, 200, 50)
221
+ num_neurons = st.sidebar.slider("Neurons per Hidden Layer", 1, 100, 16)
222
+ hidden_layers = st.sidebar.slider("Hidden Layers", 1, 5, 2)
223
+ dropout_rate = 0.3
224
+
225
+ # Data Preparation
226
+ if dataset == "Moons":
227
+ x, y = make_moons(n_samples=n_samples, noise=noise, random_state=42)
228
+ elif dataset == "Circles":
229
+ x, y = make_circles(n_samples=n_samples, noise=noise, random_state=42)
230
+ else:
231
+ x, y = make_blobs(n_samples=n_samples, centers=2, cluster_std=1.5, random_state=42)
232
+
233
+ scaler = StandardScaler()
234
+ x = scaler.fit_transform(x)
235
+ x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=split, random_state=27)
236
+
237
+ params = {
238
+ 'x': x,
239
+ 'y': y,
240
+ 'x_train': x_train,
241
+ 'x_test': x_test,
242
+ 'y_train': y_train,
243
+ 'y_test': y_test,
244
+ 'activation': activation,
245
+ 'lr': lr,
246
+ 'batch': batch,
247
+ 'epochs': epochs,
248
+ 'num_neurons': num_neurons,
249
+ 'hidden_layers': hidden_layers,
250
+ 'dropout_rate': dropout_rate,
251
+ }
252
+
253
+ # Train all models ONCE
254
+ with st.spinner("Training models, please wait..."):
255
+ model_results = train_models(params)
256
+
257
+ # UI: Select which model and plot to show
258
+ st.title("⚡ Neural Net Regularization Visualizer")
259
+ model_choice = st.radio("Choose Model", ["Base Model", "EarlyStopping", "Dropout"])
260
+ plot_choice = st.selectbox("Select Plot", ["Decision Boundary", "Loss Curve"])
261
 
262
+ # Display results
263
+ selected = model_results[model_choice]
264
 
265
+ st.subheader(f"Test Accuracy: {selected['test_acc']:.4f}")
266
+ st.caption(f"Test Loss: {selected['test_loss']:.4f}")
267
 
268
+ if plot_choice == "Decision Boundary":
269
+ st.pyplot(selected['decision_fig'])
270
  else:
271
+ st.pyplot(selected['loss_fig'])