Gowthamvemula commited on
Commit
60d3df6
·
verified ·
1 Parent(s): 519389b

Update Home.py

Browse files
Files changed (1) hide show
  1. Home.py +187 -111
Home.py CHANGED
@@ -1,115 +1,191 @@
1
- import tensorflow as tf
2
- from tensorflow.keras import layers, regularizers, optimizers, losses, metrics
3
- from tensorflow.keras.models import Sequential
4
- from tensorflow.keras.callbacks import Callback
5
-
6
- # Custom Callback to Log Epoch Details
7
- class EpochLearningRateLogger(Callback):
8
- """
9
- Logs epoch number, learning rate, and model details during training.
10
- """
11
- def __init__(self, model, problem_type, activation_function, regularization_type=None, regularization_rate=None):
12
- super().__init__()
13
- self.model = model
14
- self.problem_type = problem_type
15
- self.activation_function = activation_function
16
- self.regularization_type = regularization_type
17
- self.regularization_rate = regularization_rate
18
-
19
- def on_epoch_begin(self, epoch, logs=None):
20
- optimizer = self.model.optimizer
21
- learning_rate = optimizer.learning_rate.numpy()
22
-
23
- print(f"\nEpoch: {epoch + 1}")
24
- print(f"Learning Rate: {learning_rate}")
25
- print(f"Problem Type: {self.problem_type}")
26
- print(f"Activation Function: {self.activation_function}")
27
-
28
- if self.regularization_type:
29
- print(f"Regularization Type: {self.regularization_type}")
30
- print(f"Regularization Rate: {self.regularization_rate}")
31
-
32
- # Function to Create the Model
33
- def create_model(input_shape, problem_type, activation_function='relu', regularization_type=None, regularization_rate=0.01, num_classes=None):
34
- """
35
- Builds and compiles a TensorFlow Keras model based on given parameters.
36
- """
37
- if problem_type == "classification" and num_classes is None:
38
- raise ValueError("num_classes must be specified for classification problems.")
39
-
40
- model = Sequential()
41
- model.add(layers.Input(shape=input_shape))
42
- model.add(layers.Flatten()) # Flatten input (useful for images)
43
-
44
- # Apply Regularization if specified
45
- kernel_regularizer = None
46
- if regularization_type == 'l1':
47
- kernel_regularizer = regularizers.L1(regularization_rate)
48
- elif regularization_type == 'l2':
49
- kernel_regularizer = regularizers.L2(regularization_rate)
50
-
51
- # Hidden Layers
52
- model.add(layers.Dense(128, activation=activation_function, kernel_regularizer=kernel_regularizer))
53
- model.add(layers.Dense(64, activation=activation_function, kernel_regularizer=kernel_regularizer))
54
-
55
- # Output Layer
56
- if problem_type == "classification":
57
- model.add(layers.Dense(num_classes, activation='softmax'))
58
- loss_function = losses.CategoricalCrossentropy()
59
- metrics_list = ['accuracy']
60
- elif problem_type == "regression":
61
- model.add(layers.Dense(1)) # Linear activation for regression
62
- loss_function = losses.MeanSquaredError()
63
- metrics_list = ['mean_absolute_error']
64
- else:
65
- raise ValueError("Invalid problem_type. Must be 'classification' or 'regression'.")
66
-
67
- # Compile Model
68
- model.compile(optimizer=optimizers.Adam(), loss=loss_function, metrics=metrics_list)
69
- return model
70
-
71
- # Main Execution
72
- if __name__ == '__main__':
73
- # Model Parameters
74
- input_shape = (28, 28, 1) # Example: MNIST images
75
- num_classes = 10 # Example: MNIST has 10 classes
76
- problem_type = "classification"
77
- activation_function = 'relu'
78
- regularization_type = 'l2'
79
- regularization_rate = 0.001
80
-
81
- # Create and Display Model Summary
82
- model = create_model(input_shape, problem_type, activation_function, regularization_type, regularization_rate, num_classes)
83
- model.summary()
84
-
85
- # Load and Preprocess MNIST Data
86
- (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
87
- x_train, x_test = x_train.astype('float32') / 255.0, x_test.astype('float32') / 255.0
88
-
89
- # Reshape Images to Include Channel Dimension
90
- x_train, x_test = x_train.reshape((-1, 28, 28, 1)), x_test.reshape((-1, 28, 28, 1))
91
-
92
- # One-Hot Encoding for Classification
93
- if problem_type == "classification":
94
- y_train = tf.keras.utils.to_categorical(y_train, num_classes)
95
- y_test = tf.keras.utils.to_categorical(y_test, num_classes)
96
-
97
- # Define Custom Callback
98
- epoch_lr_logger = EpochLearningRateLogger(
99
- model=model,
100
- problem_type=problem_type,
101
- activation_function=activation_function,
102
- regularization_type=regularization_type,
103
- regularization_rate=regularization_rate
104
  )
105
 
106
- # Train Model
107
- history = model.fit(
108
- x_train, y_train,
109
- epochs=5,
110
- batch_size=32,
111
- validation_data=(x_test, y_test),
112
- callbacks=[epoch_lr_logger]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  )
114
 
115
- print("\nTraining Completed.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ mport streamlit as st
2
+ import numpy as np
3
+ from sklearn.datasets import load_iris
4
+ from sklearn.model_selection import train_test_split
5
+ from sklearn.preprocessing import StandardScaler, OneHotEncoder
6
+ from tensorflow import keras
7
+ from tensorflow.keras import layers, regularizers
8
+
9
+ def main():
10
+ st.title("Neural Network Playground (TensorFlow + Streamlit)")
11
+ st.write("""
12
+ This demo trains a simple feed-forward neural network on the Iris dataset.
13
+ Adjust the hyperparameters below and click *Train* to see how they affect performance.
14
+ """)
15
+
16
+ # -----------------------------
17
+ # 1. SIDEBAR / HYPERPARAMETERS
18
+ # -----------------------------
19
+ st.sidebar.header("Hyperparameters")
20
+
21
+ # Learning Rate
22
+ learning_rate = st.sidebar.slider(
23
+ "Learning Rate",
24
+ min_value=1e-5,
25
+ max_value=1.0,
26
+ value=0.01,
27
+ step=1e-5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  )
29
 
30
+ # Regularization type
31
+ reg_type = st.sidebar.selectbox(
32
+ "Regularization Type",
33
+ ["None", "L1", "L2", "L1L2"]
34
+ )
35
+
36
+ # Regularization value
37
+ reg_value = st.sidebar.number_input(
38
+ "Regularization Value",
39
+ value=0.01,
40
+ step=0.01,
41
+ min_value=0.0
42
+ )
43
+
44
+ # Activation function
45
+ activation_fn = st.sidebar.selectbox(
46
+ "Activation Function",
47
+ ["sigmoid", "tanh", "relu"]
48
+ )
49
+
50
+ # Number of hidden layers
51
+ num_hidden_layers = st.sidebar.slider(
52
+ "Number of Hidden Layers",
53
+ min_value=0,
54
+ max_value=5,
55
+ value=1
56
+ )
57
+
58
+ # Neurons per hidden layer
59
+ neurons_per_layer = st.sidebar.slider(
60
+ "Neurons per Hidden Layer",
61
+ min_value=1,
62
+ max_value=128,
63
+ value=16
64
+ )
65
+
66
+ # Ratio of training to test
67
+ test_size = st.sidebar.slider(
68
+ "Test Set Ratio",
69
+ min_value=0.05,
70
+ max_value=0.95,
71
+ value=0.2,
72
+ step=0.05
73
+ )
74
+
75
+ # Batch size & Epochs
76
+ batch_size = st.sidebar.selectbox(
77
+ "Batch Size",
78
+ [8, 16, 32, 64, 128]
79
+ )
80
+ epochs = st.sidebar.slider(
81
+ "Epochs",
82
+ min_value=1,
83
+ max_value=200,
84
+ value=50
85
+ )
86
+
87
+ # -----------------------------
88
+ # 2. DATA PREPARATION
89
+ # -----------------------------
90
+ iris = load_iris()
91
+ X = iris.data # shape (150, 4)
92
+ y = iris.target.reshape(-1, 1) # shape (150, 1)
93
+
94
+ # One-hot encode target
95
+ encoder = OneHotEncoder(sparse=False)
96
+ y_encoded = encoder.fit_transform(y) # shape (150, 3)
97
+
98
+ # Split data
99
+ X_train, X_test, y_train, y_test = train_test_split(
100
+ X, y_encoded,
101
+ test_size=test_size,
102
+ random_state=42
103
  )
104
 
105
+ # Scale features
106
+ scaler = StandardScaler()
107
+ X_train = scaler.fit_transform(X_train)
108
+ X_test = scaler.transform(X_test)
109
+
110
+ # -----------------------------
111
+ # 3. BUILD MODEL FUNCTION
112
+ # -----------------------------
113
+ def build_model(lr, reg_t, reg_v, activation, n_hidden, n_neurons):
114
+ # Choose the correct regularizer
115
+ if reg_t == "None":
116
+ reg = None
117
+ elif reg_t == "L1":
118
+ reg = regularizers.l1(reg_v)
119
+ elif reg_t == "L2":
120
+ reg = regularizers.l2(reg_v)
121
+ else:
122
+ reg = regularizers.l1_l2(reg_v, reg_v)
123
+
124
+ model = keras.Sequential()
125
+ # Input layer shape = 4 (for Iris)
126
+ model.add(layers.Input(shape=(4,)))
127
+
128
+ # Add hidden layers
129
+ for _ in range(n_hidden):
130
+ model.add(
131
+ layers.Dense(
132
+ n_neurons,
133
+ activation=activation,
134
+ kernel_regularizer=reg
135
+ )
136
+ )
137
+
138
+ # Output layer (3 classes for Iris)
139
+ model.add(layers.Dense(3, activation='softmax'))
140
+
141
+ # Compile the model
142
+ model.compile(
143
+ optimizer=keras.optimizers.Adam(learning_rate=lr),
144
+ loss='categorical_crossentropy',
145
+ metrics=['accuracy']
146
+ )
147
+ return model
148
+
149
+ # -----------------------------
150
+ # 4. TRAINING
151
+ # -----------------------------
152
+ if st.button("Train"):
153
+ st.write("### Training in progress...")
154
+ model = build_model(
155
+ learning_rate,
156
+ reg_type,
157
+ reg_value,
158
+ activation_fn,
159
+ num_hidden_layers,
160
+ neurons_per_layer
161
+ )
162
+
163
+ history = model.fit(
164
+ X_train,
165
+ y_train,
166
+ epochs=epochs,
167
+ batch_size=batch_size,
168
+ validation_split=0.2,
169
+ verbose=0
170
+ )
171
+
172
+ # Plot training history
173
+ st.write("#### Accuracy")
174
+ st.line_chart({
175
+ "Train": history.history['accuracy'],
176
+ "Val": history.history['val_accuracy']
177
+ })
178
+
179
+ st.write("#### Loss")
180
+ st.line_chart({
181
+ "Train": history.history['loss'],
182
+ "Val": history.history['val_loss']
183
+ })
184
+
185
+ # Evaluate on test set
186
+ loss, acc = model.evaluate(X_test, y_test, verbose=0)
187
+ st.write(f"#### Test Loss: {loss:.4f}")
188
+ st.write(f"#### Test Accuracy: {acc:.4f}")
189
+
190
+ if _name_ == "_main_":
191
+ main()