Gowthamvemula commited on
Commit
519389b
·
verified ·
1 Parent(s): 21407e7

Update Home.py

Browse files
Files changed (1) hide show
  1. Home.py +37 -87
Home.py CHANGED
@@ -1,12 +1,12 @@
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
  class EpochLearningRateLogger(Callback):
7
  """
8
- A Keras Callback that logs the epoch number, learning rate,
9
- and other model details during training.
10
  """
11
  def __init__(self, model, problem_type, activation_function, regularization_type=None, regularization_rate=None):
12
  super().__init__()
@@ -17,11 +17,8 @@ class EpochLearningRateLogger(Callback):
17
  self.regularization_rate = regularization_rate
18
 
19
  def on_epoch_begin(self, epoch, logs=None):
20
- """
21
- Called at the beginning of each epoch.
22
- """
23
- optimizer = self.model.optimizer # Access the optimizer directly
24
- learning_rate = optimizer.learning_rate.numpy() # Assuming learning rate is a Tensor/Variable
25
 
26
  print(f"\nEpoch: {epoch + 1}")
27
  print(f"Learning Rate: {learning_rate}")
@@ -32,113 +29,72 @@ class EpochLearningRateLogger(Callback):
32
  print(f"Regularization Type: {self.regularization_type}")
33
  print(f"Regularization Rate: {self.regularization_rate}")
34
 
35
-
36
-
37
  def create_model(input_shape, problem_type, activation_function='relu', regularization_type=None, regularization_rate=0.01, num_classes=None):
38
  """
39
- Creates a TensorFlow Keras model based on specified parameters.
40
-
41
- Args:
42
- input_shape: Shape of the input data (e.g., (28, 28, 1) for MNIST).
43
- problem_type: "classification" or "regression".
44
- activation_function: Activation function to use (e.g., 'relu', 'sigmoid', 'tanh').
45
- regularization_type: 'l1' or 'l2', or None for no regularization.
46
- regularization_rate: The regularization strength (lambda).
47
- num_classes: Number of classes for classification problems. Required if problem_type is "classification".
48
- Ignored for "regression".
49
-
50
- Returns:
51
- A compiled Keras model.
52
  """
53
-
54
  if problem_type == "classification" and num_classes is None:
55
  raise ValueError("num_classes must be specified for classification problems.")
56
 
57
-
58
  model = Sequential()
59
- # Input Layer
60
  model.add(layers.Input(shape=input_shape))
61
- model.add(layers.Flatten()) # Flatten image to 1D
62
 
63
-
64
- # Hidden layers with regularization
65
  kernel_regularizer = None
66
  if regularization_type == 'l1':
67
  kernel_regularizer = regularizers.L1(regularization_rate)
68
  elif regularization_type == 'l2':
69
  kernel_regularizer = regularizers.L2(regularization_rate)
70
 
71
-
72
- model.add(layers.Dense(128, activation=activation_function, kernel_regularizer=kernel_regularizer)) # Example Hidden Layer
73
- model.add(layers.Dense(64, activation=activation_function, kernel_regularizer=kernel_regularizer)) # Another Example
74
-
75
 
76
  # Output Layer
77
  if problem_type == "classification":
78
- model.add(layers.Dense(num_classes, activation='softmax')) # Softmax for multi-class classification
79
  loss_function = losses.CategoricalCrossentropy()
80
- metrics_list = ['accuracy'] # Common classification metric
81
  elif problem_type == "regression":
82
- model.add(layers.Dense(1)) # Linear activation for regression
83
  loss_function = losses.MeanSquaredError()
84
- metrics_list = ['mean_absolute_error'] # Common regression metric
85
  else:
86
  raise ValueError("Invalid problem_type. Must be 'classification' or 'regression'.")
87
 
88
-
89
- # Optimizer
90
- optimizer = optimizers.Adam() # You can configure the learning rate here if desired.
91
-
92
- model.compile(optimizer=optimizer, loss=loss_function, metrics=metrics_list)
93
  return model
94
 
95
-
96
  if __name__ == '__main__':
97
- # Example usage:
98
- input_shape = (28, 28, 1) # Example: MNIST image size
99
  num_classes = 10 # Example: MNIST has 10 classes
100
-
101
- # Define model parameters
102
- problem_type = "classification" # Or "regression"
103
  activation_function = 'relu'
104
- regularization_type = 'l2' # 'l1', 'l2', or None
105
  regularization_rate = 0.001
106
- learning_rate = 0.001
107
-
108
- # Create the model
109
- model = create_model(
110
- input_shape=input_shape,
111
- problem_type=problem_type,
112
- activation_function=activation_function,
113
- regularization_type=regularization_type,
114
- regularization_rate=regularization_rate,
115
- num_classes=num_classes
116
- )
117
 
118
- # Print model summary
 
119
  model.summary()
120
 
121
-
122
-
123
- # Load and preprocess data (Example: MNIST)
124
  (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
125
- x_train = x_train.astype('float32') / 255.0
126
- x_test = x_test.astype('float32') / 255.0
127
-
128
- # Reshape images to include the channel dimension
129
- x_train = x_train.reshape((-1, 28, 28, 1))
130
- x_test = x_test.reshape((-1, 28, 28, 1))
131
-
132
 
 
 
133
 
 
134
  if problem_type == "classification":
135
  y_train = tf.keras.utils.to_categorical(y_train, num_classes)
136
  y_test = tf.keras.utils.to_categorical(y_test, num_classes)
137
 
138
-
139
-
140
-
141
- # Create the custom callback
142
  epoch_lr_logger = EpochLearningRateLogger(
143
  model=model,
144
  problem_type=problem_type,
@@ -147,19 +103,13 @@ if __name__ == '__main__':
147
  regularization_rate=regularization_rate
148
  )
149
 
150
-
151
-
152
- # Train the model
153
- epochs = 5
154
- batch_size = 32
155
-
156
  history = model.fit(
157
- x_train,
158
- y_train,
159
- epochs=epochs,
160
- batch_size=batch_size,
161
  validation_data=(x_test, y_test),
162
- callbacks=[epoch_lr_logger] # Pass the callback to the fit method
163
  )
164
 
165
- print("\nTraining completed.")
 
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__()
 
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}")
 
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,
 
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.")