Adityaganesh commited on
Commit
f32b71a
·
verified ·
1 Parent(s): 59c9c3a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +110 -0
app.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import numpy as np
3
+ import matplotlib.pyplot as plt
4
+ import tensorflow as tf
5
+ from sklearn.datasets import make_moons, make_circles, make_classification
6
+ from sklearn.model_selection import train_test_split
7
+ from sklearn.preprocessing import StandardScaler
8
+ from tensorflow import keras
9
+ import plotly.graph_objects as go
10
+ import plotly.figure_factory as ff
11
+
12
+
13
+ # Sidebar: Neural Network Settings
14
+ st.sidebar.header("Neural Network Settings")
15
+ problem_type = st.sidebar.selectbox("Problem type", ["Classification", "Regression"])
16
+ dataset_choice = st.sidebar.selectbox("Dataset", ["Moons", "Circles", "Linear"])
17
+ train_ratio = st.sidebar.slider("Training Data Ratio", 0.1, 0.9, 0.5, 0.05)
18
+ noise = st.sidebar.slider("Noise Level", 0.0, 0.5, 0.1, 0.01)
19
+ batch_size = st.sidebar.slider("Batch Size", 5, 100, 10, 5)
20
+ hidden_layers = st.sidebar.slider("Hidden Layers", 1, 5, 2)
21
+ neurons_per_layer = st.sidebar.slider("Neurons per Hidden Layer", 2, 10, 4)
22
+ activation_function = st.sidebar.selectbox("Activation Function", ["relu", "sigmoid", "tanh"])
23
+ learning_rate = st.sidebar.slider("Learning Rate", 0.001, 0.1, 0.03, step=0.001)
24
+ regularization = st.sidebar.selectbox("Regularization", ["None", "L1", "L2"])
25
+ reg_rate = st.sidebar.slider("Regularization Rate", 0.0, 0.1, 0.0, step=0.01)
26
+ epochs = st.sidebar.slider("Epochs", 10, 500, 100)
27
+
28
+ # Generate Dataset
29
+ if dataset_choice == "Moons":
30
+ X, y = make_moons(n_samples=1000, noise=noise, random_state=42)
31
+ elif dataset_choice == "Circles":
32
+ X, y = make_circles(n_samples=1000, noise=noise, factor=0.5, random_state=42)
33
+ else:
34
+ X, y = make_classification(n_samples=1000, n_features=2, n_classes=2, n_redundant=0, random_state=42)
35
+
36
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1-train_ratio, random_state=42)
37
+ scaler = StandardScaler()
38
+ X_train = scaler.fit_transform(X_train)
39
+ X_test = scaler.transform(X_test)
40
+
41
+ # Build Neural Network
42
+ model = keras.Sequential([keras.layers.InputLayer(input_shape=(2,))])
43
+ reg = None
44
+ if regularization == "L1":
45
+ reg = keras.regularizers.l1(reg_rate)
46
+ elif regularization == "L2":
47
+ reg = keras.regularizers.l2(reg_rate)
48
+ for _ in range(hidden_layers):
49
+ model.add(keras.layers.Dense(neurons_per_layer, activation=activation_function, kernel_regularizer=reg))
50
+ model.add(keras.layers.Dense(1, activation="sigmoid"))
51
+
52
+ optimizer = keras.optimizers.Adam(learning_rate=learning_rate)
53
+ model.compile(optimizer=optimizer, loss="binary_crossentropy", metrics=["accuracy"])
54
+
55
+ # Train the model
56
+ history = model.fit(X_train, y_train, epochs=epochs, batch_size=batch_size, verbose=0, validation_data=(X_test, y_test))
57
+
58
+ # Training Progress Visualization
59
+ st.subheader("Training Progress")
60
+ fig, ax = plt.subplots(1, 2, figsize=(12, 4))
61
+ ax[0].plot(history.history['loss'], label="Train Loss")
62
+ ax[0].plot(history.history['val_loss'], label="Validation Loss")
63
+ ax[0].set_title("Loss Curve")
64
+ ax[0].legend()
65
+ ax[1].plot(history.history['accuracy'], label="Train Accuracy")
66
+ ax[1].plot(history.history['val_accuracy'], label="Validation Accuracy")
67
+ ax[1].set_title("Accuracy Curve")
68
+ ax[1].legend()
69
+ st.pyplot(fig)
70
+
71
+ # Neural Network Visualization
72
+ st.subheader("Neural Network Structure")
73
+ fig = go.Figure()
74
+ layer_x_positions = [0] + [i * 2 for i in range(1, hidden_layers + 1)] + [hidden_layers * 2 + 2]
75
+ layer_names = ["Input Layer"] + [f"Hidden Layer {i+1}" for i in range(hidden_layers)] + ["Output Layer"]
76
+ for i, x in enumerate(layer_x_positions):
77
+ y_positions = np.linspace(-1, 1, neurons_per_layer if i != 0 and i != len(layer_x_positions) - 1 else 2)
78
+ fig.add_trace(go.Scatter(
79
+ x=[x] * len(y_positions), y=y_positions, mode='markers+text',
80
+ marker=dict(size=20, color='blue'),
81
+ text=[f"N{j+1}" for j in range(len(y_positions))], textposition="middle right", name=layer_names[i]
82
+ ))
83
+ for i in range(len(layer_x_positions) - 1):
84
+ prev_y_positions = np.linspace(-1, 1, neurons_per_layer if i != 0 else 2)
85
+ next_y_positions = np.linspace(-1, 1, neurons_per_layer if i + 1 != len(layer_x_positions) - 1 else 1)
86
+ for y1 in prev_y_positions:
87
+ for y2 in next_y_positions:
88
+ fig.add_trace(go.Scatter(
89
+ x=[layer_x_positions[i], layer_x_positions[i + 1]],
90
+ y=[y1, y2], mode='lines', line=dict(color='gray', width=2), showlegend=False
91
+ ))
92
+ st.plotly_chart(fig, use_container_width=True)
93
+
94
+ # Decision Boundary Plot
95
+ def plot_decision_boundary(model, X, y):
96
+ x_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5
97
+ y_min, y_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5
98
+ xx, yy = np.meshgrid(np.linspace(x_min, x_max, 100),
99
+ np.linspace(y_min, y_max, 100))
100
+
101
+ Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
102
+ Z = (Z > 0.5).astype(int).reshape(xx.shape)
103
+
104
+ plt.contourf(xx, yy, Z, alpha=0.3)
105
+ plt.scatter(X[:, 0], X[:, 1], c=y, edgecolors="k")
106
+ plt.title("Decision Boundary")
107
+ st.pyplot(plt)
108
+
109
+ st.subheader("Decision Boundary")
110
+ plot_decision_boundary(model, X_test, y_test)