zoya23 commited on
Commit
5c16c9d
·
verified ·
1 Parent(s): 8876313

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -39
app.py CHANGED
@@ -1,69 +1,83 @@
 
1
  import streamlit as st
2
  import numpy as np
3
- from sklearn.datasets import make_circles
 
4
  from sklearn.model_selection import train_test_split
5
  from sklearn.preprocessing import StandardScaler
6
  from tensorflow.keras.models import Sequential
7
  from tensorflow.keras.layers import Dense
8
  from tensorflow.keras.optimizers import Adam
9
- import matplotlib.pyplot as plt
10
-
11
- # Set Streamlit page config
12
- st.set_page_config(page_title="ML Playground", layout="centered")
13
 
 
14
  st.title("🧠 TensorFlow Playground Clone")
15
- st.markdown("Train a simple neural network on a synthetic dataset like circles")
16
 
17
  # Sidebar controls
18
- st.sidebar.header("Model Settings")
 
 
 
19
 
20
- # Dataset
21
- dataset = st.sidebar.selectbox("Dataset", ["Circle"])
22
- n_samples = st.sidebar.slider("Number of Samples", 100, 1000, 300)
23
-
24
- # Model settings
25
- layers = st.sidebar.text_input("Network Shape (comma-separated)", "4,2")
26
- activation = st.sidebar.selectbox("Activation", ["relu", "tanh", "sigmoid"])
27
- learning_rate = st.sidebar.slider("Learning Rate", 0.001, 0.1, 0.03, step=0.001)
28
- epochs = st.sidebar.slider("Epochs", 10, 200, 50)
29
 
30
  # Generate dataset
31
- X, y = make_circles(n_samples=n_samples, factor=0.5, noise=0.05, random_state=0)
 
 
 
 
 
 
 
32
  X = StandardScaler().fit_transform(X)
33
- X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=42)
34
 
35
  # Build model
36
  model = Sequential()
37
  layer_sizes = [int(n.strip()) for n in layers.split(",") if n.strip().isdigit()]
38
- input_dim = X.shape[1]
39
-
40
- # Input + hidden layers
41
- model.add(Dense(layer_sizes[0], input_dim=input_dim, activation=activation))
42
  for size in layer_sizes[1:]:
43
  model.add(Dense(size, activation=activation))
 
 
44
 
45
- # Output layer
46
- model.add(Dense(1, activation='sigmoid'))
47
-
48
- optimizer = Adam(learning_rate=learning_rate)
49
- model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy'])
50
-
51
- # Training
52
  with st.spinner("Training model..."):
53
- history = model.fit(X_train, y_train, epochs=epochs, verbose=0, validation_data=(X_test, y_test))
 
 
 
 
 
54
 
55
- # Plotting
56
  fig, ax = plt.subplots()
57
- ax.plot(history.history['accuracy'], label='Train Accuracy')
58
- ax.plot(history.history['val_accuracy'], label='Val Accuracy')
59
- ax.set_title("Training Progress")
60
  ax.set_xlabel("Epoch")
61
  ax.set_ylabel("Accuracy")
62
  ax.legend()
63
  st.pyplot(fig)
64
 
65
- # Final Accuracy
66
- train_acc = model.evaluate(X_train, y_train, verbose=0)[1]
67
- test_acc = model.evaluate(X_test, y_test, verbose=0)[1]
68
- st.success(f"✅ Final Training Accuracy: {train_acc:.2f}")
69
- st.success(f"✅ Final Testing Accuracy: {test_acc:.2f}")
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
  import streamlit as st
3
  import numpy as np
4
+ import matplotlib.pyplot as plt
5
+ from sklearn.datasets import make_circles, make_moons, make_classification
6
  from sklearn.model_selection import train_test_split
7
  from sklearn.preprocessing import StandardScaler
8
  from tensorflow.keras.models import Sequential
9
  from tensorflow.keras.layers import Dense
10
  from tensorflow.keras.optimizers import Adam
 
 
 
 
11
 
12
+ st.set_page_config(page_title="TF Playground", layout="wide")
13
  st.title("🧠 TensorFlow Playground Clone")
 
14
 
15
  # Sidebar controls
16
+ st.sidebar.header("1. Dataset Options")
17
+ dataset = st.sidebar.selectbox("Select Dataset", ["circle", "moons", "linear","guassian"])
18
+ noise = st.sidebar.slider("Noise Level", 0.0, 0.5, 0.1, 0.01)
19
+ perc_train = st.sidebar.slider("Train/Test Split %", 10, 90, 50)
20
 
21
+ st.sidebar.header("2. Network Settings")
22
+ layers = st.sidebar.text_input("Neural Network Layers (e.g., 4,2)", "4,2")
23
+ activation = st.sidebar.selectbox("Activation Function", ["tanh", "relu", "sigmoid"])
24
+ learning_rate = st.sidebar.slider("Learning Rate", 0.001, 0.1, 0.03)
25
+ epochs = st.sidebar.slider("Epochs", 10, 300, 100)
26
+ batch_size = st.sidebar.slider("Batch Size", 1, 100, 10)
 
 
 
27
 
28
  # Generate dataset
29
+ if dataset == "circle":
30
+ X, y = make_circles(n_samples=500, noise=noise, factor=0.5, random_state=0)
31
+ elif dataset == "moons":
32
+ X, y = make_moons(n_samples=500, noise=noise, random_state=0)
33
+ else:
34
+ X, y = make_classification(n_samples=500, n_features=2, n_redundant=0, n_clusters_per_class=1,
35
+ n_informative=2, n_classes=2, class_sep=1.0, flip_y=noise, random_state=0)
36
+
37
  X = StandardScaler().fit_transform(X)
38
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=(100 - perc_train)/100, random_state=42)
39
 
40
  # Build model
41
  model = Sequential()
42
  layer_sizes = [int(n.strip()) for n in layers.split(",") if n.strip().isdigit()]
43
+ model.add(Dense(layer_sizes[0], input_dim=2, activation=activation))
 
 
 
44
  for size in layer_sizes[1:]:
45
  model.add(Dense(size, activation=activation))
46
+ model.add(Dense(1, activation="sigmoid"))
47
+ model.compile(optimizer=Adam(learning_rate=learning_rate), loss="binary_crossentropy", metrics=["accuracy"])
48
 
 
 
 
 
 
 
 
49
  with st.spinner("Training model..."):
50
+ history = model.fit(X_train, y_train, validation_data=(X_test, y_test),
51
+ epochs=epochs, batch_size=batch_size, verbose=0)
52
+
53
+ train_acc = model.evaluate(X_train, y_train, verbose=0)[1]
54
+ test_acc = model.evaluate(X_test, y_test, verbose=0)[1]
55
+ st.success(f"Train Accuracy: {train_acc:.3f} | Test Accuracy: {test_acc:.3f}")
56
 
57
+ # Accuracy plot
58
  fig, ax = plt.subplots()
59
+ ax.plot(history.history["accuracy"], label="Train")
60
+ ax.plot(history.history["val_accuracy"], label="Test")
61
+ ax.set_title("Accuracy")
62
  ax.set_xlabel("Epoch")
63
  ax.set_ylabel("Accuracy")
64
  ax.legend()
65
  st.pyplot(fig)
66
 
67
+ # Decision boundary
68
+ def plot_boundary(X, y, model, ax):
69
+ h = 0.02
70
+ x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
71
+ y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
72
+ xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
73
+ np.arange(y_min, y_max, h))
74
+ grid = np.c_[xx.ravel(), yy.ravel()]
75
+ preds = model.predict(grid)
76
+ preds = preds.reshape(xx.shape)
77
+ ax.contourf(xx, yy, preds, cmap=plt.cm.RdBu, alpha=0.6)
78
+ ax.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.RdBu, edgecolors='k')
79
+
80
+ fig2, ax2 = plt.subplots()
81
+ plot_boundary(X_test, y_test, model, ax2)
82
+ ax2.set_title("Decision Boundary")
83
+ st.pyplot(fig2)