Download resnet50_code.py from newRoop10/Periodontal_Disease: direct link, hf CLI and curl.
- Browser
- Download file 10.3 kB
-
https://huggingface.co/newRoop10/Periodontal_Disease/resolve/main/resnet50_code.py
- Command line
-
hf download hf://newRoop10/Periodontal_Disease/resnet50_code.py
-
curl -L -o resnet50_code.py https://huggingface.co/newRoop10/Periodontal_Disease/resolve/main/resnet50_code.py
10.3 kB
| # -*- 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) |