DOMMETI commited on
Commit
da3dfc7
Β·
verified Β·
1 Parent(s): 2f8fda8

Update pages/1_User_Defined_DataLab.py

Browse files
Files changed (1) hide show
  1. pages/1_User_Defined_DataLab.py +47 -26
pages/1_User_Defined_DataLab.py CHANGED
@@ -10,17 +10,17 @@ from sklearn.model_selection import train_test_split
10
  from mlxtend.plotting import plot_decision_regions
11
  import numpy as np
12
 
 
13
  st.title("🧠 Neural Network Playground - Custom Dataset")
14
 
15
- # User input parameters
16
  n_samples = st.slider("Number of Samples", 100, 1000, 300)
17
  noise = st.slider("Noise Level", 0.0, 1.0, 0.2)
18
  random_state = st.number_input("Random State", value=42)
19
 
20
- # Generate synthetic 2-feature data
21
  X, y = make_classification(n_samples=n_samples, n_features=2, n_redundant=0,
22
- n_informative=2, n_clusters_per_class=1, flip_y=noise,
23
- random_state=random_state, class_sep=4)
24
 
25
  df = pd.DataFrame(X, columns=["X1", "X2"])
26
  df["label"] = y
@@ -28,49 +28,70 @@ df["label"] = y
28
  st.write("### πŸ“„ Preview of Generated Data")
29
  st.dataframe(df.head())
30
 
31
- st.session_state['X'] = X
32
- st.session_state['y'] = y
33
-
34
  # Scatter plot
35
  st.write("### 🎯 Feature Scatter Plot by Class Label")
36
  fig, ax = plt.subplots()
37
  sns.scatterplot(data=df, x="X1", y="X2", hue="label", palette="deep", ax=ax)
38
  st.pyplot(fig)
39
 
40
- # Sidebar - Network Config
41
- st.sidebar.title("πŸ› οΈ Network Configuration")
42
  n_layers = st.sidebar.slider("Number of Hidden Layers", 1, 4, 2)
43
  hidden_activation = st.sidebar.selectbox("Activation for Hidden Layers", ["tanh", "sigmoid"])
44
 
45
  hidden_config = []
46
  for i in range(n_layers):
47
- units = st.sidebar.slider(f"Neurons in Layer {i+1}", 1, 10, 4)
48
  hidden_config.append(units)
49
 
50
  learning_rate = st.sidebar.slider("Learning Rate", 0.0001, 1.0, 0.1, step=0.0001, format="%.4f")
51
- batch_size = st.sidebar.slider("Batch Size", 1, 1000, 200)
52
  epochs = st.sidebar.slider("Epochs", 100, 2000, 350, step=50)
53
 
54
  # Train model
55
  if st.button("πŸš€ Train Model"):
56
- X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
- model = Sequential()
59
- model.add(InputLayer(shape=(2,)))
60
- for units in hidden_config:
61
- model.add(Dense(units, activation=hidden_activation))
62
- model.add(Dense(1, activation="sigmoid"))
63
 
64
- model.compile(optimizer=SGD(learning_rate=learning_rate),
65
- loss='binary_crossentropy',
66
- metrics=['accuracy'])
 
67
 
68
- history = model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs, validation_split=0.2, verbose=0)
 
69
 
70
- # Plot decision region
71
- st.write("### 🧭 Decision Boundary")
 
 
72
  fig2, ax2 = plt.subplots()
73
- plot_decision_regions(X=X, y=y.astype(int),
74
- clf=lambda X_: (model.predict(X_) > 0.5).astype(int).flatten(),
75
- legend=2, ax=ax2)
76
  st.pyplot(fig2)
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  from mlxtend.plotting import plot_decision_regions
11
  import numpy as np
12
 
13
+ st.set_page_config(layout="wide")
14
  st.title("🧠 Neural Network Playground - Custom Dataset")
15
 
16
+ # Generate synthetic 2-feature dataset
17
  n_samples = st.slider("Number of Samples", 100, 1000, 300)
18
  noise = st.slider("Noise Level", 0.0, 1.0, 0.2)
19
  random_state = st.number_input("Random State", value=42)
20
 
 
21
  X, y = make_classification(n_samples=n_samples, n_features=2, n_redundant=0,
22
+ n_informative=2, n_clusters_per_class=1,
23
+ flip_y=noise, random_state=random_state, class_sep=4)
24
 
25
  df = pd.DataFrame(X, columns=["X1", "X2"])
26
  df["label"] = y
 
28
  st.write("### πŸ“„ Preview of Generated Data")
29
  st.dataframe(df.head())
30
 
 
 
 
31
  # Scatter plot
32
  st.write("### 🎯 Feature Scatter Plot by Class Label")
33
  fig, ax = plt.subplots()
34
  sns.scatterplot(data=df, x="X1", y="X2", hue="label", palette="deep", ax=ax)
35
  st.pyplot(fig)
36
 
37
+ # Sidebar - Model Configuration
38
+ st.sidebar.title("πŸ› οΈ Neural Network Configuration")
39
  n_layers = st.sidebar.slider("Number of Hidden Layers", 1, 4, 2)
40
  hidden_activation = st.sidebar.selectbox("Activation for Hidden Layers", ["tanh", "sigmoid"])
41
 
42
  hidden_config = []
43
  for i in range(n_layers):
44
+ units = st.sidebar.slider(f"Neurons in Layer {i+1}", 1, 10, 4, key=f"layer_{i}")
45
  hidden_config.append(units)
46
 
47
  learning_rate = st.sidebar.slider("Learning Rate", 0.0001, 1.0, 0.1, step=0.0001, format="%.4f")
48
+ batch_size = st.sidebar.slider("Batch Size", 1, 512, 64)
49
  epochs = st.sidebar.slider("Epochs", 100, 2000, 350, step=50)
50
 
51
  # Train model
52
  if st.button("πŸš€ Train Model"):
53
+ with st.spinner("Training in progress... please wait ⏳"):
54
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
55
+
56
+ # Build model
57
+ model = Sequential()
58
+ model.add(InputLayer(shape=(2,)))
59
+ for units in hidden_config:
60
+ model.add(Dense(units, activation=hidden_activation))
61
+ model.add(Dense(1, activation="sigmoid"))
62
+
63
+ model.compile(optimizer=SGD(learning_rate=learning_rate),
64
+ loss='binary_crossentropy',
65
+ metrics=['accuracy'])
66
 
67
+ history = model.fit(X_train, y_train, batch_size=batch_size,
68
+ epochs=epochs, validation_split=0.2, verbose=0)
 
 
 
69
 
70
+ # βœ… Keras model wrapper for mlxtend
71
+ class KerasClassifierWrapper:
72
+ def __init__(self, model):
73
+ self.model = model
74
 
75
+ def predict(self, X):
76
+ return (self.model.predict(X) > 0.5).astype(int).flatten()
77
 
78
+ wrapped_model = KerasClassifierWrapper(model)
79
+
80
+ # 🎯 Plot decision region
81
+ st.subheader("🧭 Decision Region")
82
  fig2, ax2 = plt.subplots()
83
+ plot_decision_regions(X=X, y=y.astype(int),
84
+ clf=wrapped_model, legend=2, ax=ax2)
 
85
  st.pyplot(fig2)
86
+
87
+ # πŸ“‰ Plot training history
88
+ st.subheader("πŸ“ˆ Training & Validation Loss")
89
+ fig3, ax3 = plt.subplots()
90
+ ax3.plot(history.history['loss'], label='Train Loss')
91
+ ax3.plot(history.history['val_loss'], label='Val Loss')
92
+ ax3.set_xlabel("Epochs")
93
+ ax3.set_ylabel("Loss")
94
+ ax3.legend()
95
+ st.pyplot(fig3)
96
+
97
+ st.success("βœ… Model training completed!")