Gova823 commited on
Commit
bb19d90
·
verified ·
1 Parent(s): 13e0bad

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +206 -4
app.py CHANGED
@@ -1,3 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # importing required libraries
2
  import streamlit as st
3
  import pandas as pd
@@ -15,8 +218,7 @@ from keras.regularizers import L1, L2
15
  import mlxtend
16
  from mlxtend.plotting import plot_decision_regions
17
  import warnings
18
- warnings.filterwarnings("ignore")
19
-
20
 
21
 
22
  # Title
@@ -89,7 +291,7 @@ else:
89
 
90
 
91
  # Construct the file path
92
- file_path = rf"C:\Users\VARSHINA\Govardhan\Machine_Learning_and_Deep_Learning\Deep Learning\Projects\Streamlit\Tensorflow_playground\web_app\data\{data_set}"
93
 
94
  # loading the data
95
  df = pd.read_csv(file_path)
@@ -253,5 +455,5 @@ if st.sidebar.button('Submit'):
253
  fig, axs = plt.subplots(figsize = (8,4))
254
  plot_decision_regions(X = st.session_state.X_test, y = st.session_state.y_test.astype(int), clf = st.session_state.model)
255
  st.pyplot(fig)
256
-
257
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ import seaborn as sns
5
+ import matplotlib.pyplot as plt
6
+ import io
7
+ from sklearn.datasets import make_classification, make_regression, make_moons, make_circles
8
+ from sklearn.model_selection import train_test_split
9
+ from sklearn.preprocessing import StandardScaler
10
+ from keras.models import Sequential
11
+ from keras.layers import InputLayer, Dense
12
+ from keras.regularizers import L1, L2
13
+ from mlxtend.plotting import plot_decision_regions
14
+ import warnings
15
+
16
+ warnings.filterwarnings("ignore")
17
+
18
+ # Title
19
+ st.sidebar.title('Tensorflow Playground')
20
+
21
+ # Problem Type
22
+ problem_type = st.sidebar.selectbox('Problem Type', ['Classification', 'Regression', 'Moons', 'Circles'])
23
+
24
+ # Choose Datasets
25
+ st.sidebar.title('Choose Dataset')
26
+
27
+ # Datasets
28
+ data_set = st.sidebar.selectbox('Datasets', [
29
+ '1.ushape.csv', '2.concerticcir1.csv', '3.concertriccir2.csv',
30
+ '4.linearsep.csv', '5.outlier.csv', '6.overlap.csv',
31
+ '7.xor.csv', '8.twospirals.csv', '9.random.csv'
32
+ ])
33
+
34
+ # Learning Rate
35
+ learning_rate = st.sidebar.selectbox('Learning Rate', [0.00001, 0.0001, 0.001, 0.01, 0.03, 0.1, 0.3, 1, 3, 10])
36
+
37
+ # Activation
38
+ activation_func = st.sidebar.selectbox('Activation', ['tanh', 'Sigmoid', 'linear', 'relu', 'softmax'])
39
+
40
+ # Regularization Rate
41
+ regularization_rate = st.sidebar.selectbox('Regularization Rate', [0.00001, 0.0001, 0.001, 0.01, 0.03, 0.1, 0.3, 1, 3, 10])
42
+
43
+ # Regularization
44
+ regularization = st.sidebar.selectbox('Regularization', ['None', 'L1', 'L2'])
45
+
46
+ # Epochs
47
+ epochs = st.sidebar.select_slider("Select number of Epochs", options=[i for i in range(1, 1001)])
48
+
49
+ # Split Train/Test
50
+ test_size = st.sidebar.slider("Test Size (%)", min_value=10, max_value=90, value=40, step=1) / 100
51
+
52
+ # Hidden layers
53
+ hidden_layers = st.sidebar.select_slider('Hidden Layers', options=[i for i in range(1, 51)])
54
+
55
+ # Regularization configuration
56
+ kernel_regularizer = None
57
+ bias_regularizer = None
58
+ if regularization == 'L1':
59
+ kernel_regularizer = L1(regularization_rate)
60
+ bias_regularizer = L1(regularization_rate)
61
+ elif regularization == 'L2':
62
+ kernel_regularizer = L2(regularization_rate)
63
+ bias_regularizer = L2(regularization_rate)
64
+
65
+ # Load Data
66
+ file_path = f"C:\\Users\\VARSHINA\\Govardhan\\Machine_Learning_and_Deep_Learning\\Deep Learning\\Projects\\Streamlit\\Tensorflow_playground\\web_app\\data\\{data_set}"
67
+ df = pd.read_csv(file_path)
68
+ X = df.iloc[:, :2].values
69
+ y = df.iloc[:, -1].values
70
+
71
+ # Build the model
72
+ model = Sequential()
73
+ model.add(InputLayer(input_shape=(2,)))
74
+ for i in range(1, hidden_layers + 1):
75
+ n = st.sidebar.text_input(f'No of Neurons in Layer {i}', '2')
76
+ try:
77
+ n = int(n)
78
+ model.add(Dense(units=n, activation=activation_func, use_bias=True, kernel_regularizer=kernel_regularizer, bias_regularizer=bias_regularizer))
79
+ except ValueError:
80
+ st.error(f"Invalid input for the number of neurons in Layer {i}. Please enter an integer.")
81
+
82
+ # Final layer configuration based on problem type
83
+ if problem_type == 'Regression':
84
+ model.add(Dense(units=1, activation='linear', use_bias=True))
85
+ else:
86
+ model.add(Dense(units=1, activation='sigmoid', use_bias=True))
87
+
88
+ # Batch Size
89
+ batch_size = st.sidebar.select_slider("Batch Size", options=[i for i in range(1, len(X)+1)])
90
+
91
+ # Initialize session state
92
+ if 'model' not in st.session_state:
93
+ st.session_state.model = None
94
+ if 'history' not in st.session_state:
95
+ st.session_state.history = None
96
+ if 'X_train' not in st.session_state:
97
+ st.session_state.X_train = None
98
+ if 'y_train' not in st.session_state:
99
+ st.session_state.y_train = None
100
+
101
+ if st.sidebar.button('Submit'):
102
+ # Data Generation for classification problems
103
+ if problem_type == 'Classification':
104
+ X, y = make_classification(n_samples=10000, n_features=2, n_informative=2, n_redundant=0, n_repeated=0, n_classes=2, class_sep=2.5, random_state=10)
105
+ elif problem_type == 'Moons':
106
+ X, y = make_moons(n_samples=10000, noise=0.1, random_state=20)
107
+ elif problem_type == 'Circles':
108
+ X, y = make_circles(n_samples=10000, noise=0.05, random_state=20)
109
+ elif problem_type == 'Regression':
110
+ X, y = make_regression(n_samples=10000, n_features=2, n_informative=2, n_targets=1, noise=0.05, random_state=20)
111
+
112
+ # Data visualization
113
+ st.subheader("Visualization of Data Points with Class Labels")
114
+ fig, ax = plt.subplots(figsize=(8, 4))
115
+ sns.scatterplot(x=X[:, 0], y=X[:, 1], hue=y, ax=ax)
116
+ st.pyplot(fig)
117
+
118
+ # Split train/test
119
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=20, stratify=y)
120
+
121
+ # Standardize
122
+ scaler = StandardScaler()
123
+ X_train = scaler.fit_transform(X_train)
124
+ X_test = scaler.transform(X_test)
125
+
126
+ # Save model and training data in session state
127
+ st.session_state.model = model
128
+ st.session_state.X_train = X_train
129
+ st.session_state.y_train = y_train
130
+ st.session_state.X_test = X_test
131
+ st.session_state.y_test = y_test
132
+
133
+ # Display model summary
134
+ buffer = io.StringIO()
135
+ model.summary(print_fn=lambda x: buffer.write(x + '\n'))
136
+ st.subheader("Model Summary:")
137
+ st.text(buffer.getvalue())
138
+ buffer.close()
139
+
140
+ # Compile and train the model
141
+ if problem_type == 'Regression':
142
+ model.compile(optimizer='sgd', loss='mse', metrics=['mae', 'mse'])
143
+ else:
144
+ model.compile(optimizer='sgd', loss='binary_crossentropy', metrics=['accuracy'])
145
+
146
+ st.session_state.history = model.fit(X_train, y_train, epochs=epochs, batch_size=batch_size, verbose=1, validation_split=0.2)
147
+
148
+ # Plot loss and accuracy
149
+ fig, ax = plt.subplots(figsize=(8, 4))
150
+ ax.plot(range(1, epochs + 1), st.session_state.history.history['loss'], label='Train loss')
151
+ ax.plot(range(1, epochs + 1), st.session_state.history.history['val_loss'], label='Val loss')
152
+ ax.set_title("Training and Validation Loss Analysis")
153
+ ax.set_xlabel('Epochs')
154
+ ax.set_ylabel('Loss')
155
+ ax.legend()
156
+ st.pyplot(fig)
157
+
158
+ if problem_type != 'Regression':
159
+ fig, ax = plt.subplots(figsize=(8, 4))
160
+ ax.plot(range(1, epochs + 1), st.session_state.history.history['accuracy'], label='Train Accuracy')
161
+ ax.plot(range(1, epochs + 1), st.session_state.history.history['val_accuracy'], label='Val Accuracy')
162
+ ax.set_title('Training and Validation Accuracy Analysis')
163
+ ax.set_xlabel('Epochs')
164
+ ax.set_ylabel('Accuracy')
165
+ ax.legend()
166
+ st.pyplot(fig)
167
+
168
+ # Plot decision surface
169
+ fig, ax = plt.subplots(figsize=(8, 4))
170
+ plot_decision_regions(X=st.session_state.X_train, y=st.session_state.y_train.astype(int), clf=st.session_state.model)
171
+ st.pyplot(fig)
172
+
173
+ fig, ax = plt.subplots(figsize=(8, 4))
174
+ plot_decision_regions(X=st.session_state.X_test, y=st.session_state.y_test.astype(int), clf=st.session_state.model)
175
+ st.pyplot(fig)
176
+
177
+
178
+
179
+
180
+
181
+
182
+
183
+
184
+
185
+
186
+
187
+
188
+
189
+
190
+
191
+
192
+
193
+
194
+
195
+
196
+
197
+
198
+
199
+
200
+
201
+
202
+
203
+ '''
204
  # importing required libraries
205
  import streamlit as st
206
  import pandas as pd
 
218
  import mlxtend
219
  from mlxtend.plotting import plot_decision_regions
220
  import warnings
221
+ warnings.filterwarnings("ignore")
 
222
 
223
 
224
  # Title
 
291
 
292
 
293
  # Construct the file path
294
+ file_path = f"C:\Users\VARSHINA\Govardhan\Machine_Learning_and_Deep_Learning\Deep Learning\Projects\Streamlit\Tensorflow_playground\web_app\data\{data_set}"
295
 
296
  # loading the data
297
  df = pd.read_csv(file_path)
 
455
  fig, axs = plt.subplots(figsize = (8,4))
456
  plot_decision_regions(X = st.session_state.X_test, y = st.session_state.y_test.astype(int), clf = st.session_state.model)
457
  st.pyplot(fig)
458
+ '''
459