File size: 6,862 Bytes
c0280fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
import streamlit as st
import base64

# Set page config
st.set_page_config(page_title="Neural Network Playground", layout="centered")

# Load and encode background image
def get_base64(file_path):
    with open(file_path, "rb") as f:
        data = f.read()
    return base64.b64encode(data).decode()

img_base64 = get_base64("tf1.jpg")  

# Inject CSS with base64 background
st.markdown(
    f"""

    <style>

    .stApp {{

        background-image: url("data:image/jpg;base64,{img_base64}");

        background-size: cover;

        background-position: center;

        background-repeat: no-repeat;

        background-attachment: fixed;

    }}

    </style>

    """,
    unsafe_allow_html=True
)

# Title
st.markdown(
    """

    <h1 style='text-align: center; color: #FF6336; font-weight: bold;'>

        Neural Network Playground

    </h1>

    """,
    unsafe_allow_html=True
)

# Subtitle
st.markdown(
    """

    <h3 style='text-align: center; color: #2E8B57; font-weight: normal;'>

        Dive into the world of neural networks—explore and train with ease!

    </h3>

    """,
    unsafe_allow_html=True
)

# About section
st.subheader("🔎 :blue[About the App:]")

st.markdown("""

Neural Network Playground is an interactive tool designed for hands-on exploration of machine learning models.

Whether you're just starting or already exploring advanced concepts, this platform lets you:

- 🧑‍💻 Build and visualize neural networks with ease and fun.

- 🔬 Train models on interactive datasets with real-time updates.

- 🛠️ Experiment with various architectures and see instant results.

- 🧠 Adjust hyperparameters and observe their effects on model learning—live!

No coding required. Just pure, interactive learning.

""")



import streamlit as st
import base64
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.datasets import make_circles, make_moons, make_classification
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import SGD
from mlxtend.plotting import plot_decision_regions
import numpy as np
import tensorflow as tf
from tensorflow import keras


# Page title with new theme
st.markdown(
    "<h1 style='text-align: center; color: #FF6347;'>🤖 Neural Network Playground</h1>",
    unsafe_allow_html=True
)
# Load and encode background image
def get_base64(file_path):
    with open(file_path, "rb") as f:
        data = f.read()
    return base64.b64encode(data).decode()

img_base64 = get_base64("tf1.jpg")  

# Inject CSS with base64 background
st.markdown(
    f"""

    <style>

    .stApp {{

        background-image: url("data:image/jpg;base64,{img_base64}");

        background-size: cover;

        background-position: center;

        background-repeat: no-repeat;

        background-attachment: fixed;

    }}

    </style>

    """,
    unsafe_allow_html=True
)
# Sidebar configuration with new theme
st.sidebar.title("⚙️ Model Configuration")

# User input options in sidebar with theme
num_points = st.sidebar.slider("Number of Data Points", 100, 10000, 1000, step=100)
noise = st.sidebar.slider("Noise", 0.01, 0.9, 0.1)
batch_size = st.sidebar.slider("Batch Size", 1, 512, 32)
epochs = st.sidebar.slider("Epochs", 1, 100, 10)
learning_rate = st.sidebar.slider("Learning Rate", 0.0001, 1.0, 0.01, step=0.0001, format="%.4f")
hidden_layers = st.sidebar.slider("Hidden Layers", 1, 5, 2)
neurons_per_layer = st.sidebar.slider("Neurons per Layer", 1, 512, 32)
activation_name = st.sidebar.selectbox("Activation Function", ["relu", "tanh", "sigmoid", "linear"])

# Dataset selection with new theme
st.subheader("📊 Dataset Selection")
dataset_option = st.selectbox("Choose the dataset", ("circle", "moons", "classification"))

# Dataset generation based on user selection
if dataset_option == "circle":
    x, y = make_circles(n_samples=num_points, noise=noise, factor=0.5, random_state=42)
elif dataset_option == "moons":
    x, y = make_moons(n_samples=num_points, noise=noise, random_state=42)
else:
    x, y = make_classification(n_samples=num_points, n_features=2, n_informative=2,
                                n_redundant=0, n_clusters_per_class=1, random_state=42)

# Submit button
if st.button("🚀 Submit"):
    st.subheader("📍 Input Data")
    fig, ax = plt.subplots()
    sns.scatterplot(x=x[:, 0], y=x[:, 1], hue=y, palette='Set2', ax=ax)
    st.pyplot(fig)

# Train button with a fresh theme for model training
if st.button("🧠 Train the model"):
    with st.spinner("⏳ Training the model..."):
        # Data split and scale
        x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=1, stratify=y)
        scaler = StandardScaler()
        x_train = scaler.fit_transform(x_train)
        x_test = scaler.transform(x_test)

        # Model architecture
        model = Sequential()
        model.add(Dense(neurons_per_layer, input_shape=(2,), activation=activation_name))
        for _ in range(hidden_layers - 1):
            model.add(Dense(neurons_per_layer, activation=activation_name))
        model.add(Dense(1, activation='sigmoid'))

        # Compile and train
        sgd = SGD(learning_rate=learning_rate)
        model.compile(optimizer=sgd, loss='binary_crossentropy', metrics=['accuracy'])
        history = model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_split=0.2, verbose=0)

    st.success("✅ Training Complete!")

    # Show training plots with a fresh look
    st.subheader("📈 Training Progress")
    fig, ax = plt.subplots()
    ax.plot(history.history['loss'], label='Training Loss')
    ax.plot(history.history['val_loss'], label='Validation Loss')
    ax.set_title("Training vs Validation Loss")
    ax.set_xlabel("Epoch")
    ax.legend()
    st.pyplot(fig)

    # Display final loss metrics
    final_loss = history.history['loss'][-1]
    final_val_loss = history.history['val_loss'][-1]
    st.write(f"🧮 Final Training Loss: **{final_loss:.4f}**")
    st.write(f"✅ Final Validation Loss: **{final_val_loss:.4f}**")

    # Decision boundary visualization with a fresh UI
    class KerasClassifierWrapper:
        def __init__(self, model):
            self.model = model

        def predict(self, X):
            return (self.model.predict(X) > 0.5).astype("int32")

    with st.spinner("🔮 Generating decision boundary..."):
        st.subheader("📌 Decision Boundary (Training Data)")
        fig, ax = plt.subplots()
        plot_decision_regions(X=x_train, y=y_train, clf=KerasClassifierWrapper(model), ax=ax)
        st.pyplot(fig)