Spaces:
Sleeping
Sleeping
Update pages/1_Random_Data.py
Browse files- 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 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 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}")
|