trohith89 commited on
Commit
1d335d9
·
verified ·
1 Parent(s): 2e084d0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +195 -89
app.py CHANGED
@@ -1,104 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  import numpy as np
3
  import matplotlib.pyplot as plt
4
- import networkx as nx
5
- from sklearn.datasets import make_classification, make_moons, make_circles, make_regression
6
- from sklearn.model_selection import train_test_split
7
- from sklearn.preprocessing import StandardScaler
8
- from tensorflow import keras
9
- from tensorflow.keras import layers
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
- # Title Bar
12
- st.title("Neural Network Playground")
 
 
 
13
 
14
- # Navigation Bar
15
- col1, col2, col3, col4, col5, col6, col7 = st.columns(7)
 
16
 
17
  with col1:
18
- epochs = st.selectbox("Epochs", [100, 200, 500, 800, 1000, 1500, 2000])
 
 
19
  with col2:
20
- learning_rate = st.selectbox("Learning Rate", [0.0001, 0.001, 0.01, 0.1, 0.3, 1, 3, 10])
 
21
  with col3:
22
- activation = st.selectbox("Activation Function", ["ReLU", "Tanh", "Sigmoid", "Linear"])
 
23
  with col4:
24
- reg_type = st.selectbox("Regularization Type", ["L1", "L2", "None"])
25
- reg_rate = st.slider("Regularization Rate", 0.0, 0.1, 0.01, step=0.01)
26
  with col5:
27
- problem_type = st.selectbox("Problem Type", ["Classification", "Regression"])
28
  with col6:
29
- play = st.button("Train Model")
30
  with col7:
31
- epoch_counter = st.empty()
32
-
33
- # Dataset Selection & Preprocessing
34
- st.subheader("Dataset Selection & Preprocessing")
35
- dataset_type = st.selectbox("Select Dataset", ["Binary Classification", "XOR", "Binary Spiral", "Binary Circles", "Regression 1", "Regression 2"])
36
- test_ratio = st.slider("Train-Test Split Ratio", 0.1, 0.5, 0.2, step=0.05)
37
- batch_size = st.slider("Batch Size", 4, 64, 16, step=2)
38
-
39
- data_generated = False
40
- X_train, X_test, y_train, y_test = None, None, None, None
41
-
42
- if st.button("Generate Dataset"):
43
- if dataset_type == "Binary Classification":
44
- X, y = make_classification(n_samples=1000, n_features=2, n_classes=2, random_state=42)
45
- elif dataset_type == "XOR":
46
- X, y = make_moons(n_samples=1000, noise=0.2, random_state=42)
47
- elif dataset_type == "Binary Spiral":
48
- X, y = make_circles(n_samples=1000, noise=0.2, factor=0.5, random_state=42)
49
- elif dataset_type == "Regression 1":
50
- X, y = make_regression(n_samples=1000, n_features=1, noise=5, random_state=42)
51
- elif dataset_type == "Regression 2":
52
- X = np.linspace(-1, 1, 1000).reshape(-1, 1)
53
- y = X ** 3 + 0.1 * np.random.randn(1000, 1).flatten()
54
-
55
- X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_ratio, random_state=42)
56
- scaler = StandardScaler()
57
- X_train = scaler.fit_transform(X_train)
58
- X_test = scaler.transform(X_test)
59
- data_generated = True
60
- st.success("Dataset Generated Successfully")
61
- st.subheader("Dataset Preview")
62
- st.write("Features:")
63
- st.write(X[:5])
64
- st.write("Labels:")
65
- st.write(y[:5])
66
-
67
- # Model Training
68
- if play and data_generated:
69
- model = keras.Sequential()
70
- model.add(layers.InputLayer(input_shape=(X_train.shape[1],)))
71
-
72
- for i in range(3): # Defaulting to 3 layers
73
- model.add(layers.Dense(10, activation=activation.lower(),
74
- kernel_regularizer=keras.regularizers.l1(reg_rate) if reg_type == "L1" else
75
- (keras.regularizers.l2(reg_rate) if reg_type == "L2" else None)))
76
- model.add(layers.Dropout(0.2))
77
-
78
- model.add(layers.Dense(1, activation="sigmoid" if problem_type == "Classification" else "linear"))
79
- model.compile(optimizer=keras.optimizers.Adam(learning_rate=learning_rate),
80
- loss="binary_crossentropy" if problem_type == "Classification" else "mse",
81
- metrics=["accuracy"] if problem_type == "Classification" else [])
82
-
83
- history = model.fit(X_train, y_train, epochs=epochs, batch_size=batch_size, verbose=0, validation_data=(X_test, y_test))
84
- st.success("Model Training Complete")
85
-
86
- # Plot Training History
87
- st.subheader("Training Progress")
88
- fig, ax = plt.subplots(1, 2, figsize=(15, 6))
89
- ax[0].plot(history.history['loss'], label='Training Loss')
90
- ax[0].plot(history.history['val_loss'], label='Validation Loss')
91
- ax[0].set_title("Loss Curve")
92
- ax[0].set_xlabel("Epochs")
93
- ax[0].set_ylabel("Loss")
94
- ax[0].legend()
95
-
96
- if problem_type == "Classification":
97
- ax[1].plot(history.history['accuracy'], label='Training Accuracy')
98
- ax[1].plot(history.history['val_accuracy'], label='Validation Accuracy')
99
- ax[1].set_title("Accuracy Curve")
100
- ax[1].set_xlabel("Epochs")
101
- ax[1].set_ylabel("Accuracy")
102
- ax[1].legend()
103
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  st.pyplot(fig)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Rohith Ramdass
2
+ rohith.r18
3
+ Idle
4
+
5
+ Rohith Ramdass — 1/23/25, 3:30 PM
6
+ hi
7
+ Attachment file type: unknown
8
+ chandrika_classification (1).ipynb
9
+ 1.13 MB
10
+ N_Days,Status,Drug,Age,Sex,Ascites,Hepatomegaly,Spiders,Edema,Bilirubin,Cholesterol,Albumin,Copper,Alk_Phos,SGOT,Tryglicerides,Platelets,Prothrombin,Stage
11
+ 2221,C,Placebo,18499,F,N,Y,N,N,0.5,149.0,4.04,227.0,598.0,52.7,57.0,256.0,9.9,1
12
+ 1230,C,Placebo,19724,M,Y,N,Y,N,0.5,219.0,3.93,22.0,663.0,45.0,75.0,220.0,10.8,2
13
+ 4184,C,Placebo,11839,F,N,N,N,N,0.5,320.0,3.54,51.0,1243.0,122.45,80.0,225.0,10.0,2
14
+ 2090,D,Placebo,16467,F,N,N,N,N,0.7,255.0,3.74,23.0,1024.0,77.5,58.0,151.0,10.2,2
15
+ 2105,D,Placebo,21699,F,N,Y,N,N,1.9,486.0,3.54,74.0,1052.0,108.5,109.0,151.0,11.5,1... (3 MB left)
16
+ Expand
17
+ liver_cirrhosis.csv
18
+ 3 MB
19
+ Rohith Ramdass — 1/23/25, 5:02 PM
20
+ Attachment file type: unknown
21
+ Consumer_Electronics_Sales_Prediction_Main (1) (1).ipynb
22
+ 1.90 MB
23
+ yamunagovindha — 1/31/25, 7:16 PM
24
+ hi classification dhi file petava nedhi
25
+ Rohith Ramdass — 1/31/25, 7:25 PM
26
+ Attachment file type: unknown
27
+ Consumer_Electronics_Sales_Prediction_Final (1) (1).ipynb
28
+ 5.51 MB
29
+ ide kada or face detection?
30
+ yamunagovindha — 1/31/25, 7:27 PM
31
+ ha ide
32
+ yamunagovindha — 2/6/25, 6:07 PM
33
+ Attachment file type: document
34
+ IMDB_PPT (1).pptx
35
+ 1.76 MB
36
+ yamunagovindha — Today at 11:43 AM
37
  import streamlit as st
38
  import numpy as np
39
  import matplotlib.pyplot as plt
40
+ import seaborn as sns
41
+ import graphviz
42
+ import time
43
+ Expand
44
+ message.txt
45
+ 6 KB
46
+ 
47
+ yamunagovindha
48
+ 123yamu_
49
+ import streamlit as st
50
+ import numpy as np
51
+ import matplotlib.pyplot as plt
52
+ import seaborn as sns
53
+ import graphviz
54
+ import time
55
+ from sklearn.datasets import make_moons, make_circles, make_classification
56
+
57
+ # Set Streamlit page title
58
+ st.set_page_config(page_title="Neural Network Trainer", layout="wide")
59
 
60
+ # ================= Session State for Training Controls =================
61
+ if "epoch" not in st.session_state:
62
+ st.session_state.epoch = 0
63
+ if "running" not in st.session_state:
64
+ st.session_state.running = False
65
 
66
+ # ================= TRAINING CONTROL PANEL (Top) =================
67
+ st.markdown("### Training Controls")
68
+ col1, col2, col3, col4, col5, col6, col7, col8, col9 = st.columns(9)
69
 
70
  with col1:
71
+ if st.button("↩️ Reset"):
72
+ st.session_state.epoch = 0
73
+ st.session_state.running = False
74
  with col2:
75
+ if st.button("▶️ Train"):
76
+ st.session_state.running = True
77
  with col3:
78
+ if st.button("⏸️ Pause"):
79
+ st.session_state.running = False
80
  with col4:
81
+ activation = st.selectbox("Activation", ["ReLU", "Sigmoid", "Tanh", "LeakyReLU"])
 
82
  with col5:
83
+ regularization = st.selectbox("Regularization", ["None", "L1", "L2"])
84
  with col6:
85
+ reg_rate = st.selectbox("Regularization Rate", [0.0001, 0.001, 0.01, 0.1]) if regularization in ["L1", "L2"] else 0
86
  with col7:
87
+ problem_type = st.selectbox("Problem Type", ["Classification", "Regression"])
88
+ with col8:
89
+ learning_rate = st.selectbox("Learning Rate", [0.0001, 0.001, 0.01, 0.03, 0.1])
90
+ with col9:
91
+ st.write(f"Epoch: **{st.session_state.epoch}**")
92
+
93
+ # 🚀 **Fix:** Run training loop without breaking Streamlit
94
+ if st.session_state.running:
95
+ time.sleep(1) # Simulating training
96
+ st.session_state.epoch += 1
97
+
98
+ # ================= MAIN LAYOUT =================
99
+ col_features, col_hidden, col_output = st.columns([2, 2, 2])
100
+
101
+ # ========== FEATURES PANEL (Left) ========== #
102
+ with col_features:
103
+ st.header("FEATURES")
104
+ st.write("Which properties do you want to feed in?")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
 
106
+ x1 = st.checkbox("X₁", value=True)
107
+ x2 = st.checkbox("X₂", value=True)
108
+ x1_squared = st.checkbox("X₁²")
109
+ x2_squared = st.checkbox("X₂²")
110
+ x1_x2 = st.checkbox("X₁X₂")
111
+ sin_x1 = st.checkbox("sin(X₁)")
112
+ sin_x2 = st.checkbox("sin(X₂)")
113
+
114
+ # ========== HIDDEN LAYERS PANEL (Middle) ========== #
115
+ with col_hidden:
116
+ st.header("HIDDEN LAYERS")
117
+ hidden_layers = st.slider("Number of Hidden Layers", 1, 7, 2)
118
+
119
+ neurons = []
120
+ for i in range(hidden_layers):
121
+ neurons.append(st.slider(f"Neurons in Layer {i+1}", 1, 20, 4))
122
+
123
+ # ========== OUTPUT PANEL (Right) ========== #
124
+ with col_output:
125
+ st.header("OUTPUT")
126
+ st.write("Test Loss: *0.501*")
127
+ st.write("Training Loss: *0.507*")
128
+
129
+ # Spiral Plot with Updated Color Palette
130
+ x = np.linspace(-6, 6, 300)
131
+ y = np.sin(x) + np.random.normal(0, 0.1, x.shape)
132
+
133
+ fig, ax = plt.subplots()
134
+ sns.scatterplot(x=x, y=y, hue=x, palette="plasma", ax=ax)
135
  st.pyplot(fig)
136
+
137
+ show_test_data = st.checkbox("Show test data")
138
+ discretize_output = st.checkbox("Discretize output")
139
+
140
+ # ================= DATASET SELECTION (Sidebar) =================
141
+ st.sidebar.header("DATA")
142
+
143
+ dataset_option = st.sidebar.radio(
144
+ "Which dataset do you want to use?",
145
+ ("Moons", "Circles", "Spiral"),
146
+ index=2
147
+ )
148
+
149
+ train_ratio = st.sidebar.slider("Ratio of training to test data:", 10, 90, 50, format="%d%%")
150
+ noise = st.sidebar.slider("Noise:", 0.0, 1.0, 0.1, step=0.1)
151
+ batch_size = st.sidebar.slider("Batch size:", 1, 100, 10)
152
+
153
+ # ================= DATASET GENERATION =================
154
+ def generate_data():
155
+ if dataset_option == "Moons":
156
+ X, y = make_moons(n_samples=500, noise=noise)
157
+ elif dataset_option == "Circles":
158
+ X, y = make_circles(n_samples=500, noise=noise)
159
+ else:
160
+ theta = np.sqrt(np.random.rand(500)) * 2 * np.pi
161
+ r = theta
162
+ X = np.array([r * np.cos(theta), r * np.sin(theta)]).T
163
+ y = (theta % (2 * np.pi)) > np.pi
164
+ return X, y
165
+
166
+ X, y = generate_data()
167
+
168
+ # =================== DRAW NEURAL NETWORK ===================
169
+ def draw_neural_network():
170
+ graph = graphviz.Digraph()
171
+
172
+ # Input Layer
173
+ graph.node("X1", "X₁", shape="circle", style="filled", fillcolor="lightblue")
174
+ graph.node("X2", "X₂", shape="circle", style="filled", fillcolor="lightblue")
175
+
176
+ prev_layer = ["X1", "X2"]
177
+
178
+ # Hidden Layers
179
+ for i, num_neurons in enumerate(neurons):
180
+ current_layer = [f"H{i+1}{j+1}" for j in range(num_neurons)]
181
+ for neuron in current_layer:
182
+ graph.node(neuron, neuron, shape="circle", style="filled", fillcolor="lightyellow")
183
+ for prev in prev_layer:
184
+ for curr in current_layer:
185
+ graph.edge(prev, curr)
186
+ prev_layer = current_layer
187
+
188
+ # Output Layer
189
+ graph.node("Output", "Output", shape="circle", style="filled", fillcolor="lightgreen")
190
+ for neuron in prev_layer:
191
+ graph.edge(neuron, "Output")
192
+
193
+ return graph
194
+
195
+ # =================== DISPLAY DATA PLOT ===================
196
+ st.sidebar.subheader("Dataset Visualization")
197
+ fig, ax = plt.subplots()
198
+ ax.scatter(X[:, 0], X[:, 1], c=y, cmap="plasma", edgecolors="k")
199
+ st.sidebar.pyplot(fig)
200
+
201
+ # =================== DISPLAY NEURAL NETWORK ===================
202
+ st.graphviz_chart(draw_neural_network())
203
+
204
+ # =================== TRAINING STATUS ===================
205
+ if st.session_state.running:
206
+ st.write("🚀 Training started...")
207
+ elif not st.session_state.running and st.session_state.epoch > 0:
208
+ st.write("⏸️ Training paused.")
209
+ message.txt
210
+ 6 KB