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