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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
|
| 11 |
-
forums](https://discuss.streamlit.io).
|
| 12 |
-
|
| 13 |
-
In the meantime, below is an example of what you can do with just a few lines of code:
|
| 14 |
-
"""
|
| 15 |
-
|
| 16 |
-
num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
|
| 17 |
-
num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
|
| 18 |
-
|
| 19 |
-
indices = np.linspace(0, 1, num_points)
|
| 20 |
-
theta = 2 * np.pi * num_turns * indices
|
| 21 |
-
radius = indices
|
| 22 |
-
|
| 23 |
-
x = radius * np.cos(theta)
|
| 24 |
-
y = radius * np.sin(theta)
|
| 25 |
-
|
| 26 |
-
df = pd.DataFrame({
|
| 27 |
-
"x": x,
|
| 28 |
-
"y": y,
|
| 29 |
-
"idx": indices,
|
| 30 |
-
"rand": np.random.randn(num_points),
|
| 31 |
-
})
|
| 32 |
-
|
| 33 |
-
st.altair_chart(alt.Chart(df, height=700, width=700)
|
| 34 |
-
.mark_point(filled=True)
|
| 35 |
-
.encode(
|
| 36 |
-
x=alt.X("x", axis=None),
|
| 37 |
-
y=alt.Y("y", axis=None),
|
| 38 |
-
color=alt.Color("idx", legend=None, scale=alt.Scale()),
|
| 39 |
-
size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
|
| 40 |
-
))
|
|
|
|
| 1 |
+
# Import packages
|
|
|
|
|
|
|
| 2 |
import streamlit as st
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import torch.optim as optim
|
| 6 |
+
from sklearn.datasets import make_moons, make_circles, make_classification
|
| 7 |
+
from sklearn.model_selection import train_test_split
|
| 8 |
+
from sklearn.preprocessing import StandardScaler
|
| 9 |
+
from sklearn.metrics import accuracy_score
|
| 10 |
+
import numpy as np
|
| 11 |
+
import matplotlib.pyplot as plt
|
| 12 |
+
import io
|
| 13 |
+
import time
|
| 14 |
+
|
| 15 |
+
# Streamlit config
|
| 16 |
+
st.set_page_config(page_title="ANN Visualizer", layout="wide")
|
| 17 |
+
|
| 18 |
+
# ---------- UI Components ----------
|
| 19 |
+
st.title("🧠 Interactive ANN Visualizer")
|
| 20 |
+
|
| 21 |
+
with st.sidebar:
|
| 22 |
+
st.header("⚙️ Model Configuration")
|
| 23 |
+
|
| 24 |
+
dataset_type = st.selectbox("Dataset", ["moons", "circles", "classification"])
|
| 25 |
+
n_samples = st.slider("Samples", 100, 5000, 500, 100)
|
| 26 |
+
noise = st.slider("Noise", 0.0, 1.0, 0.2, 0.05)
|
| 27 |
+
epochs = st.slider("Epochs", 100, 5000, 500, 100)
|
| 28 |
+
lr = st.number_input("Learning Rate", 0.0001, 1.0, 0.01, format="%f")
|
| 29 |
+
|
| 30 |
+
early_stop = st.checkbox("Early Stopping", value=True)
|
| 31 |
+
patience = st.slider("Patience", 1, 20, 5) if early_stop else None
|
| 32 |
+
min_delta = st.number_input("Min Delta", 0.0001, 0.1, 0.001, format="%f") if early_stop else None
|
| 33 |
+
|
| 34 |
+
st.subheader("🧱 Hidden Layers")
|
| 35 |
+
num_hidden = st.number_input("Number of Layers", 1, 10, 2)
|
| 36 |
+
layer_configs = []
|
| 37 |
+
|
| 38 |
+
activation_map = {"ReLU": nn.ReLU, "Tanh": nn.Tanh, "Sigmoid": nn.Sigmoid}
|
| 39 |
+
for i in range(num_hidden):
|
| 40 |
+
st.markdown(f"**Layer {i + 1}**")
|
| 41 |
+
units = st.number_input(f"Units", 1, 512, 8, key=f"units_{i}")
|
| 42 |
+
act = st.selectbox("Activation", list(activation_map.keys()), key=f"act_{i}")
|
| 43 |
+
dropout = st.slider("Dropout", 0.0, 0.9, 0.0, 0.05, key=f"drop_{i}")
|
| 44 |
+
reg_type = st.selectbox("Regularization", ["None", "L1", "L2", "L1_L2"], key=f"reg_{i}")
|
| 45 |
+
reg_strength = st.number_input("Reg Strength", 0.0, 1.0, 0.001, format="%f", key=f"reg_strength_{i}") if reg_type != "None" else 0.0
|
| 46 |
+
layer_configs.append((units, act, dropout, reg_type, reg_strength))
|
| 47 |
+
|
| 48 |
+
start_training = st.button("🚀 Train Model")
|
| 49 |
+
|
| 50 |
+
# ---------- Data Generation ----------
|
| 51 |
+
def generate_data():
|
| 52 |
+
if dataset_type == "moons":
|
| 53 |
+
return make_moons(n_samples=n_samples, noise=noise, random_state=42)
|
| 54 |
+
elif dataset_type == "circles":
|
| 55 |
+
return make_circles(n_samples=n_samples, noise=noise, factor=0.5, random_state=42)
|
| 56 |
+
return make_classification(n_samples=n_samples, n_features=2, n_informative=2, n_redundant=0, n_clusters_per_class=1)
|
| 57 |
+
|
| 58 |
+
# ---------- Model ----------
|
| 59 |
+
class CustomLayer(nn.Module):
|
| 60 |
+
def __init__(self, in_f, out_f, activation, dropout, reg_type, reg_strength):
|
| 61 |
+
super().__init__()
|
| 62 |
+
self.linear = nn.Linear(in_f, out_f)
|
| 63 |
+
self.activation = activation_map[activation]()
|
| 64 |
+
self.dropout = nn.Dropout(dropout)
|
| 65 |
+
self.reg_type = reg_type
|
| 66 |
+
self.reg_strength = reg_strength
|
| 67 |
+
|
| 68 |
+
def forward(self, x):
|
| 69 |
+
return self.dropout(self.activation(self.linear(x)))
|
| 70 |
+
|
| 71 |
+
def reg_loss(self):
|
| 72 |
+
if self.reg_type == "L1":
|
| 73 |
+
return self.reg_strength * torch.sum(torch.abs(self.linear.weight))
|
| 74 |
+
elif self.reg_type == "L2":
|
| 75 |
+
return self.reg_strength * torch.sum(self.linear.weight ** 2)
|
| 76 |
+
elif self.reg_type == "L1_L2":
|
| 77 |
+
return self.reg_strength * (torch.sum(torch.abs(self.linear.weight)) + torch.sum(self.linear.weight ** 2))
|
| 78 |
+
return 0.0
|
| 79 |
+
|
| 80 |
+
class ANN(nn.Module):
|
| 81 |
+
def __init__(self, input_dim, output_dim, configs):
|
| 82 |
+
super().__init__()
|
| 83 |
+
self.layers = nn.ModuleList()
|
| 84 |
+
prev = input_dim
|
| 85 |
+
self.reg_layers = []
|
| 86 |
+
for units, act, drop, reg, reg_strength in configs:
|
| 87 |
+
layer = CustomLayer(prev, units, act, drop, reg, reg_strength)
|
| 88 |
+
self.layers.append(layer)
|
| 89 |
+
self.reg_layers.append(layer)
|
| 90 |
+
prev = units
|
| 91 |
+
self.output = nn.Linear(prev, output_dim)
|
| 92 |
+
|
| 93 |
+
def forward(self, x):
|
| 94 |
+
for l in self.layers:
|
| 95 |
+
x = l(x)
|
| 96 |
+
return self.output(x)
|
| 97 |
+
|
| 98 |
+
def regularization_loss(self):
|
| 99 |
+
return sum(l.reg_loss() for l in self.reg_layers)
|
| 100 |
+
|
| 101 |
+
# ---------- Training Logic ----------
|
| 102 |
+
if start_training:
|
| 103 |
+
X, y = generate_data()
|
| 104 |
+
X = StandardScaler().fit_transform(X)
|
| 105 |
+
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
|
| 106 |
+
|
| 107 |
+
X_train_tensor = torch.tensor(X_train, dtype=torch.float32)
|
| 108 |
+
y_train_tensor = torch.tensor(y_train, dtype=torch.long)
|
| 109 |
+
X_test_tensor = torch.tensor(X_test, dtype=torch.float32)
|
| 110 |
+
y_test_tensor = torch.tensor(y_test, dtype=torch.long)
|
| 111 |
+
|
| 112 |
+
model = ANN(2, 2, layer_configs)
|
| 113 |
+
criterion = nn.CrossEntropyLoss()
|
| 114 |
+
optimizer = optim.Adam(model.parameters(), lr=lr)
|
| 115 |
+
|
| 116 |
+
best_loss = float("inf")
|
| 117 |
+
best_weights = None
|
| 118 |
+
patience_counter = 0
|
| 119 |
+
train_losses, test_losses = [], []
|
| 120 |
+
|
| 121 |
+
grid_x, grid_y = np.meshgrid(np.linspace(X[:, 0].min() - 0.5, X[:, 0].max() + 0.5, 400),
|
| 122 |
+
np.linspace(X[:, 1].min() - 0.5, X[:, 1].max() + 0.5, 400))
|
| 123 |
+
grid_tensor = torch.tensor(np.c_[grid_x.ravel(), grid_y.ravel()], dtype=torch.float32)
|
| 124 |
+
|
| 125 |
+
progress = st.progress(0)
|
| 126 |
+
for epoch in range(1, epochs + 1):
|
| 127 |
+
model.train()
|
| 128 |
+
optimizer.zero_grad()
|
| 129 |
+
out = model(X_train_tensor)
|
| 130 |
+
loss = criterion(out, y_train_tensor) + model.regularization_loss()
|
| 131 |
+
loss.backward()
|
| 132 |
+
optimizer.step()
|
| 133 |
+
|
| 134 |
+
model.eval()
|
| 135 |
+
with torch.no_grad():
|
| 136 |
+
val_out = model(X_test_tensor)
|
| 137 |
+
val_loss = criterion(val_out, y_test_tensor) + model.regularization_loss()
|
| 138 |
+
|
| 139 |
+
train_losses.append(loss.item())
|
| 140 |
+
test_losses.append(val_loss.item())
|
| 141 |
+
|
| 142 |
+
if early_stop:
|
| 143 |
+
if val_loss.item() < best_loss - min_delta:
|
| 144 |
+
best_loss = val_loss.item()
|
| 145 |
+
best_weights = model.state_dict()
|
| 146 |
+
patience_counter = 0
|
| 147 |
+
else:
|
| 148 |
+
patience_counter += 1
|
| 149 |
+
if patience_counter >= patience:
|
| 150 |
+
st.warning(f"Stopped early at epoch {epoch}")
|
| 151 |
+
break
|
| 152 |
+
|
| 153 |
+
if epoch % (epochs // 10) == 0 or epoch == epochs:
|
| 154 |
+
with torch.no_grad():
|
| 155 |
+
preds = model(grid_tensor).argmax(dim=1).numpy().reshape(grid_x.shape)
|
| 156 |
+
fig, ax = plt.subplots(figsize=(5, 5))
|
| 157 |
+
ax.contourf(grid_x, grid_y, preds, cmap='Spectral', alpha=0.8)
|
| 158 |
+
ax.scatter(X[:, 0], X[:, 1], c=y, cmap='Spectral', edgecolor='k', s=15)
|
| 159 |
+
ax.set_title(f"Decision Boundary at Epoch {epoch}")
|
| 160 |
+
ax.axis("off")
|
| 161 |
+
st.pyplot(fig)
|
| 162 |
+
|
| 163 |
+
progress.progress(epoch / epochs)
|
| 164 |
+
|
| 165 |
+
if best_weights:
|
| 166 |
+
model.load_state_dict(best_weights)
|
| 167 |
+
|
| 168 |
+
# Final results
|
| 169 |
+
st.success("✅ Training complete!")
|
| 170 |
+
|
| 171 |
+
st.subheader("📈 Loss Curve")
|
| 172 |
+
fig1, ax1 = plt.subplots()
|
| 173 |
+
ax1.plot(train_losses, label="Train", color="navy")
|
| 174 |
+
ax1.plot(test_losses, label="Test", color="orange")
|
| 175 |
+
ax1.legend(); ax1.grid(True); st.pyplot(fig1)
|
| 176 |
+
|
| 177 |
+
buf1 = io.BytesIO(); fig1.savefig(buf1, format="png")
|
| 178 |
+
st.download_button("Download Loss Plot", buf1.getvalue(), "loss.png", "image/png")
|
| 179 |
+
|
| 180 |
+
st.subheader("🧭 Final Decision Boundary")
|
| 181 |
+
with torch.no_grad():
|
| 182 |
+
final_preds = model(grid_tensor).argmax(dim=1).numpy().reshape(grid_x.shape)
|
| 183 |
+
fig2, ax2 = plt.subplots(figsize=(5, 5))
|
| 184 |
+
ax2.contourf(grid_x, grid_y, final_preds, cmap='Spectral', alpha=0.8)
|
| 185 |
+
ax2.scatter(X[:, 0], X[:, 1], c=y, cmap='Spectral', edgecolor='k', s=15)
|
| 186 |
+
ax2.set_title("Final Decision Boundary"); ax2.axis("off")
|
| 187 |
+
st.pyplot(fig2)
|
| 188 |
+
|
| 189 |
+
buf2 = io.BytesIO(); fig2.savefig(buf2, format="png")
|
| 190 |
+
st.download_button("Download Decision Boundary", buf2.getvalue(), "boundary.png", "image/png")
|
| 191 |
|
| 192 |
+
y_train_pred = model(X_train_tensor).argmax(dim=1).numpy()
|
| 193 |
+
y_test_pred = model(X_test_tensor).argmax(dim=1).numpy()
|
| 194 |
+
st.metric("Train Accuracy", f"{accuracy_score(y_train, y_train_pred):.2%}")
|
| 195 |
+
st.metric("Test Accuracy", f"{accuracy_score(y_test, y_test_pred):.2%}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|