newRoop commited on
Commit
5aab96e
Β·
verified Β·
1 Parent(s): da2f552

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +243 -0
app.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tensorflow as tf
2
+ from tensorflow.keras.layers import Input, Add, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D, MaxPooling2D, AveragePooling2D
3
+ from tensorflow.keras.models import Model
4
+ from tensorflow.keras.initializers import GlorotUniform
5
+ from tensorflow.keras.preprocessing.image import ImageDataGenerator
6
+ from tensorflow.keras.optimizers import Adam
7
+ from tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping, TensorBoard
8
+ import os
9
+ from google.colab import drive
10
+
11
+ # Mount Google Drive
12
+ drive.mount("/content/drive", timeout_ms=60000)
13
+
14
+ # Define your data directories
15
+ train_dir = "/content/drive/MyDrive/Periodontal_lessDataSet/train" # Update this
16
+ val_dir = "/content/drive/MyDrive/Periodontal_lessDataSet/val" # Update this
17
+ test_dir = "/content/drive/MyDrive/Periodontal_lessDataSet/test" # Update this
18
+
19
+ # Image parameters
20
+ img_height, img_width = 224, 224 # Standard ResNet input size
21
+ batch_size = 32
22
+ epochs = 10
23
+ num_classes = 2 # Binary classification
24
+
25
+ # Data augmentation
26
+ train_datagen = ImageDataGenerator(
27
+ rescale=1./255,
28
+ rotation_range=20, # Less aggressive than 40 for medical images
29
+ width_shift_range=0.1,
30
+ height_shift_range=0.1,
31
+ shear_range=0.1,
32
+ zoom_range=0.1,
33
+ horizontal_flip=True,
34
+ vertical_flip=True, # Added if orientation doesn't matter
35
+ fill_mode='nearest'
36
+ )
37
+
38
+ # Validation/test generators (no augmentation)
39
+ val_datagen = ImageDataGenerator(rescale=1./255)
40
+ test_datagen = ImageDataGenerator(rescale=1./255)
41
+
42
+ # Data generators
43
+ train_generator = train_datagen.flow_from_directory(
44
+ train_dir,
45
+ target_size=(img_height, img_width),
46
+ batch_size=batch_size,
47
+ class_mode='categorical',
48
+ shuffle=True,
49
+ seed=42
50
+ )
51
+
52
+ validation_generator = val_datagen.flow_from_directory(
53
+ val_dir,
54
+ target_size=(img_height, img_width),
55
+ batch_size=batch_size,
56
+ class_mode='categorical',
57
+ shuffle=False,
58
+ seed=42
59
+ )
60
+
61
+ test_generator = test_datagen.flow_from_directory(
62
+ test_dir,
63
+ target_size=(img_height, img_width),
64
+ batch_size=batch_size,
65
+ class_mode='categorical',
66
+ shuffle=False,
67
+ seed=42
68
+ )
69
+
70
+ # ======================
71
+ # ResNet-50 Architecture
72
+ # ======================
73
+
74
+ def identity_block(X, f, filters, stage, block):
75
+ """
76
+ Bottleneck identity block (1x1 -> 3x3 -> 1x1)
77
+ Arguments:
78
+ X -- input tensor
79
+ f -- kernel size for middle conv layer
80
+ filters -- list of 3 integers: [F1, F2, F3]
81
+ stage -- for layer naming
82
+ block -- for layer naming
83
+ """
84
+ conv_name_base = f'res{stage}{block}_branch'
85
+ bn_name_base = f'bn{stage}{block}_branch'
86
+ F1, F2, F3 = filters
87
+
88
+ X_shortcut = X
89
+
90
+ # First component (1x1 reduce)
91
+ X = Conv2D(F1, (1, 1), strides=(1,1), padding='valid',
92
+ name=conv_name_base+'2a', kernel_initializer=GlorotUniform(seed=0))(X)
93
+ X = BatchNormalization(axis=3, name=bn_name_base+'2a')(X)
94
+ X = Activation('relu')(X)
95
+
96
+ # Second component (3x3)
97
+ X = Conv2D(F2, (f, f), strides=(1,1), padding='same',
98
+ name=conv_name_base+'2b', kernel_initializer=GlorotUniform(seed=0))(X)
99
+ X = BatchNormalization(axis=3, name=bn_name_base+'2b')(X)
100
+ X = Activation('relu')(X)
101
+
102
+ # Third component (1x1 expand)
103
+ X = Conv2D(F3, (1, 1), strides=(1,1), padding='valid',
104
+ name=conv_name_base+'2c', kernel_initializer=GlorotUniform(seed=0))(X)
105
+ X = BatchNormalization(axis=3, name=bn_name_base+'2c')(X)
106
+
107
+ # Add shortcut and activate
108
+ X = Add()([X, X_shortcut])
109
+ X = Activation('relu')(X)
110
+
111
+ return X
112
+
113
+ def convolutional_block(X, f, filters, stage, block, s=2):
114
+ """
115
+ Bottleneck convolutional block with shortcut conv
116
+ Arguments:
117
+ s -- stride for first conv layer
118
+ """
119
+ conv_name_base = f'res{stage}{block}_branch'
120
+ bn_name_base = f'bn{stage}{block}_branch'
121
+ F1, F2, F3 = filters
122
+
123
+ X_shortcut = X
124
+
125
+ # Main path
126
+ X = Conv2D(F1, (1, 1), strides=(s,s), padding='valid',
127
+ name=conv_name_base+'2a', kernel_initializer=GlorotUniform(seed=0))(X)
128
+ X = BatchNormalization(axis=3, name=bn_name_base+'2a')(X)
129
+ X = Activation('relu')(X)
130
+
131
+ X = Conv2D(F2, (f, f), strides=(1,1), padding='same',
132
+ name=conv_name_base+'2b', kernel_initializer=GlorotUniform(seed=0))(X)
133
+ X = BatchNormalization(axis=3, name=bn_name_base+'2b')(X)
134
+ X = Activation('relu')(X)
135
+
136
+ X = Conv2D(F3, (1, 1), strides=(1,1), padding='valid',
137
+ name=conv_name_base+'2c', kernel_initializer=GlorotUniform(seed=0))(X)
138
+ X = BatchNormalization(axis=3, name=bn_name_base+'2c')(X)
139
+
140
+ # Shortcut path
141
+ X_shortcut = Conv2D(F3, (1, 1), strides=(s,s), padding='valid',
142
+ name=conv_name_base+'1', kernel_initializer=GlorotUniform(seed=0))(X_shortcut)
143
+ X_shortcut = BatchNormalization(axis=3, name=bn_name_base+'1')(X_shortcut)
144
+
145
+ # Add and activate
146
+ X = Add()([X, X_shortcut])
147
+ X = Activation('relu')(X)
148
+
149
+ return X
150
+
151
+ def ResNet50(input_shape=(224, 224, 3), classes=2):
152
+ """True ResNet-50 implementation"""
153
+ X_input = Input(input_shape)
154
+
155
+ # Stage 1
156
+ X = ZeroPadding2D((3, 3))(X_input)
157
+ X = Conv2D(64, (7, 7), strides=(2, 2), name='conv1', kernel_initializer=GlorotUniform(seed=0))(X)
158
+ X = BatchNormalization(axis=3, name='bn_conv1')(X)
159
+ X = Activation('relu')(X)
160
+ X = MaxPooling2D((3, 3), strides=(2, 2))(X)
161
+
162
+ # Stage 2 (3 blocks)
163
+ X = convolutional_block(X, f=3, filters=[64, 64, 256], stage=2, block='a', s=1)
164
+ X = identity_block(X, 3, [64, 64, 256], stage=2, block='b')
165
+ X = identity_block(X, 3, [64, 64, 256], stage=2, block='c')
166
+
167
+ # Stage 3 (4 blocks)
168
+ X = convolutional_block(X, f=3, filters=[128, 128, 512], stage=3, block='a', s=2)
169
+ X = identity_block(X, 3, [128, 128, 512], stage=3, block='b')
170
+ X = identity_block(X, 3, [128, 128, 512], stage=3, block='c')
171
+ X = identity_block(X, 3, [128, 128, 512], stage=3, block='d')
172
+
173
+ # Stage 4 (6 blocks)
174
+ X = convolutional_block(X, f=3, filters=[256, 256, 1024], stage=4, block='a', s=2)
175
+ X = identity_block(X, 3, [256, 256, 1024], stage=4, block='b')
176
+ X = identity_block(X, 3, [256, 256, 1024], stage=4, block='c')
177
+ X = identity_block(X, 3, [256, 256, 1024], stage=4, block='d')
178
+ X = identity_block(X, 3, [256, 256, 1024], stage=4, block='e')
179
+ X = identity_block(X, 3, [256, 256, 1024], stage=4, block='f')
180
+
181
+ # Stage 5 (3 blocks)
182
+ X = convolutional_block(X, f=3, filters=[512, 512, 2048], stage=5, block='a', s=2)
183
+ X = identity_block(X, 3, [512, 512, 2048], stage=5, block='b')
184
+ X = identity_block(X, 3, [512, 512, 2048], stage=5, block='c')
185
+
186
+ # Final layers
187
+ X = AveragePooling2D((2, 2), name='avg_pool')(X)
188
+ X = Flatten()(X)
189
+ X = Dense(classes, activation='softmax', name='fc' + str(classes))(X)
190
+
191
+ model = Model(inputs=X_input, outputs=X, name='ResNet50')
192
+ return model
193
+
194
+ # ==============
195
+ # Model Training
196
+ # ==============
197
+
198
+ # Build model
199
+ model = ResNet50(input_shape=(img_height, img_width, 3), classes=num_classes)
200
+ model.summary()
201
+
202
+ # Compile
203
+ optimizer = Adam(learning_rate=0.001)
204
+ model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])
205
+
206
+ # Callbacks
207
+ callbacks = [
208
+ ModelCheckpoint(
209
+ 'best_resnet50_model.h5',
210
+ monitor='val_accuracy',
211
+ save_best_only=True,
212
+ mode='max'
213
+ ),
214
+ ReduceLROnPlateau(
215
+ monitor='val_loss',
216
+ factor=0.1, # More conservative than 0.2
217
+ patience=5,
218
+ verbose=1,
219
+ mode='min'
220
+ ),
221
+ EarlyStopping(
222
+ monitor='val_loss',
223
+ patience=15, # Increased for deeper networks
224
+ restore_best_weights=True
225
+ ),
226
+ TensorBoard(log_dir='./logs')
227
+ ]
228
+
229
+ # Train
230
+ history = model.fit(
231
+ train_generator,
232
+ steps_per_epoch=train_generator.samples // batch_size,
233
+ epochs=epochs,
234
+ validation_data=validation_generator,
235
+ validation_steps=validation_generator.samples // batch_size,
236
+ callbacks=callbacks,
237
+ verbose=1
238
+ )
239
+
240
+ # Evaluate
241
+ test_loss, test_acc = model.evaluate(test_generator, verbose=1)
242
+ print(f"Test Accuracy: {test_acc:.4f}")
243
+ print(f"Test Loss: {test_loss:.4f}")