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

Upload resnet50_code.py

Browse files
Files changed (1) hide show
  1. resnet50_code.py +300 -0
resnet50_code.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """ResNet50 Code
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1QlSwlono_bMfdUiJYNVkXAYO0yTw442A
8
+ """
9
+
10
+ import keras
11
+ from keras.layers import Dense, GlobalAveragePooling2D, Dropout, BatchNormalization
12
+ from keras.optimizers import Adam
13
+ from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping
14
+ from tensorflow.keras.preprocessing.image import ImageDataGenerator
15
+ from keras.models import Model
16
+ from tensorflow.keras.applications import ResNet50 # Changed import to ResNet50
17
+ import numpy as np
18
+ import os
19
+ from google.colab import drive
20
+ import tensorflow as tf
21
+ from tensorflow.keras.preprocessing import image
22
+ from tensorflow.keras.models import load_model
23
+ from tensorflow.keras.utils import to_categorical # Needed for manual label assignment
24
+
25
+
26
+
27
+ # Mount Google Drive
28
+ drive.mount("/content/drive", timeout_ms=60000)
29
+
30
+ # Print TensorFlow and Keras versions
31
+ print("TensorFlow version:", tf.__version__)
32
+ print("Keras version:", keras.__version__)
33
+
34
+ # Define your data directories
35
+ train_dir = "/content/drive/MyDrive/Periodontal/train"
36
+ val_dir = "/content/drive/MyDrive/Periodontal/val"
37
+ test_dir = "/content/drive/MyDrive/Periodontal/test"
38
+ img_height, img_width = 64, 64
39
+ batch_size = 32
40
+ epochs = 100
41
+ data_augmentation = True
42
+ num_classes = 2 # Changed to 2 for binary classification (normal, inflamed)
43
+ input_shape = (img_height, img_width, 3)
44
+
45
+ # Data augmentation
46
+ train_datagen = ImageDataGenerator(
47
+ rescale=1. / 255,
48
+ rotation_range=40,
49
+ width_shift_range=0.3,
50
+ height_shift_range=0.3,
51
+ shear_range=0.2,
52
+ zoom_range=0.2,
53
+ horizontal_flip=True,
54
+ vertical_flip=True,
55
+ fill_mode='nearest'
56
+ )
57
+ val_datagen = ImageDataGenerator(rescale=1. / 255)
58
+ test_datagen = ImageDataGenerator(rescale=1. / 255)
59
+
60
+
61
+ def create_generators(train_dir, val_dir, test_dir, target_size, batch_size):
62
+ """
63
+ Creates training, validation, and testing data generators for binary classification.
64
+
65
+ Args:
66
+ train_dir (str): Path to the training data directory.
67
+ val_dir (str): Path to the validation data directory.
68
+ test_dir (str): Path to the testing data directory.
69
+ target_size (tuple): The target image size (height, width).
70
+ batch_size (int): The batch size.
71
+
72
+ Returns:
73
+ tuple: (train_generator, validation_generator, test_generator, class_labels)
74
+ - train_generator: Training data generator.
75
+ - validation_generator: Validation data generator.
76
+ - test_generator: Testing data generator.
77
+ - class_labels: A dictionary mapping numerical labels to disease states.
78
+ """
79
+ train_generator = train_datagen.flow_from_directory(
80
+ train_dir,
81
+ target_size=target_size,
82
+ batch_size=batch_size,
83
+ class_mode='binary', # Changed to 'binary'
84
+ classes=['normal', 'inflammation'], # Explicitly define classes
85
+ shuffle=True,
86
+ )
87
+
88
+ validation_generator = val_datagen.flow_from_directory(
89
+ val_dir,
90
+ target_size=target_size,
91
+ batch_size=batch_size,
92
+ class_mode='binary', # Changed to 'binary'
93
+ classes=['normal', 'inflammation'], # Explicitly define classes
94
+ shuffle=False,
95
+ )
96
+
97
+ test_generator = test_datagen.flow_from_directory(
98
+ test_dir,
99
+ target_size=target_size,
100
+ batch_size=batch_size,
101
+ class_mode='binary', # Changed to 'binary'
102
+ classes=['normal', 'inflammation'], # Explicitly define classes
103
+ shuffle=False,
104
+ )
105
+
106
+ class_labels = {0: 'normal', 1: 'inflamed'} # Updated class labels
107
+ return train_generator, validation_generator, test_generator, class_labels
108
+
109
+
110
+ # Create the data generators
111
+ train_generator, validation_generator, test_generator, class_labels = create_generators(
112
+ train_dir, val_dir, test_dir, (img_height, img_width), batch_size
113
+ )
114
+
115
+ sample_train_batch = next(train_generator)
116
+ print(
117
+ "Shape of one train batch (data, labels):",
118
+ sample_train_batch[0].shape,
119
+ sample_train_batch[1].shape,
120
+ )
121
+ print("Label shape from train generator:", sample_train_batch[1].shape)
122
+ print("Data type of labels from train generator:", sample_train_batch[1].dtype)
123
+ print(f"First 5 labels: {sample_train_batch[1][:5]}") # Print the first 5 labels
124
+
125
+
126
+
127
+ # Load the pre-trained ResNet50 model
128
+ base_model = ResNet50(weights='imagenet', include_top=False, input_shape=input_shape) # Changed model
129
+
130
+
131
+
132
+ for layer in base_model.layers:
133
+ layer.trainable = False
134
+ from tensorflow.keras.regularizers import l2
135
+
136
+ x = base_model.output
137
+ x = GlobalAveragePooling2D()(x)
138
+ x = Dropout(0.5)(x)
139
+ x = Dense(256, activation='relu', kernel_regularizer=l2(0.001))(x)
140
+ x = BatchNormalization()(x)
141
+ x = Dropout(0.5)(x)
142
+ predictions = Dense(1, activation='sigmoid')(x) # Changed activation to 'sigmoid' for binary # CHANGED LINE
143
+ model = Model(inputs=base_model.input, outputs=predictions)
144
+
145
+ base_model.trainable = True
146
+ fine_tune_at = 100
147
+ for layer in base_model.layers[:fine_tune_at]:
148
+ layer.trainable = False
149
+
150
+ model.compile(
151
+ optimizer=Adam(learning_rate=1e-4),
152
+ loss='binary_crossentropy',
153
+ metrics=['accuracy'],
154
+ )
155
+ model.summary()
156
+
157
+ model_type = 'ResNet50_binary' # Updated model name # CHANGED LINE
158
+ save_dir = os.path.join(os.getcwd(), 'saved_models')
159
+ model_name = 'periodontol_%s_model.{epoch:03d}.keras' % model_type
160
+ if not os.path.isdir(save_dir):
161
+ os.makedirs(save_dir)
162
+ filepath = os.path.join(save_dir, model_name)
163
+
164
+ checkpoint = ModelCheckpoint(
165
+ filepath=filepath,
166
+ monitor='val_accuracy',
167
+ verbose=1,
168
+ save_best_only=True,
169
+ )
170
+ lr_reducer = ReduceLROnPlateau(
171
+ factor=np.sqrt(0.1),
172
+ cooldown=0,
173
+ patience=10,
174
+ min_lr=1e-6,
175
+ )
176
+ early_stopping = EarlyStopping(
177
+ monitor='val_loss', patience=20, restore_best_weights=True
178
+ )
179
+ callbacks = [checkpoint, lr_reducer, early_stopping]
180
+
181
+
182
+ def train_model(model, train_generator, validation_generator, epochs, data_augmentation, callbacks):
183
+ """
184
+ Trains the model with or without data augmentation.
185
+
186
+ Args:
187
+ model (keras.Model): The Keras model to train.
188
+ train_generator (ImageDataGenerator): The training data generator.
189
+ validation_generator (ImageDataGenerator): The validation data generator.
190
+ epochs (int): The number of epochs to train for.
191
+ data_augmentation (bool): Whether to use data augmentation.
192
+ callbacks (list): List of Keras callbacks.
193
+ """
194
+ print("train_generator.class_indices:", train_generator.class_indices)
195
+ if not data_augmentation:
196
+ print('Not using data augmentation.')
197
+ model.fit(
198
+ train_generator,
199
+ steps_per_epoch=train_generator.samples // train_generator.batch_size,
200
+ epochs=epochs,
201
+ validation_data=validation_generator,
202
+ validation_steps=validation_generator.samples // validation_generator.batch_size,
203
+ shuffle=True,
204
+ verbose=1,
205
+ callbacks=callbacks,
206
+ )
207
+ else:
208
+ print('Using real-time data augmentation.')
209
+ model.fit(
210
+ train_generator,
211
+ steps_per_epoch=train_generator.samples // train_generator.batch_size,
212
+ epochs=epochs,
213
+ validation_data=validation_generator,
214
+ validation_steps=validation_generator.samples // validation_generator.batch_size,
215
+ verbose=1,
216
+ callbacks=callbacks,
217
+ )
218
+ print("Training complete.")
219
+
220
+
221
+
222
+ # Train the model
223
+ train_model(model, train_generator, validation_generator, epochs, data_augmentation, callbacks)
224
+
225
+ print("Training complete. Trained model saved to:", save_dir)
226
+
227
+ from tensorflow.keras.models import load_model
228
+
229
+ model_files = [
230
+ f for f in os.listdir('saved_models') if f.startswith('periodontol_ResNet50_binary') and f.endswith('.keras') # Changed to ResNet50
231
+ ]
232
+
233
+ if model_files:
234
+ best_model_path = os.path.join('saved_models', sorted(model_files)[-1])
235
+ loaded_model = load_model(best_model_path)
236
+ print(f"Loaded model from: {best_model_path}")
237
+ else:
238
+ print("No model files found in the 'saved_models' directory.")
239
+ exit()
240
+
241
+
242
+
243
+ def predict_severity_level(img_path, model, class_labels, target_size=(64, 64)):
244
+ """
245
+ Predicts whether the image is 'normal' or 'inflamed'.
246
+
247
+ Args:
248
+ img_path (str): Path to the image file.
249
+ model (keras.Model): Loaded Keras model.
250
+ class_labels (dict): Dictionary mapping numerical labels to disease states.
251
+ target_size (tuple): The target image size (height, width).
252
+
253
+ Returns:
254
+ str: The predicted class ('normal' or 'inflamed').
255
+ """
256
+ img = image.load_img(img_path, target_size=target_size)
257
+ img_array = image.img_to_array(img)
258
+ img_array = np.expand_dims(img_array, axis=0)
259
+ img_array = img_array / 255.0
260
+ predictions = model.predict(img_array)
261
+ if predictions[0] > 0.5:
262
+ predicted_class = class_labels[1] # 'inflamed'
263
+ else:
264
+ predicted_class = class_labels[0] # 'normal'
265
+ return predicted_class
266
+
267
+
268
+
269
+ # Example
270
+ image_to_predict = "/content/drive/MyDrive/Periodontal/test/inflammation/(6).jpg" # Replace with an actual path
271
+ severity = predict_severity_level(image_to_predict, loaded_model, class_labels)
272
+ print(f"Predicted class: {severity}")
273
+
274
+
275
+
276
+ def evaluate_loaded_model(model, test_generator, class_labels):
277
+ """Evaluates the loaded model on the test data and prints the results.
278
+
279
+ Args:
280
+ model: The loaded Keras model.
281
+ test_generator: The test data generator.
282
+ class_labels (dict): Dictionary mapping numerical labels to disease states.
283
+ """
284
+ loss, accuracy = model.evaluate(test_generator, steps=test_generator.samples // test_generator.batch_size)
285
+ print(f"Test Loss: {loss:.4f}")
286
+ print(f"Test Accuracy: {accuracy:.4f}")
287
+
288
+ predictions = model.predict(test_generator, steps=test_generator.samples // test_generator.batch_size)
289
+ predicted_classes = (predictions > 0.5).astype(int).flatten()
290
+ true_classes = test_generator.classes
291
+ class_names = list(class_labels.values())
292
+
293
+ from sklearn.metrics import classification_report
294
+
295
+ print(classification_report(true_classes, predicted_classes, target_names=class_names, zero_division=0))
296
+
297
+
298
+
299
+ # Evaluate the loaded model
300
+ evaluate_loaded_model(loaded_model, test_generator, class_labels)