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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -55
app.py CHANGED
@@ -11,14 +11,15 @@ 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
- st.sidebar.title("🔧 Model Settings")
 
15
 
16
  with st.sidebar.expander("🧠 Dataset Settings"):
17
  dataset = st.radio("Choose Dataset", ['Moons', 'Circles', 'Blobs'])
18
  noise = st.slider("Noise Level", 0.0, 0.2, 0.1)
19
  n_samples = st.slider("Number of Samples", 100, 1000, 300, step=50)
20
 
21
- with st.sidebar.expander("⚙️ Model Hyperparameters"):
22
  activation = st.selectbox("Activation Function", ['relu', 'sigmoid', 'tanh', 'elu'])
23
  lr = st.slider("Learning Rate", 0.001, 0.1, 0.01)
24
  split = st.slider("Train-Test Split", 0.1, 0.9, 0.2)
@@ -27,11 +28,15 @@ with st.sidebar.expander("⚙️ Model Hyperparameters"):
27
  num_neurons = st.slider("Neurons per Hidden Layer", 1, 100, 16)
28
  hidden_layers = st.slider("Number of Hidden Layers", 1, 5, 2)
29
 
30
- with st.sidebar.expander("🛠 Regularization"):
31
- use_earlystop = st.checkbox("Use EarlyStopping", value=True)
32
- use_dropout = st.checkbox("Use Dropout", value=True)
33
- dropout_rate = st.slider("Dropout Rate", 0.0, 0.5, 0.3) if use_dropout else 0.0
 
34
 
 
 
 
35
  if dataset == "Moons":
36
  x, y = make_moons(n_samples=n_samples, noise=noise, random_state=42)
37
  elif dataset == "Circles":
@@ -44,44 +49,36 @@ x = scaler.fit_transform(x)
44
 
45
  x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=split, random_state=27)
46
 
47
- callbacks = [EarlyStopping(patience=10, restore_best_weights=True)] if use_earlystop else []
48
-
49
- def build_model(with_dropout=False):
50
  model = Sequential()
51
  model.add(Input(shape=(2,)))
52
  for _ in range(hidden_layers):
53
  model.add(Dense(units=num_neurons, activation=activation))
54
- if with_dropout:
55
  model.add(Dropout(dropout_rate))
56
  model.add(Dense(1, activation="sigmoid"))
57
  model.compile(optimizer=Adam(learning_rate=lr), loss='binary_crossentropy', metrics=['accuracy'])
58
  return model
59
 
60
- base_model = build_model(False)
61
- dropout_model = build_model(True)
62
-
63
- base_hist = base_model.fit(x_train, y_train,
64
- validation_data=(x_test, y_test),
65
- batch_size=batch,
66
- epochs=epochs,
67
- callbacks=[],
68
- verbose=0)
69
-
70
- early_model = build_model(False)
71
- early_hist = early_model.fit(x_train, y_train,
72
- validation_data=(x_test, y_test),
73
- batch_size=batch,
74
- epochs=epochs,
75
- callbacks=callbacks,
76
- verbose=0)
77
-
78
- dropout_hist = dropout_model.fit(x_train, y_train,
79
- validation_data=(x_test, y_test),
80
- batch_size=batch,
81
- epochs=epochs,
82
- callbacks=callbacks,
83
- verbose=0)
84
 
 
 
 
85
  def plot_decision_boundary(model, title):
86
  x_min, x_max = x[:, 0].min() - 1, x[:, 0].max() + 1
87
  y_min, y_max = x[:, 1].min() - 1, x[:, 1].max() + 1
@@ -90,7 +87,7 @@ def plot_decision_boundary(model, title):
90
  grid = np.c_[xx.ravel(), yy.ravel()]
91
  preds = model.predict(grid, verbose=0).reshape(xx.shape)
92
 
93
- fig, ax = plt.subplots()
94
  ax.contourf(xx, yy, preds, cmap='RdBu', alpha=0.6)
95
  ax.scatter(x[:, 0], x[:, 1], c=y, cmap='RdBu', edgecolors='k', s=25)
96
  ax.set_title(title)
@@ -98,33 +95,28 @@ def plot_decision_boundary(model, title):
98
  ax.set_ylabel("Feature 2")
99
  return fig
100
 
101
- def plot_loss(history, title):
102
- fig, ax = plt.subplots()
 
103
  ax.plot(history.history['loss'], label='Train Loss')
104
  ax.plot(history.history['val_loss'], label='Val Loss')
105
  ax.set_title(title)
106
- ax.set_xlabel("Epochs")
107
  ax.set_ylabel("Loss")
108
  ax.legend()
109
  return fig
110
 
111
- st.title("🧪 Regularization Comparison")
112
-
113
- st.markdown("Below are the decision boundaries and loss curves for three configurations:")
114
 
115
- cols = st.columns(3)
 
116
 
117
- with cols[0]:
118
- st.markdown("### 🔹 Base Model")
119
- st.pyplot(plot_decision_boundary(base_model, "Base Model"))
120
- st.pyplot(plot_loss(base_hist, "Base Model Loss"))
121
 
122
- with cols[1]:
123
- st.markdown("### 🟢 With EarlyStopping")
124
- st.pyplot(plot_decision_boundary(early_model, "EarlyStopping"))
125
- st.pyplot(plot_loss(early_hist, "EarlyStopping Loss"))
126
-
127
- with cols[2]:
128
- st.markdown("### 🔸 With Dropout")
129
- st.pyplot(plot_decision_boundary(dropout_model, "Dropout Model"))
130
- st.pyplot(plot_loss(dropout_hist, "Dropout Loss"))
 
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)
 
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":
 
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
 
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)
 
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"))