newRoop commited on
Commit
1690c98
Β·
verified Β·
1 Parent(s): 25d1474

Upload app.py

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