Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import tensorflow as tf
|
| 3 |
+
import numpy as np
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
from sklearn.datasets import make_moons, make_circles, make_blobs
|
| 6 |
+
from sklearn.model_selection import train_test_split
|
| 7 |
+
from sklearn.preprocessing import StandardScaler
|
| 8 |
+
from tensorflow.keras import models, layers, optimizers
|
| 9 |
+
|
| 10 |
+
# --- Dataset Generator ---
|
| 11 |
+
def get_dataset(name, n_samples=1000, noise=0.2):
|
| 12 |
+
if name == "Moons":
|
| 13 |
+
return make_moons(n_samples=n_samples, noise=noise)
|
| 14 |
+
elif name == "Circles":
|
| 15 |
+
return make_circles(n_samples=n_samples, noise=noise)
|
| 16 |
+
else:
|
| 17 |
+
return make_blobs(n_samples=n_samples, centers=2, cluster_std=1.5, random_state=42)
|
| 18 |
+
|
| 19 |
+
# --- Model Builder ---
|
| 20 |
+
def build_model(activation, lr, num_layers, num_neurons):
|
| 21 |
+
model = models.Sequential([layers.Input(shape=(2,))])
|
| 22 |
+
for _ in range(num_layers):
|
| 23 |
+
model.add(layers.Dense(num_neurons, activation=activation))
|
| 24 |
+
model.add(layers.Dense(1, activation='sigmoid'))
|
| 25 |
+
model.compile(optimizer=optimizers.Adam(learning_rate=lr),
|
| 26 |
+
loss='binary_crossentropy', metrics=['accuracy'])
|
| 27 |
+
return model
|
| 28 |
+
|
| 29 |
+
# --- Decision Boundary Plotter ---
|
| 30 |
+
def visualize_decision_boundary(model, X, y):
|
| 31 |
+
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
|
| 32 |
+
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
|
| 33 |
+
xx, yy = np.meshgrid(np.linspace(x_min, x_max, 300),
|
| 34 |
+
np.linspace(y_min, y_max, 300))
|
| 35 |
+
grid = np.c_[xx.ravel(), yy.ravel()]
|
| 36 |
+
preds = model.predict(grid, verbose=0).reshape(xx.shape)
|
| 37 |
+
|
| 38 |
+
fig, ax = plt.subplots(figsize=(7, 6))
|
| 39 |
+
ax.contourf(xx, yy, preds, cmap='RdBu', alpha=0.6)
|
| 40 |
+
ax.scatter(X[:, 0], X[:, 1], c=y, cmap='RdBu', edgecolors='k', s=25)
|
| 41 |
+
ax.set(title="Decision Boundary", xlabel="Feature 1", ylabel="Feature 2")
|
| 42 |
+
return fig
|
| 43 |
+
|
| 44 |
+
# --- Loss Plotter ---
|
| 45 |
+
def plot_loss(history):
|
| 46 |
+
fig, ax = plt.subplots(figsize=(7, 5))
|
| 47 |
+
ax.plot(history.history['loss'], label='Train Loss')
|
| 48 |
+
ax.plot(history.history['val_loss'], label='Test Loss')
|
| 49 |
+
ax.set(title="Training vs Testing Loss", xlabel="Epoch", ylabel="Loss")
|
| 50 |
+
ax.legend()
|
| 51 |
+
ax.grid(True, linestyle='--', alpha=0.7)
|
| 52 |
+
return fig
|
| 53 |
+
|
| 54 |
+
# --- Streamlit UI ---
|
| 55 |
+
st.set_page_config(page_title="TensorFlow Playground", layout="centered")
|
| 56 |
+
st.title("🧠 TensorFlow Playground")
|
| 57 |
+
st.write("Explore how hyperparameters affect decision boundaries in neural networks.")
|
| 58 |
+
|
| 59 |
+
# --- Sidebar Controls ---
|
| 60 |
+
st.sidebar.header("🔧 Hyperparameters")
|
| 61 |
+
dataset = st.sidebar.selectbox("Select Dataset", ["Moons", "Circles", "Blobs"])
|
| 62 |
+
noise = st.sidebar.slider("Dataset Noise", 0.0, 1.0, 0.2, 0.01)
|
| 63 |
+
activation = st.sidebar.selectbox("Activation Function", ["relu", "sigmoid", "tanh"])
|
| 64 |
+
lr = st.sidebar.slider("Learning Rate", 0.001, 0.1, 0.01, 0.001)
|
| 65 |
+
split = st.sidebar.slider("Train-Test Split", 0.1, 0.9, 0.7, 0.05)
|
| 66 |
+
batch = st.sidebar.select_slider("Batch Size", options=list(range(8, 129, 8)), value=32)
|
| 67 |
+
epochs = st.sidebar.slider("Epochs", 10, 300, 100, 10)
|
| 68 |
+
num_neurons = st.sidebar.slider("Neurons/Layer", 1, 100, 10)
|
| 69 |
+
num_layers = st.sidebar.slider("Hidden Layers", 1, 5, 2)
|
| 70 |
+
|
| 71 |
+
# --- Train Button ---
|
| 72 |
+
if st.button("🚀 Train Model"):
|
| 73 |
+
with st.spinner("Training the model..."):
|
| 74 |
+
X, y = get_dataset(dataset, noise=noise)
|
| 75 |
+
X = StandardScaler().fit_transform(X)
|
| 76 |
+
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=split, random_state=42)
|
| 77 |
+
|
| 78 |
+
model = build_model(activation, lr, num_layers, num_neurons)
|
| 79 |
+
history = model.fit(X_train, y_train, validation_data=(X_test, y_test),
|
| 80 |
+
batch_size=batch, epochs=epochs, verbose=0)
|
| 81 |
+
|
| 82 |
+
test_loss, test_acc = model.evaluate(X_test, y_test, verbose=0)
|
| 83 |
+
st.success(f"✅ Trained Successfully! Test Accuracy: {test_acc:.2f}")
|
| 84 |
+
|
| 85 |
+
st.subheader("📊 Decision Boundary")
|
| 86 |
+
st.pyplot(visualize_decision_boundary(model, X, y))
|
| 87 |
+
|
| 88 |
+
st.subheader("📈 Loss Over Epochs")
|
| 89 |
+
st.pyplot(plot_loss(history))
|