newRoop commited on
Commit
dae8b49
Β·
verified Β·
1 Parent(s): 0ac8ba8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +334 -0
app.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import sys
3
+ import os
4
+
5
+ def install_tensorflow():
6
+ """
7
+ Installs TensorFlow using pip. Handles potential errors during the installation.
8
+ """
9
+ try:
10
+ print("Installing TensorFlow...")
11
+ result = subprocess.run(
12
+ [sys.executable, "-m", "pip", "install", "tensorflow"],
13
+ check=True,
14
+ stdout=subprocess.PIPE,
15
+ stderr=subprocess.PIPE,
16
+ text=True,
17
+ )
18
+ print("TensorFlow installed successfully.")
19
+ print(result.stdout)
20
+
21
+ except subprocess.CalledProcessError as e:
22
+ print(f"Error installing TensorFlow: {e}")
23
+ print(f"Error output (stderr):\n{e.stderr}")
24
+ print("Please check your pip installation and internet connection.")
25
+ print("You may need to install TensorFlow manually. Instructions can be found at:")
26
+ print("https://www.tensorflow.org/install")
27
+ sys.exit(1)
28
+
29
+ except Exception as ex:
30
+ print(f"An unexpected error occurred during TensorFlow installation: {ex}")
31
+ sys.exit(1)
32
+
33
+ def check_tensorflow_installation():
34
+ """
35
+ Checks if TensorFlow is installed and can be imported.
36
+ If not installed, it calls the installation function.
37
+ """
38
+ try:
39
+ import tensorflow as tf
40
+ print(f"TensorFlow version: {tf.__version__}")
41
+ print("TensorFlow is installed and ready to use.")
42
+ return True
43
+ except ImportError:
44
+ print("TensorFlow is not installed.")
45
+ install_tensorflow()
46
+ return False
47
+
48
+ if not check_tensorflow_installation():
49
+ check_tensorflow_installation()
50
+
51
+ import tensorflow as tf
52
+ from tensorflow.keras.layers import Input, Add, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D, MaxPooling2D, AveragePooling2D, Dropout
53
+ from tensorflow.keras.models import Model
54
+ from tensorflow.keras.initializers import GlorotUniform
55
+ from tensorflow.keras.preprocessing.image import ImageDataGenerator
56
+ from tensorflow.keras.optimizers import Adam
57
+ from tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping
58
+
59
+ # Check if running in Google Colab
60
+ try:
61
+ from google.colab import drive
62
+ IS_COLAB = True
63
+ except ImportError:
64
+ IS_COLAB = False
65
+ print("Not running in Google Colab. Using local file paths.")
66
+
67
+ # Mount Google Drive if in Colab
68
+ if IS_COLAB:
69
+ try:
70
+ drive.mount("/content/drive", timeout_ms=60000)
71
+ except Exception as e:
72
+ print(f"Error mounting drive: {e}")
73
+ print("Continuing without Google Drive...")
74
+ train_dir = 'train'
75
+ val_dir = 'val'
76
+ test_dir = 'test'
77
+ else:
78
+ # **IMPORTANT: Update these paths to the actual location of your data!**
79
+ train_dir = "/path/to/your/data/train" # Replace with your actual path
80
+ val_dir = "/path/to/your/data/val" # Replace with your actual path
81
+ test_dir = "/path/to/your/data/test" # Replace with your actual path
82
+
83
+ if not os.path.exists(train_dir):
84
+ print(f"Error: Training data directory not found at {train_dir}")
85
+ print("Please make sure the path is correct and the directory exists.")
86
+ sys.exit(1)
87
+ if not os.path.exists(val_dir):
88
+ print(f"Error: Validation data directory not found at {val_dir}")
89
+ print("Please make sure the path is correct and the directory exists.")
90
+ sys.exit(1)
91
+ if not os.path.exists(test_dir):
92
+ print(f"Error: Test data directory not found at {test_dir}")
93
+ print("Please make sure the path is correct and the directory exists.")
94
+ sys.exit(1)
95
+ print(f"Training data directory: {train_dir}")
96
+ print(f"Validation data directory: {val_dir}")
97
+ print(f"Test data directory: {test_dir}")
98
+
99
+ img_height, img_width = 224, 224
100
+ batch_size = 32
101
+ epochs = 100
102
+ num_classes = 2
103
+
104
+ # Data augmentation (optional but recommended)
105
+ train_datagen = ImageDataGenerator(
106
+ rescale=1. / 255,
107
+ rotation_range=40,
108
+ width_shift_range=0.2,
109
+ height_shift_range=0.2,
110
+ shear_range=0.2,
111
+ zoom_range=0.2,
112
+ horizontal_flip=True,
113
+ fill_mode='nearest'
114
+ )
115
+
116
+ val_datagen = ImageDataGenerator(rescale=1. / 255)
117
+ test_datagen = ImageDataGenerator(rescale=1. / 255)
118
+
119
+ # Create data generators
120
+ try:
121
+ train_generator = train_datagen.flow_from_directory(
122
+ train_dir,
123
+ target_size=(img_height, img_width),
124
+ batch_size=batch_size,
125
+ class_mode='categorical',
126
+ shuffle=True,
127
+ seed=42
128
+ )
129
+
130
+ validation_generator = val_datagen.flow_from_directory(
131
+ val_dir,
132
+ target_size=(img_height, img_width),
133
+ batch_size=batch_size,
134
+ class_mode='categorical',
135
+ shuffle=False,
136
+ seed=42
137
+ )
138
+
139
+ test_generator = test_datagen.flow_from_directory(
140
+ test_dir,
141
+ target_size=(img_height, img_width),
142
+ batch_size=batch_size,
143
+ class_mode='categorical',
144
+ shuffle=False,
145
+ seed=42
146
+ )
147
+ except Exception as e:
148
+ print(f"Error creating data generators: {e}")
149
+ print("Please check your directory paths and data.")
150
+ exit()
151
+
152
+ def identity_block(X, f, filters, stage, block):
153
+ """
154
+ Implementation of the identity block as defined in Figure 3 of the paper
155
+ Arguments:
156
+ X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)
157
+ f -- integer, specifying the shape of the middle CONV's window for the main path
158
+ filters -- python list of integers, defining the number of filters in the CONV layers of the main path
159
+ stage -- integer, used to name the layers, depending on their position in the network
160
+ block -- string/character, used to name the layers, depending on their position in the network
161
+ Returns:
162
+ X -- output tensor of shape (m, n_H, n_W, n_C)
163
+ """
164
+ # defining name basis
165
+ conv_name_base = 'conv' + str(stage) + block + '_branch'
166
+ bn_name_base = 'bn' + str(stage) + block + '_branch'
167
+
168
+ # Retrieve Filters
169
+ F1, F2, F3 = filters
170
+ # Save the input value. You'll need this later to add back to the main path.
171
+ X_shortcut = X
172
+ # First component of main path
173
+ X = Conv2D(filters=F1, kernel_size=(1, 1), strides=(1, 1), padding='valid', name=conv_name_base + '2a', kernel_initializer=GlorotUniform(seed=0))(X)
174
+ X = BatchNormalization(axis=3, name=bn_name_base + '2a')(X)
175
+ X = Activation('relu')(X)
176
+ # Second component of main path
177
+ X = Conv2D(filters=F2, kernel_size=(f, f), strides=(1, 1), padding='same', name=conv_name_base + '2b', kernel_initializer=GlorotUniform(seed=0))(X)
178
+ X = BatchNormalization(axis=3, name=bn_name_base + '2b')(X)
179
+ X = Activation('relu')(X)
180
+ # Third component of main path
181
+ X = Conv2D(filters=F3, kernel_size=(1, 1), strides=(1, 1), padding='valid', name=conv_name_base + '2c', kernel_initializer=GlorotUniform(seed=0))(X)
182
+ X = BatchNormalization(axis=3, name=bn_name_base + '2c')(X)
183
+ # Final step: Add shortcut value to main path, and pass it through a RELU activation
184
+ X = Add()([X, X_shortcut]) # X_shortcut from the beginning
185
+ X = Activation('relu')(X)
186
+ return X
187
+
188
+ def convolutional_block(X, f, filters, stage, block, s=2):
189
+ """
190
+ Implementation of the convolutional block as defined in Figure 4
191
+ Arguments:
192
+ X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)
193
+ f -- integer, specifying the shape of the middle CONV's window for the main path
194
+ filters -- python list of integers, defining the number of filters in the CONV layers of the main path
195
+ stage -- integer, used to name the layers, depending on their position in the network
196
+ block -- string/character, used to name the layers, depending on their position in the network
197
+ s -- integer, specifying the stride to be used
198
+ Returns:
199
+ X -- output tensor of shape (m, n_H, n_W, n_C)
200
+ """
201
+ # defining name basis
202
+ conv_name_base = 'conv' + str(stage) + block + '_branch'
203
+ bn_name_base = 'bn' + str(stage) + block + '_branch'
204
+ # Retrieve Filters
205
+ F1, F2, F3 = filters
206
+ # Save the input value
207
+ X_shortcut = X
208
+ # First component of main path
209
+ X = Conv2D(filters=F1, kernel_size=(1, 1), strides=(s, s), padding='valid', name=conv_name_base + '2a', kernel_initializer=GlorotUniform(seed=0))(X)
210
+ X = BatchNormalization(axis=3, name=bn_name_base + '2a')(X)
211
+ X = Activation('relu')(X)
212
+ # Second component of main path
213
+ X = Conv2D(filters=F2, kernel_size=(f, f), strides=(1, 1), padding='same', name=conv_name_base + '2b', kernel_initializer=GlorotUniform(seed=0))(X)
214
+ X = BatchNormalization(axis=3, name=bn_name_base + '2b')(X)
215
+ X = Activation('relu')(X)
216
+ # Third component of main path
217
+ X = Conv2D(filters=F3, kernel_size=(1, 1), strides=(1, 1), padding='valid', name=conv_name_base + '2c', kernel_initializer=GlorotUniform(seed=0))(X)
218
+ X = BatchNormalization(axis=3, name=bn_name_base + '2c')(X)
219
+ ##### SHORTCUT PATH ####
220
+ X_shortcut = Conv2D(filters=F3, kernel_size=(1, 1), strides=(s, s), padding='valid', name=conv_name_base + '1', kernel_initializer=GlorotUniform(seed=0))(X_shortcut)
221
+ X_shortcut = BatchNormalization(axis=3, name=bn_name_base + '1')(X_shortcut)
222
+ # Final step: Add shortcut value to main path, and pass it through a RELU activation
223
+ X = Add()([X, X_shortcut])
224
+ X = Activation('relu')(X)
225
+ return X
226
+
227
+ def ResNetCustom(input_shape=(224, 224, 3), classes=2, num_blocks_per_stage=[2, 2, 2, 2]):
228
+ """
229
+ Implementation of a custom ResNet architecture. You can specify the number of blocks per stage.
230
+ Arguments:
231
+ input_shape -- shape of the images of the dataset
232
+ classes -- integer, number of classes
233
+ num_blocks_per_stage -- a list indicating the number of identity blocks in each stage after the convolutional block
234
+ Returns:
235
+ model -- a Model() instance in Keras
236
+ """
237
+ # Define the input as a tensor with shape input_shape
238
+ X_input = Input(input_shape)
239
+ # Zero-Padding
240
+ X = ZeroPadding2D((3, 3))(X_input)
241
+ # Stage 1
242
+ X = Conv2D(64, (7, 7), strides=(2, 2), name='conv1', kernel_initializer=GlorotUniform(seed=0))(X)
243
+ X = BatchNormalization(axis=3, name='bn_conv1')(X)
244
+ X = Activation('relu')(X)
245
+ X = MaxPooling2D((3, 3), strides=(2, 2))(X)
246
+ # Stage 2
247
+ X = convolutional_block(X, f=3, filters=[64, 64, 256], stage=2, block='a', s=1)
248
+ for i in range(num_blocks_per_stage[0]):
249
+ X = identity_block(X, 3, [64, 64, 256], stage=2, block=chr(ord('b') + i)) # b, c, d...
250
+ # Stage 3
251
+ X = convolutional_block(X, f=3, filters=[128, 128, 512], stage=3, block='a', s=2)
252
+ for i in range(num_blocks_per_stage[1]):
253
+ X = identity_block(X, 3, [128, 128, 512], stage=3, block=chr(ord('b') + i))
254
+ # Stage 4
255
+ X = convolutional_block(X, f=3, filters=[256, 256, 1024], stage=4, block='a', s=2)
256
+ for i in range(num_blocks_per_stage[2]):
257
+ X = identity_block(X, 3, [256, 256, 1024], stage=4, block=chr(ord('b') + i))
258
+ # Stage 5
259
+ X = convolutional_block(X, f=3, filters=[512, 512, 2048], stage=5, block='a', s=2)
260
+ for i in range(num_blocks_per_stage[3]):
261
+ X = identity_block(X, 3, [512, 512, 2048], stage=5, block=chr(ord('b') + i))
262
+ # AVGPOOL
263
+ X = AveragePooling2D(pool_size=(2, 2), name='avg_pool')(X)
264
+ # FLATTEN
265
+ X = Flatten()(X)
266
+ # Fully connected layer
267
+ X = Dense(classes, activation='softmax', name='fc' + str(classes), kernel_initializer=GlorotUniform(seed=0))(X)
268
+ # Create model
269
+ model = Model(inputs=X_input, outputs=X, name='ResNetCustom')
270
+ return model
271
+
272
+ # Build the model
273
+ model = ResNetCustom(input_shape=(img_height, img_width, 3), classes=num_classes, num_blocks_per_stage=[1, 1, 1, 1])
274
+
275
+ # Compile the model
276
+ optimizer = Adam(learning_rate=0.001)
277
+ model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])
278
+
279
+ # Model summary
280
+ model.summary()
281
+
282
+ # Define callbacks
283
+ checkpoint = ModelCheckpoint(
284
+ filepath='best_resnet_model.keras',
285
+ monitor='val_accuracy',
286
+ verbose=1,
287
+ save_best_only=True,
288
+ mode='max'
289
+ )
290
+
291
+ reduce_lr = ReduceLROnPlateau(
292
+ monitor='val_loss',
293
+ factor=0.2,
294
+ patience=5,
295
+ verbose=1,
296
+ mode='min',
297
+ min_lr=1e-6
298
+ )
299
+
300
+ early_stopping = EarlyStopping(
301
+ monitor='val_loss',
302
+ patience=10,
303
+ restore_best_weights=True,
304
+ verbose=1
305
+ )
306
+
307
+ callbacks = [checkpoint, reduce_lr, early_stopping]
308
+
309
+ # Train the model
310
+ try:
311
+ history = model.fit(
312
+ train_generator,
313
+ steps_per_epoch=train_generator.samples // train_generator.batch_size,
314
+ epochs=epochs,
315
+ validation_data=validation_generator,
316
+ validation_steps=validation_generator.samples // validation_generator.batch_size,
317
+ callbacks=callbacks,
318
+ verbose=1
319
+ )
320
+ print("Training complete!")
321
+
322
+ # Evaluate the model on the test set
323
+ test_loss, test_accuracy = model.evaluate(test_generator, steps=test_generator.samples // test_generator.batch_size, verbose=1)
324
+ print(f"Test Loss: {test_loss:.4f}")
325
+ print(f"Test Accuracy: {test_accuracy:.4f}")
326
+
327
+ except KeyboardInterrupt:
328
+ print("\nTraining interrupted by user (Ctrl+C).")
329
+ print("Saving the model so far...")
330
+ model.save('interrupted_resnet_model.keras')
331
+ print("Model saved. You can resume training later by loading this model.")
332
+ except Exception as e:
333
+ print(f"An error occurred during training: {e}")
334
+ print("Please check your data and model configuration.")