Gova823 commited on
Commit
22b4736
·
verified ·
1 Parent(s): d0886ac

Update app.py

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