Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,86 +1,273 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
import numpy as np
|
| 3 |
-
|
|
|
|
| 4 |
from sklearn.preprocessing import StandardScaler
|
| 5 |
from sklearn.model_selection import train_test_split
|
| 6 |
-
from tensorflow import
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
from keras.
|
| 10 |
-
from keras.
|
| 11 |
-
from keras.losses import MeanAbsoluteError,MeanSquaredError
|
| 12 |
-
from keras.optimizers import SGD
|
| 13 |
-
from keras.regularizers import l1,l1,l1_l2
|
| 14 |
|
|
|
|
| 15 |
from mlxtend.plotting import plot_decision_regions
|
| 16 |
import graphviz
|
| 17 |
|
|
|
|
|
|
|
|
|
|
| 18 |
st.title("TensorFlow Playground")
|
| 19 |
|
| 20 |
with st.sidebar:
|
| 21 |
-
st.header("
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
st.header("Model Hyperparameters")
|
| 32 |
-
hl = st.number_input("Hidden Layers",1,10,step=1)
|
| 33 |
-
numbers = st.text_input("Neurons for each hidden layer"
|
| 34 |
input_func = lambda x: [int(i.strip()) for i in x.split(",") if i.strip() != ""]
|
| 35 |
nn = input_func(numbers)
|
| 36 |
-
|
| 37 |
-
|
| 38 |
|
| 39 |
-
|
| 40 |
col1, col2 = st.columns(2)
|
| 41 |
-
|
| 42 |
with col1:
|
| 43 |
-
af = st.selectbox("Activation Function",["sigmoid","tanh","relu"],index=2)
|
| 44 |
with col2:
|
| 45 |
-
lr = st.selectbox("Learning Rate",[0.1,0.01,0.02,0.2])
|
| 46 |
-
|
| 47 |
-
# col3,col4 = st.column(2)
|
| 48 |
|
| 49 |
-
|
| 50 |
-
reg = st.selectbox("Regularizer", ["None", "L1", "L2","ElasticNet"])
|
| 51 |
if reg != "None":
|
| 52 |
reg_rate = st.slider("Regularization rate", 0.0, 0.1, 0.01)
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
if
|
| 56 |
col3, col4 = st.columns(2)
|
| 57 |
with col3:
|
| 58 |
-
min_delta = st.number_input("Minimum Delta",0.001,0.9,step=0.
|
| 59 |
-
|
| 60 |
with col4:
|
| 61 |
-
patience = st.number_input("Patience",3,20,step=1)
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
if
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
x,y=make_moons(n_samples=1000,noise=noise,random_state=42)
|
| 74 |
elif dataset == "Blobs":
|
| 75 |
-
|
| 76 |
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
| 78 |
|
|
|
|
| 79 |
std = StandardScaler()
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
|
|
|
|
| 84 |
if reg == "L1":
|
| 85 |
reg = l1(reg_rate)
|
| 86 |
elif reg == "L2":
|
|
@@ -88,42 +275,70 @@ if btn:
|
|
| 88 |
elif reg == "ElasticNet":
|
| 89 |
reg = l1_l2(l1=reg_rate, l2=reg_rate)
|
| 90 |
else:
|
| 91 |
-
reg=None
|
| 92 |
-
|
| 93 |
-
|
| 94 |
|
|
|
|
| 95 |
model = Sequential()
|
| 96 |
model.add(InputLayer(shape=(2,)))
|
| 97 |
if hl == len(nn):
|
| 98 |
-
for
|
| 99 |
-
model.add(Dense(units=
|
| 100 |
|
| 101 |
-
model.add(Dense(units=1,activation="sigmoid",kernel_regularizer=reg))
|
| 102 |
-
sgd=SGD(learning_rate=lr)
|
| 103 |
-
model.compile(loss="binary_crossentropy",optimizer=sgd,metrics=["accuracy"])
|
| 104 |
-
train_size=round(x_train.shape[0]-x_train.shape[0]*0.2)
|
| 105 |
|
|
|
|
| 106 |
callbacks = []
|
| 107 |
-
if
|
| 108 |
es = EarlyStopping(
|
| 109 |
monitor="val_loss",
|
| 110 |
-
|
| 111 |
-
min_delta = min_delta,
|
| 112 |
patience=patience,
|
| 113 |
verbose=1,
|
| 114 |
restore_best_weights=True,
|
| 115 |
-
start_from_epoch=50
|
| 116 |
)
|
| 117 |
callbacks.append(es)
|
| 118 |
-
|
| 119 |
-
hist=model.fit(x_train,y_train,epochs=epochs,batch_size=train_size,validation_data=(x_test, y_test),verbose=False)
|
| 120 |
|
| 121 |
-
#
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
|
| 128 |
# ---------------- Graphical NN Architecture ----------------
|
| 129 |
st.subheader("Neural Network Architecture")
|
|
@@ -149,29 +364,6 @@ if btn:
|
|
| 149 |
dot = visualize_nn(nn)
|
| 150 |
st.graphviz_chart(dot)
|
| 151 |
|
| 152 |
-
|
| 153 |
-
# --- Plotting Decision region ---
|
| 154 |
-
st.subheader("Decision Region")
|
| 155 |
-
fig1, ax1 = plt.subplots(figsize=(6, 5))
|
| 156 |
-
plot_decision_regions(X=x_train, y=y_train.astype(np.int_), clf=model, ax=ax1)
|
| 157 |
-
#plot_decision_regions(X=x_test, y=y_test.astype(np.int_), clf=model, ax=ax1)
|
| 158 |
-
ax1.set_title("Decision Regions", fontsize=12, weight="bold")
|
| 159 |
-
st.pyplot(fig1)
|
| 160 |
-
|
| 161 |
-
# --- Plot 2: Training vs Validation Loss ---
|
| 162 |
-
st.subheader("Training vs Validation Loss")
|
| 163 |
-
fig2, ax2 = plt.subplots(figsize=(6, 5))
|
| 164 |
-
ax2.plot(hist.history["loss"], label="Training Loss", linewidth=2)
|
| 165 |
-
ax2.plot(hist.history["val_loss"], label="Validation Loss", linewidth=2, linestyle="--")
|
| 166 |
-
ax2.set_xlabel("Epochs")
|
| 167 |
-
ax2.set_ylabel("Loss")
|
| 168 |
-
ax2.legend()
|
| 169 |
-
ax2.grid(alpha=0.3)
|
| 170 |
-
st.pyplot(fig2)
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
|
| 176 |
|
| 177 |
|
|
|
|
| 1 |
+
# import streamlit as st
|
| 2 |
+
# import numpy as np
|
| 3 |
+
# from sklearn.datasets import make_circles,make_moons,make_blobs
|
| 4 |
+
# from sklearn.preprocessing import StandardScaler
|
| 5 |
+
# from sklearn.model_selection import train_test_split
|
| 6 |
+
# from tensorflow import keras
|
| 7 |
+
# import matplotlib.pyplot as plt
|
| 8 |
+
# import seaborn as sns
|
| 9 |
+
# from keras.models import Sequential
|
| 10 |
+
# from keras.layers import InputLayer,Dense,Dropout
|
| 11 |
+
# from keras.losses import MeanAbsoluteError,MeanSquaredError
|
| 12 |
+
# from keras.optimizers import SGD
|
| 13 |
+
# from keras.regularizers import l1,l1,l1_l2
|
| 14 |
+
|
| 15 |
+
# from mlxtend.plotting import plot_decision_regions
|
| 16 |
+
# import graphviz
|
| 17 |
+
|
| 18 |
+
# st.title("TensorFlow Playground")
|
| 19 |
+
|
| 20 |
+
# with st.sidebar:
|
| 21 |
+
# st.header("Choose Dataset")
|
| 22 |
+
# dataset = st.selectbox("Select Dataset",["Blobs","Circles","Moons"])
|
| 23 |
+
# # on = st.toggle("Upload Dataset(.csv file)")
|
| 24 |
+
# # if on:
|
| 25 |
+
# # st.write("**Note:** Only 2 features are allowed.")
|
| 26 |
+
# # up_file = st.file_uploader("Upload Dataset (.csv or .xlsx)", type=["csv"])
|
| 27 |
+
|
| 28 |
+
# noise = st.slider("Noise",0.0,1.0,0.1)
|
| 29 |
+
# test_size = st.slider("Test Size",0.1,0.5,0.05)
|
| 30 |
+
|
| 31 |
+
# st.header("Model Hyperparameters")
|
| 32 |
+
# hl = st.number_input("Hidden Layers",1,10,step=1)
|
| 33 |
+
# numbers = st.text_input("Neurons for each hidden layer" ,placeholder="e.g. 8,16,32")
|
| 34 |
+
# input_func = lambda x: [int(i.strip()) for i in x.split(",") if i.strip() != ""]
|
| 35 |
+
# nn = input_func(numbers)
|
| 36 |
+
# epochs=st.number_input("Epochs",1,10000,step=1,value=10)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# col1, col2 = st.columns(2)
|
| 41 |
+
|
| 42 |
+
# with col1:
|
| 43 |
+
# af = st.selectbox("Activation Function",["sigmoid","tanh","relu"],index=2)
|
| 44 |
+
# with col2:
|
| 45 |
+
# lr = st.selectbox("Learning Rate",[0.1,0.01,0.02,0.2])
|
| 46 |
+
|
| 47 |
+
# # col3,col4 = st.column(2)
|
| 48 |
+
|
| 49 |
+
# # with col3:
|
| 50 |
+
# reg = st.selectbox("Regularizer", ["None", "L1", "L2","ElasticNet"])
|
| 51 |
+
# if reg != "None":
|
| 52 |
+
# reg_rate = st.slider("Regularization rate", 0.0, 0.1, 0.01)
|
| 53 |
+
# # with col4:
|
| 54 |
+
# es = st.selectbox("Early Stopping",["No","Yes"],index=0)
|
| 55 |
+
# if es == "Yes":
|
| 56 |
+
# col3, col4 = st.columns(2)
|
| 57 |
+
# with col3:
|
| 58 |
+
# min_delta = st.number_input("Minimum Delta",0.001,0.9,step=0.1)
|
| 59 |
+
|
| 60 |
+
# with col4:
|
| 61 |
+
# patience = st.number_input("Patience",3,20,step=1)
|
| 62 |
+
|
| 63 |
+
# btn=st.sidebar.button("Train")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# if btn:
|
| 69 |
+
# if dataset:
|
| 70 |
+
# if dataset=="Circles":
|
| 71 |
+
# x,y=make_circles(n_samples=1000,noise=noise,random_state=42,factor=0.1)
|
| 72 |
+
# elif dataset=="moons":
|
| 73 |
+
# x,y=make_moons(n_samples=1000,noise=noise,random_state=42)
|
| 74 |
+
# elif dataset == "Blobs":
|
| 75 |
+
# x,y=make_blobs(n_samples=1000, centers=2, cluster_std=noise, random_state=42)
|
| 76 |
+
|
| 77 |
+
# x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=test_size,random_state=42,stratify=y)
|
| 78 |
+
|
| 79 |
+
# std = StandardScaler()
|
| 80 |
+
# x_train = std.fit_transform(x_train)
|
| 81 |
+
# x_test = std.transform(x_test)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
# if reg == "L1":
|
| 85 |
+
# reg = l1(reg_rate)
|
| 86 |
+
# elif reg == "L2":
|
| 87 |
+
# reg = l2(reg_rate)
|
| 88 |
+
# elif reg == "ElasticNet":
|
| 89 |
+
# reg = l1_l2(l1=reg_rate, l2=reg_rate)
|
| 90 |
+
# else:
|
| 91 |
+
# reg=None
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
# model = Sequential()
|
| 96 |
+
# model.add(InputLayer(shape=(2,)))
|
| 97 |
+
# if hl == len(nn):
|
| 98 |
+
# for i in range(0,len(nn)):
|
| 99 |
+
# model.add(Dense(units=nn[i],activation=af,kernel_regularizer=reg))
|
| 100 |
+
|
| 101 |
+
# model.add(Dense(units=1,activation="sigmoid",kernel_regularizer=reg))
|
| 102 |
+
# sgd=SGD(learning_rate=lr)
|
| 103 |
+
# model.compile(loss="binary_crossentropy",optimizer=sgd,metrics=["accuracy"])
|
| 104 |
+
# train_size=round(x_train.shape[0]-x_train.shape[0]*0.2)
|
| 105 |
+
|
| 106 |
+
# callbacks = []
|
| 107 |
+
# if es == "Yes":
|
| 108 |
+
# es = EarlyStopping(
|
| 109 |
+
# monitor="val_loss",
|
| 110 |
+
# #min_delta= min_delta if min_delta else 0.001,
|
| 111 |
+
# min_delta = min_delta,
|
| 112 |
+
# patience=patience,
|
| 113 |
+
# verbose=1,
|
| 114 |
+
# restore_best_weights=True,
|
| 115 |
+
# start_from_epoch=50
|
| 116 |
+
# )
|
| 117 |
+
# callbacks.append(es)
|
| 118 |
+
|
| 119 |
+
# hist=model.fit(x_train,y_train,epochs=epochs,batch_size=train_size,validation_data=(x_test, y_test),verbose=False)
|
| 120 |
+
|
| 121 |
+
# # # --- Neural Network Diagram ---
|
| 122 |
+
# # st.subheader("Neural Network Architecture")
|
| 123 |
+
# # stringlist = []
|
| 124 |
+
# # model.summary(print_fn=lambda x: stringlist.append(x))
|
| 125 |
+
# # summary_str = "\n".join(stringlist)
|
| 126 |
+
# # st.text(summary_str)
|
| 127 |
+
|
| 128 |
+
# # ---------------- Graphical NN Architecture ----------------
|
| 129 |
+
# st.subheader("Neural Network Architecture")
|
| 130 |
+
|
| 131 |
+
# def visualize_nn(layers):
|
| 132 |
+
# dot = graphviz.Digraph()
|
| 133 |
+
# dot.attr(rankdir="LR")
|
| 134 |
+
|
| 135 |
+
# dot.node("Input", "Input Layer\nfeatures=2", shape="box", style="filled", color="lightblue")
|
| 136 |
+
|
| 137 |
+
# for i, units in enumerate(layers):
|
| 138 |
+
# dot.node(f"H{i}", f"Hidden {i+1}\nunits={units}", shape="box", style="filled", color="lightgreen")
|
| 139 |
+
# if i == 0:
|
| 140 |
+
# dot.edge("Input", f"H{i}")
|
| 141 |
+
# else:
|
| 142 |
+
# dot.edge(f"H{i-1}", f"H{i}")
|
| 143 |
+
|
| 144 |
+
# dot.node("Output", "Output Layer\nunits=1", shape="box", style="filled", color="lightcoral")
|
| 145 |
+
# dot.edge(f"H{len(layers)-1}" if layers else "Input", "Output")
|
| 146 |
+
|
| 147 |
+
# return dot
|
| 148 |
+
|
| 149 |
+
# dot = visualize_nn(nn)
|
| 150 |
+
# st.graphviz_chart(dot)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
# # --- Plotting Decision region ---
|
| 154 |
+
# st.subheader("Decision Region")
|
| 155 |
+
# fig1, ax1 = plt.subplots(figsize=(6, 5))
|
| 156 |
+
# plot_decision_regions(X=x_train, y=y_train.astype(np.int_), clf=model, ax=ax1)
|
| 157 |
+
# #plot_decision_regions(X=x_test, y=y_test.astype(np.int_), clf=model, ax=ax1)
|
| 158 |
+
# ax1.set_title("Decision Regions", fontsize=12, weight="bold")
|
| 159 |
+
# st.pyplot(fig1)
|
| 160 |
+
|
| 161 |
+
# # --- Plot 2: Training vs Validation Loss ---
|
| 162 |
+
# st.subheader("Training vs Validation Loss")
|
| 163 |
+
# fig2, ax2 = plt.subplots(figsize=(6, 5))
|
| 164 |
+
# ax2.plot(hist.history["loss"], label="Training Loss", linewidth=2)
|
| 165 |
+
# ax2.plot(hist.history["val_loss"], label="Validation Loss", linewidth=2, linestyle="--")
|
| 166 |
+
# ax2.set_xlabel("Epochs")
|
| 167 |
+
# ax2.set_ylabel("Loss")
|
| 168 |
+
# ax2.legend()
|
| 169 |
+
# ax2.grid(alpha=0.3)
|
| 170 |
+
# st.pyplot(fig2)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
|
| 174 |
import streamlit as st
|
| 175 |
import numpy as np
|
| 176 |
+
import pandas as pd
|
| 177 |
+
from sklearn.datasets import make_circles, make_moons, make_blobs
|
| 178 |
from sklearn.preprocessing import StandardScaler
|
| 179 |
from sklearn.model_selection import train_test_split
|
| 180 |
+
from tensorflow.keras.models import Sequential
|
| 181 |
+
from tensorflow.keras.layers import InputLayer, Dense
|
| 182 |
+
from tensorflow.keras.optimizers import SGD
|
| 183 |
+
from tensorflow.keras.regularizers import l1, l2, l1_l2
|
| 184 |
+
from tensorflow.keras.callbacks import EarlyStopping
|
|
|
|
|
|
|
|
|
|
| 185 |
|
| 186 |
+
import matplotlib.pyplot as plt
|
| 187 |
from mlxtend.plotting import plot_decision_regions
|
| 188 |
import graphviz
|
| 189 |
|
| 190 |
+
# -----------------------------
|
| 191 |
+
# Streamlit UI
|
| 192 |
+
# -----------------------------
|
| 193 |
st.title("TensorFlow Playground")
|
| 194 |
|
| 195 |
with st.sidebar:
|
| 196 |
+
st.header("Dataset Options")
|
| 197 |
+
dataset_mode = st.radio("Choose Dataset Mode", ["Synthetic", "Upload CSV"])
|
| 198 |
+
|
| 199 |
+
if dataset_mode == "Synthetic":
|
| 200 |
+
dataset = st.selectbox("Select Dataset", ["Blobs", "Circles", "Moons"])
|
| 201 |
+
noise = st.slider("Noise", 0.0, 1.0, 0.1)
|
| 202 |
+
test_size = st.slider("Test Size", 0.1, 0.5, 0.2)
|
| 203 |
+
else:
|
| 204 |
+
uploaded_file = st.file_uploader("Upload your CSV", type=["csv"])
|
| 205 |
+
if uploaded_file is not None:
|
| 206 |
+
df = pd.read_csv(uploaded_file)
|
| 207 |
+
if df.shape[1] < 3:
|
| 208 |
+
st.error("Your dataset must have at least 3 columns (2 features + 1 target).")
|
| 209 |
+
st.stop()
|
| 210 |
+
feature_cols = st.multiselect("Select exactly 2 features", df.columns[:-1])
|
| 211 |
+
target_col = st.selectbox("Select target column", df.columns)
|
| 212 |
+
if len(feature_cols) != 2:
|
| 213 |
+
st.error("Please select exactly 2 features.")
|
| 214 |
+
st.stop()
|
| 215 |
+
X = df[feature_cols].values
|
| 216 |
+
y = df[target_col].values
|
| 217 |
+
test_size = st.slider("Test Size", 0.1, 0.5, 0.2)
|
| 218 |
+
else:
|
| 219 |
+
st.warning("Upload a CSV file to continue.")
|
| 220 |
+
st.stop()
|
| 221 |
|
| 222 |
st.header("Model Hyperparameters")
|
| 223 |
+
hl = st.number_input("Hidden Layers", 1, 10, step=1)
|
| 224 |
+
numbers = st.text_input("Neurons for each hidden layer", placeholder="e.g. 8,16,32")
|
| 225 |
input_func = lambda x: [int(i.strip()) for i in x.split(",") if i.strip() != ""]
|
| 226 |
nn = input_func(numbers)
|
| 227 |
+
n_epochs = st.number_input("Epochs", 1, 10000, step=1, value=50)
|
|
|
|
| 228 |
|
|
|
|
| 229 |
col1, col2 = st.columns(2)
|
|
|
|
| 230 |
with col1:
|
| 231 |
+
af = st.selectbox("Activation Function", ["sigmoid", "tanh", "relu"], index=2)
|
| 232 |
with col2:
|
| 233 |
+
lr = st.selectbox("Learning Rate", [0.1, 0.01, 0.02, 0.2], index=1)
|
|
|
|
|
|
|
| 234 |
|
| 235 |
+
reg = st.selectbox("Regularizer", ["None", "L1", "L2", "ElasticNet"])
|
|
|
|
| 236 |
if reg != "None":
|
| 237 |
reg_rate = st.slider("Regularization rate", 0.0, 0.1, 0.01)
|
| 238 |
+
|
| 239 |
+
early_stop_option = st.selectbox("Early Stopping", ["No", "Yes"], index=0)
|
| 240 |
+
if early_stop_option == "Yes":
|
| 241 |
col3, col4 = st.columns(2)
|
| 242 |
with col3:
|
| 243 |
+
min_delta = st.number_input("Minimum Delta", 0.001, 0.9, step=0.01)
|
|
|
|
| 244 |
with col4:
|
| 245 |
+
patience = st.number_input("Patience", 3, 20, step=1)
|
| 246 |
|
| 247 |
+
# -----------------------------
|
| 248 |
+
# Train Button
|
| 249 |
+
# -----------------------------
|
| 250 |
+
if st.sidebar.button("Train"):
|
| 251 |
+
# ---------------- Dataset ----------------
|
| 252 |
+
if dataset_mode == "Synthetic":
|
| 253 |
+
if dataset == "Circles":
|
| 254 |
+
X, y = make_circles(n_samples=1000, noise=noise, random_state=42, factor=0.5)
|
| 255 |
+
elif dataset == "Moons":
|
| 256 |
+
X, y = make_moons(n_samples=1000, noise=noise, random_state=42)
|
|
|
|
| 257 |
elif dataset == "Blobs":
|
| 258 |
+
X, y = make_blobs(n_samples=1000, centers=2, cluster_std=noise+0.5, random_state=42)
|
| 259 |
|
| 260 |
+
# Split dataset
|
| 261 |
+
X_train, X_test, y_train, y_test = train_test_split(
|
| 262 |
+
X, y, test_size=test_size, random_state=42, stratify=y
|
| 263 |
+
)
|
| 264 |
|
| 265 |
+
# Standardize
|
| 266 |
std = StandardScaler()
|
| 267 |
+
X_train = std.fit_transform(X_train)
|
| 268 |
+
X_test = std.transform(X_test)
|
|
|
|
| 269 |
|
| 270 |
+
# ---------------- Regularizer ----------------
|
| 271 |
if reg == "L1":
|
| 272 |
reg = l1(reg_rate)
|
| 273 |
elif reg == "L2":
|
|
|
|
| 275 |
elif reg == "ElasticNet":
|
| 276 |
reg = l1_l2(l1=reg_rate, l2=reg_rate)
|
| 277 |
else:
|
| 278 |
+
reg = None
|
|
|
|
|
|
|
| 279 |
|
| 280 |
+
# ---------------- Model ----------------
|
| 281 |
model = Sequential()
|
| 282 |
model.add(InputLayer(shape=(2,)))
|
| 283 |
if hl == len(nn):
|
| 284 |
+
for units in nn:
|
| 285 |
+
model.add(Dense(units=units, activation=af, kernel_regularizer=reg))
|
| 286 |
|
| 287 |
+
model.add(Dense(units=1, activation="sigmoid", kernel_regularizer=reg))
|
| 288 |
+
sgd = SGD(learning_rate=lr)
|
| 289 |
+
model.compile(loss="binary_crossentropy", optimizer=sgd, metrics=["accuracy"])
|
|
|
|
| 290 |
|
| 291 |
+
# ---------------- Callbacks ----------------
|
| 292 |
callbacks = []
|
| 293 |
+
if early_stop_option == "Yes":
|
| 294 |
es = EarlyStopping(
|
| 295 |
monitor="val_loss",
|
| 296 |
+
min_delta=min_delta,
|
|
|
|
| 297 |
patience=patience,
|
| 298 |
verbose=1,
|
| 299 |
restore_best_weights=True,
|
| 300 |
+
start_from_epoch=50,
|
| 301 |
)
|
| 302 |
callbacks.append(es)
|
|
|
|
|
|
|
| 303 |
|
| 304 |
+
# ---------------- Training ----------------
|
| 305 |
+
hist = model.fit(
|
| 306 |
+
X_train,
|
| 307 |
+
y_train,
|
| 308 |
+
epochs=n_epochs,
|
| 309 |
+
batch_size=len(X_train),
|
| 310 |
+
validation_data=(X_test, y_test),
|
| 311 |
+
verbose=0,
|
| 312 |
+
callbacks=callbacks,
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
# ---------------- Decision Boundary ----------------
|
| 316 |
+
st.subheader("Decision Boundary")
|
| 317 |
+
fig, ax = plt.subplots()
|
| 318 |
+
plot_decision_regions(X_test, y_test, clf=model, legend=2)
|
| 319 |
+
plt.xlabel("Feature 1")
|
| 320 |
+
plt.ylabel("Feature 2")
|
| 321 |
+
st.pyplot(fig)
|
| 322 |
+
|
| 323 |
+
# ---------------- Loss Curves ----------------
|
| 324 |
+
st.subheader("Training vs Validation Loss")
|
| 325 |
+
fig2, ax2 = plt.subplots()
|
| 326 |
+
ax2.plot(hist.history["loss"], label="Train Loss")
|
| 327 |
+
ax2.plot(hist.history["val_loss"], label="Validation Loss")
|
| 328 |
+
ax2.set_xlabel("Epochs")
|
| 329 |
+
ax2.set_ylabel("Loss")
|
| 330 |
+
ax2.legend()
|
| 331 |
+
st.pyplot(fig2)
|
| 332 |
+
|
| 333 |
+
# ---------------- Accuracy Curves ----------------
|
| 334 |
+
st.subheader("Training vs Validation Accuracy")
|
| 335 |
+
fig3, ax3 = plt.subplots()
|
| 336 |
+
ax3.plot(hist.history["accuracy"], label="Train Accuracy")
|
| 337 |
+
ax3.plot(hist.history["val_accuracy"], label="Validation Accuracy")
|
| 338 |
+
ax3.set_xlabel("Epochs")
|
| 339 |
+
ax3.set_ylabel("Accuracy")
|
| 340 |
+
ax3.legend()
|
| 341 |
+
st.pyplot(fig3)
|
| 342 |
|
| 343 |
# ---------------- Graphical NN Architecture ----------------
|
| 344 |
st.subheader("Neural Network Architecture")
|
|
|
|
| 364 |
dot = visualize_nn(nn)
|
| 365 |
st.graphviz_chart(dot)
|
| 366 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 367 |
|
| 368 |
|
| 369 |
|