Yuktha26 commited on
Commit
0fcdd11
ยท
verified ยท
1 Parent(s): ac0b398

Update pages/1_Random_Data.py

Browse files
Files changed (1) hide show
  1. pages/1_Random_Data.py +85 -55
pages/1_Random_Data.py CHANGED
@@ -9,6 +9,13 @@ from sklearn.preprocessing import StandardScaler
9
  st.title("๐Ÿ”ข Random Data Playground")
10
  st.markdown("Define hyperparameters, generate synthetic data, and train your neural network interactively.")
11
 
 
 
 
 
 
 
 
12
  with st.form("data_form"):
13
  st.subheader("๐Ÿ”ง Model Configuration")
14
  col1, col2 = st.columns(2)
@@ -39,7 +46,27 @@ if submitted:
39
  X_scaled = scaler.fit_transform(X)
40
  X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.3, random_state=42)
41
 
42
- # Decision Region Before Training
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  st.subheader("๐ŸŒ€ Generated Data & Decision Region (Before Training)")
44
  h = 0.02
45
  x_min, x_max = X_scaled[:, 0].min() - 1, X_scaled[:, 0].max() + 1
@@ -51,57 +78,60 @@ if submitted:
51
  st.pyplot(fig)
52
 
53
  if st.button("๐Ÿš€ Train Model"):
54
- progress_bar = st.progress(0)
55
- status_text = st.empty()
56
-
57
- # Build model
58
- model = tf.keras.Sequential()
59
- model.add(tf.keras.layers.Input(shape=(2,)))
60
- for _ in range(n_layers):
61
- model.add(tf.keras.layers.Dense(n_neurons, activation='relu'))
62
- model.add(tf.keras.layers.Dense(1, activation='sigmoid'))
63
-
64
- optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate)
65
- model.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy'])
66
-
67
- # Custom training loop to show progress
68
- class StreamlitCallback(tf.keras.callbacks.Callback):
69
- def on_epoch_end(self, epoch, logs=None):
70
- percent = (epoch + 1) / epochs
71
- progress_bar.progress(min(percent, 1.0))
72
- status_text.text(f"Epoch {epoch+1}/{epochs} - Loss: {logs['loss']:.4f}, Val Loss: {logs['val_loss']:.4f}")
73
-
74
- history = model.fit(
75
- X_train, y_train,
76
- batch_size=batch_size,
77
- epochs=epochs,
78
- validation_split=0.2,
79
- verbose=0,
80
- callbacks=[StreamlitCallback()]
81
- )
82
-
83
- st.success("โœ… Model Trained!")
84
-
85
- # Decision Region After Training
86
- st.subheader("๐ŸŒˆ Decision Region After Training")
87
- preds = model.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape)
88
- fig, ax = plt.subplots()
89
- ax.contourf(xx, yy, preds, cmap=plt.cm.RdBu, alpha=0.6)
90
- ax.scatter(X_scaled[:, 0], X_scaled[:, 1], c=y, cmap=plt.cm.bwr, edgecolor='k')
91
- st.pyplot(fig)
92
-
93
- # Loss Plot
94
- st.subheader("๐Ÿ“‰ Training vs Validation Loss")
95
- fig, ax = plt.subplots()
96
- ax.plot(history.history['loss'], label='Train Loss')
97
- ax.plot(history.history['val_loss'], label='Validation Loss')
98
- ax.set_xlabel("Epochs")
99
- ax.set_ylabel("Loss")
100
- ax.legend()
101
- st.pyplot(fig)
102
-
103
- # Loss values
104
- final_train_loss = history.history['loss'][-1]
105
- final_val_loss = history.history['val_loss'][-1]
106
- st.write(f"๐Ÿงฎ **Final Train Loss**: `{final_train_loss:.4f}`")
107
- st.write(f"๐Ÿงช **Final Validation Loss**: `{final_val_loss:.4f}`")
 
 
 
 
9
  st.title("๐Ÿ”ข Random Data Playground")
10
  st.markdown("Define hyperparameters, generate synthetic data, and train your neural network interactively.")
11
 
12
+ # Initialize session state variables
13
+ if 'train_requested' not in st.session_state:
14
+ st.session_state.train_requested = False
15
+ if 'data_ready' not in st.session_state:
16
+ st.session_state.data_ready = False
17
+
18
+ # Form for user input
19
  with st.form("data_form"):
20
  st.subheader("๐Ÿ”ง Model Configuration")
21
  col1, col2 = st.columns(2)
 
46
  X_scaled = scaler.fit_transform(X)
47
  X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.3, random_state=42)
48
 
49
+ # Save to session state
50
+ st.session_state.X_scaled = X_scaled
51
+ st.session_state.y = y
52
+ st.session_state.X_train = X_train
53
+ st.session_state.X_test = X_test
54
+ st.session_state.y_train = y_train
55
+ st.session_state.y_test = y_test
56
+ st.session_state.data_ready = True
57
+ st.session_state.hyperparams = {
58
+ 'batch_size': batch_size,
59
+ 'epochs': epochs,
60
+ 'learning_rate': learning_rate,
61
+ 'n_layers': n_layers,
62
+ 'n_neurons': n_neurons
63
+ }
64
+
65
+ # Visualize data
66
+ if st.session_state.data_ready:
67
+ X_scaled = st.session_state.X_scaled
68
+ y = st.session_state.y
69
+
70
  st.subheader("๐ŸŒ€ Generated Data & Decision Region (Before Training)")
71
  h = 0.02
72
  x_min, x_max = X_scaled[:, 0].min() - 1, X_scaled[:, 0].max() + 1
 
78
  st.pyplot(fig)
79
 
80
  if st.button("๐Ÿš€ Train Model"):
81
+ st.session_state.train_requested = True
82
+
83
+ # Train the model
84
+ if st.session_state.get("train_requested", False):
85
+ st.subheader("๐Ÿง  Training Model")
86
+ X_train = st.session_state.X_train
87
+ y_train = st.session_state.y_train
88
+ X_test = st.session_state.X_test
89
+ y_test = st.session_state.y_test
90
+ params = st.session_state.hyperparams
91
+
92
+ progress_bar = st.progress(0)
93
+ status_text = st.empty()
94
+
95
+ # Callback to update progress
96
+ class StreamlitCallback(tf.keras.callbacks.Callback):
97
+ def on_epoch_end(self, epoch, logs=None):
98
+ percent = (epoch + 1) / params['epochs']
99
+ progress_bar.progress(min(percent, 1.0))
100
+ status_text.text(f"Epoch {epoch+1}/{params['epochs']} - Loss: {logs['loss']:.4f}, Val Loss: {logs['val_loss']:.4f}")
101
+
102
+ # Build model
103
+ model = tf.keras.Sequential()
104
+ model.add(tf.keras.layers.Input(shape=(2,)))
105
+ for _ in range(params['n_layers']):
106
+ model.add(tf.keras.layers.Dense(params['n_neurons'], activation='relu'))
107
+ model.add(tf.keras.layers.Dense(1, activation='sigmoid'))
108
+
109
+ optimizer = tf.keras.optimizers.Adam(learning_rate=params['learning_rate'])
110
+ model.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy'])
111
+
112
+ history = model.fit(X_train, y_train, batch_size=params['batch_size'], epochs=params['epochs'],
113
+ validation_split=0.2, verbose=0, callbacks=[StreamlitCallback()])
114
+
115
+ st.success("โœ… Model Trained!")
116
+
117
+ # Decision Region After Training
118
+ st.subheader("๐ŸŒˆ Decision Region After Training")
119
+ preds = model.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape)
120
+ fig, ax = plt.subplots()
121
+ ax.contourf(xx, yy, preds, cmap=plt.cm.RdBu, alpha=0.6)
122
+ ax.scatter(X_scaled[:, 0], X_scaled[:, 1], c=y, cmap=plt.cm.bwr, edgecolor='k')
123
+ st.pyplot(fig)
124
+
125
+ # Loss Plots
126
+ st.subheader("๐Ÿ“ˆ Training vs Validation Loss")
127
+ fig, ax = plt.subplots()
128
+ ax.plot(history.history['loss'], label='Train Loss')
129
+ ax.plot(history.history['val_loss'], label='Validation Loss')
130
+ ax.set_xlabel("Epoch")
131
+ ax.set_ylabel("Loss")
132
+ ax.legend()
133
+ st.pyplot(fig)
134
+
135
+ # Display last values
136
+ st.markdown(f"**Final Train Loss:** {history.history['loss'][-1]:.4f}")
137
+ st.markdown(f"**Final Validation Loss:** {history.history['val_loss'][-1]:.4f}")