DasariHarshitha commited on
Commit
cd150f3
·
verified ·
1 Parent(s): a302172

Update pages/Tensorflow.py

Browse files
Files changed (1) hide show
  1. pages/Tensorflow.py +17 -86
pages/Tensorflow.py CHANGED
@@ -1,68 +1,3 @@
1
- import streamlit as st
2
- import base64
3
-
4
- # Set page config
5
- st.set_page_config(page_title="Neural Network Playground", layout="centered")
6
-
7
- # Load and encode background image
8
- def get_base64(file_path):
9
- with open(file_path, "rb") as f:
10
- data = f.read()
11
- return base64.b64encode(data).decode()
12
-
13
- img_base64 = get_base64("ann.jpeg")
14
-
15
- # Inject CSS with base64 background
16
- st.markdown(
17
- f"""
18
- <style>
19
- .stApp {{
20
- background-image: url("data:image/jpg;base64,{img_base64}");
21
- background-size: cover;
22
- background-position: center;
23
- background-repeat: no-repeat;
24
- background-attachment: fixed;
25
- }}
26
- </style>
27
- """,
28
- unsafe_allow_html=True
29
- )
30
-
31
- # Title
32
- st.markdown(
33
- """
34
- <h1 style='text-align: center; color: #FF6347; font-weight: bold;'>
35
- Neural Network Playground
36
- </h1>
37
- """,
38
- unsafe_allow_html=True
39
- )
40
-
41
- # Subtitle
42
- st.markdown(
43
- """
44
- <h3 style='text-align: center; color: #2E8B57; font-weight: normal;'>
45
- Dive into the world of neural networks—explore and train with ease!
46
- </h3>
47
- """,
48
- unsafe_allow_html=True
49
- )
50
-
51
- # About section
52
- st.subheader("🔎 :blue[About the App:]")
53
-
54
- st.markdown("""
55
- Neural Network Playground is an interactive tool designed for hands-on exploration of machine learning models.
56
- Whether you're just starting or already exploring advanced concepts, this platform lets you:
57
- - 🧑‍💻 Build and visualize neural networks with ease and fun.
58
- - 🔬 Train models on interactive datasets with real-time updates.
59
- - 🛠️ Experiment with various architectures and see instant results.
60
- - 🧠 Adjust hyperparameters and observe their effects on model learning—live!
61
- No coding required. Just pure, interactive learning.
62
- """)
63
-
64
-
65
-
66
  import streamlit as st
67
  import base64
68
  import matplotlib.pyplot as plt
@@ -76,21 +11,14 @@ from keras.optimizers import SGD
76
  from mlxtend.plotting import plot_decision_regions
77
  import numpy as np
78
  import tensorflow as tf
79
- from tensorflow import keras
80
 
81
-
82
- # Page title with new theme
83
- st.markdown(
84
- "<h1 style='text-align: center; color: #FF6347;'>🤖 Neural Network Playground</h1>",
85
- unsafe_allow_html=True
86
- )
87
  # Load and encode background image
88
  def get_base64(file_path):
89
  with open(file_path, "rb") as f:
90
  data = f.read()
91
  return base64.b64encode(data).decode()
92
 
93
- img_base64 = get_base64("ann.jpeg")
94
 
95
  # Inject CSS with base64 background
96
  st.markdown(
@@ -107,10 +35,16 @@ st.markdown(
107
  """,
108
  unsafe_allow_html=True
109
  )
110
- # Sidebar configuration with new theme
 
 
 
 
 
 
 
111
  st.sidebar.title("⚙️ Model Configuration")
112
 
113
- # User input options in sidebar with theme
114
  num_points = st.sidebar.slider("Number of Data Points", 100, 10000, 1000, step=100)
115
  noise = st.sidebar.slider("Noise", 0.01, 0.9, 0.1)
116
  batch_size = st.sidebar.slider("Batch Size", 1, 512, 32)
@@ -120,11 +54,11 @@ hidden_layers = st.sidebar.slider("Hidden Layers", 1, 5, 2)
120
  neurons_per_layer = st.sidebar.slider("Neurons per Layer", 1, 512, 32)
121
  activation_name = st.sidebar.selectbox("Activation Function", ["relu", "tanh", "sigmoid", "linear"])
122
 
123
- # Dataset selection with new theme
124
  st.subheader("📊 Dataset Selection")
125
  dataset_option = st.selectbox("Choose the dataset", ("circle", "moons", "classification"))
126
 
127
- # Dataset generation based on user selection
128
  if dataset_option == "circle":
129
  x, y = make_circles(n_samples=num_points, noise=noise, factor=0.5, random_state=42)
130
  elif dataset_option == "moons":
@@ -133,37 +67,34 @@ else:
133
  x, y = make_classification(n_samples=num_points, n_features=2, n_informative=2,
134
  n_redundant=0, n_clusters_per_class=1, random_state=42)
135
 
136
- # Submit button
137
  if st.button("🚀 Submit"):
138
  st.subheader("📍 Input Data")
139
  fig, ax = plt.subplots()
140
  sns.scatterplot(x=x[:, 0], y=x[:, 1], hue=y, palette='Set2', ax=ax)
141
  st.pyplot(fig)
142
 
143
- # Train button with a fresh theme for model training
144
  if st.button("🧠 Train the model"):
145
  with st.spinner("⏳ Training the model..."):
146
- # Data split and scale
147
  x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=1, stratify=y)
148
  scaler = StandardScaler()
149
  x_train = scaler.fit_transform(x_train)
150
  x_test = scaler.transform(x_test)
151
 
152
- # Model architecture
153
  model = Sequential()
154
  model.add(Dense(neurons_per_layer, input_shape=(2,), activation=activation_name))
155
  for _ in range(hidden_layers - 1):
156
  model.add(Dense(neurons_per_layer, activation=activation_name))
157
  model.add(Dense(1, activation='sigmoid'))
158
 
159
- # Compile and train
160
  sgd = SGD(learning_rate=learning_rate)
161
  model.compile(optimizer=sgd, loss='binary_crossentropy', metrics=['accuracy'])
162
  history = model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_split=0.2, verbose=0)
163
 
164
  st.success("✅ Training Complete!")
165
 
166
- # Show training plots with a fresh look
167
  st.subheader("📈 Training Progress")
168
  fig, ax = plt.subplots()
169
  ax.plot(history.history['loss'], label='Training Loss')
@@ -173,13 +104,13 @@ if st.button("🧠 Train the model"):
173
  ax.legend()
174
  st.pyplot(fig)
175
 
176
- # Display final loss metrics
177
  final_loss = history.history['loss'][-1]
178
  final_val_loss = history.history['val_loss'][-1]
179
  st.write(f"🧮 Final Training Loss: **{final_loss:.4f}**")
180
  st.write(f"✅ Final Validation Loss: **{final_val_loss:.4f}**")
181
 
182
- # Decision boundary visualization with a fresh UI
183
  class KerasClassifierWrapper:
184
  def __init__(self, model):
185
  self.model = model
@@ -191,4 +122,4 @@ if st.button("🧠 Train the model"):
191
  st.subheader("📌 Decision Boundary (Training Data)")
192
  fig, ax = plt.subplots()
193
  plot_decision_regions(X=x_train, y=y_train, clf=KerasClassifierWrapper(model), ax=ax)
194
- st.pyplot(fig)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  import base64
3
  import matplotlib.pyplot as plt
 
11
  from mlxtend.plotting import plot_decision_regions
12
  import numpy as np
13
  import tensorflow as tf
 
14
 
 
 
 
 
 
 
15
  # Load and encode background image
16
  def get_base64(file_path):
17
  with open(file_path, "rb") as f:
18
  data = f.read()
19
  return base64.b64encode(data).decode()
20
 
21
+ #img_base64 = get_base64("ann.jpeg")
22
 
23
  # Inject CSS with base64 background
24
  st.markdown(
 
35
  """,
36
  unsafe_allow_html=True
37
  )
38
+
39
+ # Page title
40
+ st.markdown(
41
+ "<h1 style='text-align: center; color: #FF6347;'>🤖 Neural Network Playground</h1>",
42
+ unsafe_allow_html=True
43
+ )
44
+
45
+ # Sidebar configuration
46
  st.sidebar.title("⚙️ Model Configuration")
47
 
 
48
  num_points = st.sidebar.slider("Number of Data Points", 100, 10000, 1000, step=100)
49
  noise = st.sidebar.slider("Noise", 0.01, 0.9, 0.1)
50
  batch_size = st.sidebar.slider("Batch Size", 1, 512, 32)
 
54
  neurons_per_layer = st.sidebar.slider("Neurons per Layer", 1, 512, 32)
55
  activation_name = st.sidebar.selectbox("Activation Function", ["relu", "tanh", "sigmoid", "linear"])
56
 
57
+ # Dataset selection
58
  st.subheader("📊 Dataset Selection")
59
  dataset_option = st.selectbox("Choose the dataset", ("circle", "moons", "classification"))
60
 
61
+ # Dataset generation
62
  if dataset_option == "circle":
63
  x, y = make_circles(n_samples=num_points, noise=noise, factor=0.5, random_state=42)
64
  elif dataset_option == "moons":
 
67
  x, y = make_classification(n_samples=num_points, n_features=2, n_informative=2,
68
  n_redundant=0, n_clusters_per_class=1, random_state=42)
69
 
70
+ # Display data
71
  if st.button("🚀 Submit"):
72
  st.subheader("📍 Input Data")
73
  fig, ax = plt.subplots()
74
  sns.scatterplot(x=x[:, 0], y=x[:, 1], hue=y, palette='Set2', ax=ax)
75
  st.pyplot(fig)
76
 
77
+ # Train the model
78
  if st.button("🧠 Train the model"):
79
  with st.spinner("⏳ Training the model..."):
 
80
  x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=1, stratify=y)
81
  scaler = StandardScaler()
82
  x_train = scaler.fit_transform(x_train)
83
  x_test = scaler.transform(x_test)
84
 
 
85
  model = Sequential()
86
  model.add(Dense(neurons_per_layer, input_shape=(2,), activation=activation_name))
87
  for _ in range(hidden_layers - 1):
88
  model.add(Dense(neurons_per_layer, activation=activation_name))
89
  model.add(Dense(1, activation='sigmoid'))
90
 
 
91
  sgd = SGD(learning_rate=learning_rate)
92
  model.compile(optimizer=sgd, loss='binary_crossentropy', metrics=['accuracy'])
93
  history = model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_split=0.2, verbose=0)
94
 
95
  st.success("✅ Training Complete!")
96
 
97
+ # Training plot
98
  st.subheader("📈 Training Progress")
99
  fig, ax = plt.subplots()
100
  ax.plot(history.history['loss'], label='Training Loss')
 
104
  ax.legend()
105
  st.pyplot(fig)
106
 
107
+ # Final metrics
108
  final_loss = history.history['loss'][-1]
109
  final_val_loss = history.history['val_loss'][-1]
110
  st.write(f"🧮 Final Training Loss: **{final_loss:.4f}**")
111
  st.write(f"✅ Final Validation Loss: **{final_val_loss:.4f}**")
112
 
113
+ # Decision boundary
114
  class KerasClassifierWrapper:
115
  def __init__(self, model):
116
  self.model = model
 
122
  st.subheader("📌 Decision Boundary (Training Data)")
123
  fig, ax = plt.subplots()
124
  plot_decision_regions(X=x_train, y=y_train, clf=KerasClassifierWrapper(model), ax=ax)
125
+ st.pyplot(fig)