DasariHarshitha commited on
Commit
386ef7e
·
verified ·
1 Parent(s): 2d39e40

Update pages/Tensorflow.py

Browse files
Files changed (1) hide show
  1. pages/Tensorflow.py +194 -96
pages/Tensorflow.py CHANGED
@@ -1,96 +1,194 @@
1
- import streamlit as st
2
- import tensorflow as tf
3
- from tensorflow.keras.layers import Input, Dense
4
- from tensorflow.keras.models import Sequential
5
- import pandas as pd
6
- import matplotlib.pyplot as plt
7
- import seaborn as sns
8
- from sklearn.datasets import make_moons, make_circles, make_blobs, make_classification
9
- from sklearn.model_selection import train_test_split
10
- from sklearn.preprocessing import StandardScaler
11
- from mlxtend.plotting import plot_decision_regions
12
- import numpy as np
13
-
14
- st.title("Tensorflow Playground")
15
-
16
- data_sets = {
17
- "make_classification": make_classification,
18
- "make_moons": make_moons,
19
- "make_circles": make_circles,
20
- "make_blobs": make_blobs
21
- }
22
-
23
- learning_rate = st.sidebar.slider('Learning Rate', min_value=0.0001, max_value=0.1, value=0.001, step=0.0001, format="%.4f")
24
- noise = st.sidebar.slider('Noise Level', min_value=0.0, max_value=1.0, value=0.1, step=0.01, format="%.2f")
25
- epochs = st.sidebar.slider("Epochs", 1, 100, 10)
26
- num_hidden_layers = st.sidebar.slider('Number of Hidden Layers', min_value=1, max_value=10, value=2, step=1)
27
- neurons_per_layer = st.sidebar.slider("Neurons per Layer", 1, 512, 32)
28
- activation_function = st.sidebar.radio("Select the activation function", ["relu", "sigmoid", "tanh"])
29
- batch_size = st.sidebar.slider('Batch Size', min_value=8, max_value=512, value=32, step=8)
30
- test_size = st.sidebar.slider('test_size:', min_value=0.1, max_value=0.9, value=0.3, step=0.05)
31
-
32
- data_choice = st.sidebar.radio("Select the dataset", list(data_sets.keys()))
33
-
34
- if data_choice == "make_classification":
35
- X, y = make_classification(n_samples=2000, n_features=2, n_redundant=0, n_clusters_per_class=1, random_state=27)
36
- elif data_choice == "make_blobs":
37
- X, y = make_blobs(n_samples=2000, n_features=2, random_state=27)
38
- else:
39
- X, y = data_sets[data_choice](n_samples=2000, noise=noise, random_state=27)
40
-
41
- if st.button("Start"):
42
- st.subheader("📍 Input Data")
43
- fig, ax = plt.subplots(figsize=(8, 6))
44
- sns.scatterplot(x=X[:, 0], y=X[:, 1], hue=y, palette='Set2', ax=ax)
45
- st.pyplot(fig)
46
-
47
- if st.button("Train Model"):
48
- model = Sequential()
49
- model.add(Input(shape=(2,)))
50
- for i in range(num_hidden_layers):
51
- model.add(Dense(units=neurons_per_layer, activation=activation_function))
52
- model.add(Dense(units=1, activation="sigmoid"))
53
-
54
- optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate)
55
- model.compile(optimizer=optimizer, loss="binary_crossentropy", metrics=["accuracy"])
56
-
57
- X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=27)
58
- scaler = StandardScaler()
59
- X_train_scaled = scaler.fit_transform(X_train)
60
- X_test_scaled = scaler.transform(X_test)
61
-
62
- history = model.fit(X_train_scaled, y_train, epochs=epochs, batch_size=batch_size, validation_split=0.2, verbose=0)
63
-
64
- st.write(f"🧮 Final Training Loss: **{history.history['loss'][-1]:.4f}**")
65
- st.write(f"✅ Final Validation Loss: **{history.history['val_loss'][-1]:.4f}**")
66
-
67
- col1, col2 = st.columns(2)
68
-
69
- with col1:
70
- st.markdown("#### Training vs Validation Loss Plot")
71
- fig1, ax1 = plt.subplots(figsize=(8, 6))
72
- ax1.plot(history.history["loss"], label="Training Loss", color="green")
73
- ax1.plot(history.history["val_loss"], label="Validation Loss", color="red")
74
- ax1.set_xlabel("Epoch", fontsize=14, fontweight='bold')
75
- ax1.set_ylabel("Loss", fontsize=14, fontweight='bold')
76
- ax1.legend()
77
- st.pyplot(fig1)
78
-
79
- with col2:
80
- st.markdown("#### Decision Boundary Plot")
81
-
82
- class KerasClassifierWrapper:
83
- def __init__(self, model, scaler):
84
- self.model = model
85
- self.scaler = scaler
86
-
87
- def predict(self, X):
88
- X_scaled = self.scaler.transform(X)
89
- preds = self.model.predict(X_scaled)
90
- return np.where(preds > 0.5, 1, 0).flatten()
91
-
92
- keras_clf = KerasClassifierWrapper(model, scaler)
93
-
94
- fig2, ax2 = plt.subplots(figsize=(8, 6))
95
- plot_decision_regions(X=X_train, y=y_train, clf=keras_clf, ax=ax2)
96
- st.pyplot(fig2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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("bg.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
69
+ import seaborn as sns
70
+ from sklearn.datasets import make_circles, make_moons, make_classification
71
+ from sklearn.model_selection import train_test_split
72
+ from sklearn.preprocessing import StandardScaler
73
+ from keras.models import Sequential
74
+ from keras.layers import Dense
75
+ 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("bg.jpeg")
94
+
95
+ # Inject CSS with base64 background
96
+ st.markdown(
97
+ f"""
98
+ <style>
99
+ .stApp {{
100
+ background-image: url("data:image/jpg;base64,{img_base64}");
101
+ background-size: cover;
102
+ background-position: center;
103
+ background-repeat: no-repeat;
104
+ background-attachment: fixed;
105
+ }}
106
+ </style>
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)
117
+ epochs = st.sidebar.slider("Epochs", 1, 100, 10)
118
+ learning_rate = st.sidebar.slider("Learning Rate", 0.0001, 1.0, 0.01, step=0.0001, format="%.4f")
119
+ 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":
131
+ x, y = make_moons(n_samples=num_points, noise=noise, random_state=42)
132
+ 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')
170
+ ax.plot(history.history['val_loss'], label='Validation Loss')
171
+ ax.set_title("Training vs Validation Loss")
172
+ ax.set_xlabel("Epoch")
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
186
+
187
+ def predict(self, X):
188
+ return (self.model.predict(X) > 0.5).astype("int32")
189
+
190
+ with st.spinner("🔮 Generating decision boundary..."):
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)