Upload 6 files
Browse files- CNN/CNN.ipynb +0 -0
- CNN/CNN.py +118 -0
- DenseNet/DenseNet.ipynb +0 -0
- DenseNet/DenseNet.py +606 -0
- ResNet/ResNet.ipynb +0 -0
- ResNet/ResNet.py +155 -0
CNN/CNN.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
CNN/CNN.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""Untitled20.ipynb
|
| 3 |
+
|
| 4 |
+
Automatically generated by Colaboratory.
|
| 5 |
+
|
| 6 |
+
Original file is located at
|
| 7 |
+
https://colab.research.google.com/drive/1O_tHcmidNGKAgxAiG7Su44auJSRFR1xA
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import tensorflow as tf
|
| 11 |
+
from tensorflow.keras.models import Sequential
|
| 12 |
+
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
|
| 13 |
+
from tensorflow.keras.preprocessing.image import ImageDataGenerator
|
| 14 |
+
|
| 15 |
+
image_size = (128, 128)
|
| 16 |
+
batch_size = 32
|
| 17 |
+
train_datagen = ImageDataGenerator(
|
| 18 |
+
rescale=1./255,
|
| 19 |
+
shear_range=0.2,
|
| 20 |
+
zoom_range=0.2,
|
| 21 |
+
horizontal_flip=True
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
test_datagen = ImageDataGenerator(rescale=1./255)
|
| 25 |
+
|
| 26 |
+
train_generator = train_datagen.flow_from_directory(
|
| 27 |
+
'/content/drive/MyDrive/training',
|
| 28 |
+
target_size=image_size,
|
| 29 |
+
batch_size=batch_size,
|
| 30 |
+
class_mode='binary'
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
test_generator = test_datagen.flow_from_directory(
|
| 34 |
+
'/content/drive/MyDrive/testing',
|
| 35 |
+
target_size=image_size,
|
| 36 |
+
batch_size=batch_size,
|
| 37 |
+
class_mode='binary'
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
from tensorflow.keras.models import Sequential
|
| 41 |
+
|
| 42 |
+
model = Sequential()
|
| 43 |
+
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(image_size[0], image_size[1], 3)))
|
| 44 |
+
model.add(MaxPooling2D(pool_size=(2, 2)))
|
| 45 |
+
model.add(Conv2D(64, (3, 3), activation='relu'))
|
| 46 |
+
model.add(MaxPooling2D(pool_size=(2, 2)))
|
| 47 |
+
model.add(Conv2D(128, (3, 3), activation='relu'))
|
| 48 |
+
model.add(MaxPooling2D(pool_size=(2, 2)))
|
| 49 |
+
model.add(Flatten())
|
| 50 |
+
model.add(Dense(128, activation='relu'))
|
| 51 |
+
model.add(Dropout(0.5))
|
| 52 |
+
model.add(Dense(1, activation='sigmoid'))
|
| 53 |
+
|
| 54 |
+
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
|
| 55 |
+
model.fit(train_generator, epochs=10, validation_data=test_generator)
|
| 56 |
+
evaluation = model.evaluate(test_generator)
|
| 57 |
+
print(f"Test Accuracy: {evaluation[1] * 100:.2f}%")
|
| 58 |
+
|
| 59 |
+
predictions = model.predict(test_generator)
|
| 60 |
+
predicted_labels = (predictions > 0.5).astype(int)
|
| 61 |
+
|
| 62 |
+
from sklearn.metrics import confusion_matrix, classification_report
|
| 63 |
+
true_labels = test_generator.classes
|
| 64 |
+
conf_matrix = confusion_matrix(true_labels, predicted_labels)
|
| 65 |
+
print("Confusion Matrix:")
|
| 66 |
+
print(conf_matrix)
|
| 67 |
+
class_report = classification_report(true_labels, predicted_labels, target_names=['not_fractured', 'fractured'])
|
| 68 |
+
print("Classification Report:")
|
| 69 |
+
print(class_report)
|
| 70 |
+
|
| 71 |
+
import matplotlib.pyplot as plt
|
| 72 |
+
import random
|
| 73 |
+
test_images, true_labels = next(test_generator)
|
| 74 |
+
predicted_labels = (model.predict(test_images) > 0.5).astype(int)
|
| 75 |
+
plt.figure(figsize=(12, 8))
|
| 76 |
+
for i in range(10):
|
| 77 |
+
plt.subplot(2, 5, i+1)
|
| 78 |
+
plt.imshow(test_images[i])
|
| 79 |
+
plt.title(f"True: {true_labels[i]}, Predicted: {predicted_labels[i]}")
|
| 80 |
+
plt.axis('off')
|
| 81 |
+
plt.show()
|
| 82 |
+
|
| 83 |
+
import cv2
|
| 84 |
+
|
| 85 |
+
image = cv2.imread('/content/drive/MyDrive/testing/fractured/1-rotated1-rotated1-rotated2.jpg')
|
| 86 |
+
|
| 87 |
+
plt.imshow(image)
|
| 88 |
+
|
| 89 |
+
image.shape
|
| 90 |
+
|
| 91 |
+
image = cv2.resize(image,(256,256))
|
| 92 |
+
|
| 93 |
+
test_input = image.reshape((1,256,256,3))
|
| 94 |
+
|
| 95 |
+
image.shape
|
| 96 |
+
|
| 97 |
+
plt.imshow(image)
|
| 98 |
+
|
| 99 |
+
test_input = image.reshape((1,256,256,3))
|
| 100 |
+
|
| 101 |
+
!pip install keras
|
| 102 |
+
import keras
|
| 103 |
+
model = keras.Sequential([
|
| 104 |
+
keras.layers.Dense(128, activation="relu"),
|
| 105 |
+
keras.layers.Dense(64, activation="relu"),
|
| 106 |
+
keras.layers.Dense(10, activation="softmax")
|
| 107 |
+
])
|
| 108 |
+
|
| 109 |
+
!ls -l model
|
| 110 |
+
|
| 111 |
+
!stat model
|
| 112 |
+
|
| 113 |
+
!file model
|
| 114 |
+
|
| 115 |
+
!pip show tensorflow
|
| 116 |
+
|
| 117 |
+
model.predict(test_input)
|
| 118 |
+
|
DenseNet/DenseNet.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
DenseNet/DenseNet.py
ADDED
|
@@ -0,0 +1,606 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""DenseNet.ipynb
|
| 3 |
+
|
| 4 |
+
Automatically generated by Colaboratory.
|
| 5 |
+
|
| 6 |
+
Original file is located at
|
| 7 |
+
https://colab.research.google.com/drive/1puXj_yhdhVZAi2D2P1mpDlDvccwU_63N
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import tensorflow as tf
|
| 11 |
+
from tensorflow.keras import Input
|
| 12 |
+
from tensorflow.keras.applications.densenet import DenseNet121, DenseNet169, DenseNet201
|
| 13 |
+
from tensorflow.keras.applications import MobileNetV3Small
|
| 14 |
+
from tensorflow.keras.optimizers import Adam
|
| 15 |
+
from tensorflow.keras.models import Sequential, Model
|
| 16 |
+
from tensorflow.keras.callbacks import ModelCheckpoint
|
| 17 |
+
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D
|
| 18 |
+
from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Dense, Flatten, Dropout
|
| 19 |
+
from tensorflow.keras.preprocessing.image import ImageDataGenerator
|
| 20 |
+
from sklearn.model_selection import train_test_split
|
| 21 |
+
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score, precision_score, recall_score, f1_score, log_loss, jaccard_score
|
| 22 |
+
import numpy as np
|
| 23 |
+
import os
|
| 24 |
+
from PIL import Image
|
| 25 |
+
from shutil import copyfile
|
| 26 |
+
import pandas as pd
|
| 27 |
+
import seaborn as sns
|
| 28 |
+
import matplotlib.pyplot as plt
|
| 29 |
+
|
| 30 |
+
from google.colab import drive
|
| 31 |
+
drive.mount('/content/drive')
|
| 32 |
+
|
| 33 |
+
train_data_dir = '/content/drive/MyDrive/BoneFractureDataset/training'
|
| 34 |
+
test_data_dir = '/content/drive/MyDrive/BoneFractureDataset/training'
|
| 35 |
+
validation_data_dir = '/content/drive/MyDrive/BoneFractureDataset/training'
|
| 36 |
+
IMG_WIDTH, IMG_HEIGHT = 299, 299
|
| 37 |
+
input_shape = (IMG_WIDTH, IMG_HEIGHT, 3)
|
| 38 |
+
|
| 39 |
+
train_datagen = ImageDataGenerator(rescale=1./255)
|
| 40 |
+
test_datagen = ImageDataGenerator(rescale=1./255)
|
| 41 |
+
validation_datagen = ImageDataGenerator(rescale=1./255)
|
| 42 |
+
|
| 43 |
+
train_datagen_augmented = ImageDataGenerator(
|
| 44 |
+
rescale=1./255,
|
| 45 |
+
rotation_range=20,
|
| 46 |
+
width_shift_range=0.2,
|
| 47 |
+
height_shift_range=0.2,
|
| 48 |
+
shear_range=0.2,
|
| 49 |
+
zoom_range=0.2,
|
| 50 |
+
horizontal_flip=True,
|
| 51 |
+
vertical_flip=False,
|
| 52 |
+
fill_mode='nearest'
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
train_generator = train_datagen_augmented.flow_from_directory(train_data_dir, target_size=(IMG_WIDTH, IMG_HEIGHT), batch_size=10, class_mode='categorical')
|
| 56 |
+
|
| 57 |
+
test_datagen_augmented = ImageDataGenerator(
|
| 58 |
+
rescale=1./255,
|
| 59 |
+
rotation_range=20,
|
| 60 |
+
width_shift_range=0.2,
|
| 61 |
+
height_shift_range=0.2,
|
| 62 |
+
shear_range=0.2,
|
| 63 |
+
zoom_range=0.2,
|
| 64 |
+
horizontal_flip=True,
|
| 65 |
+
vertical_flip=False,
|
| 66 |
+
fill_mode='nearest'
|
| 67 |
+
)
|
| 68 |
+
test_generator = test_datagen.flow_from_directory(test_data_dir, target_size=(IMG_WIDTH, IMG_HEIGHT), batch_size=8, class_mode='categorical', shuffle=False)
|
| 69 |
+
|
| 70 |
+
validation_datagen_augmented = ImageDataGenerator(
|
| 71 |
+
rescale=1./255,
|
| 72 |
+
rotation_range=20,
|
| 73 |
+
width_shift_range=0.2,
|
| 74 |
+
height_shift_range=0.2,
|
| 75 |
+
shear_range=0.2,
|
| 76 |
+
zoom_range=0.2,
|
| 77 |
+
horizontal_flip=True,
|
| 78 |
+
vertical_flip=False,
|
| 79 |
+
fill_mode='nearest'
|
| 80 |
+
)
|
| 81 |
+
validation_generator = validation_datagen.flow_from_directory(validation_data_dir, target_size=(IMG_WIDTH, IMG_HEIGHT), batch_size=8, class_mode='categorical', shuffle=True)
|
| 82 |
+
|
| 83 |
+
class_indices = train_generator.class_indices
|
| 84 |
+
print(class_indices)
|
| 85 |
+
|
| 86 |
+
classes = os.listdir(train_data_dir)
|
| 87 |
+
for class_name in classes:
|
| 88 |
+
class_path = os.path.join(train_data_dir, class_name)
|
| 89 |
+
num_images = len(os.listdir(class_path))
|
| 90 |
+
print(f"Class: {class_name}, Number of images: {num_images}")
|
| 91 |
+
|
| 92 |
+
batch = train_generator.next()
|
| 93 |
+
for i in range(len(batch[0])):
|
| 94 |
+
img = batch[0][i]
|
| 95 |
+
label = batch[1][i]
|
| 96 |
+
height, width, channels = img.shape
|
| 97 |
+
print(f"Image {i+1} - Shape: {width}x{height}x{channels}, Label: {label}")
|
| 98 |
+
|
| 99 |
+
classes = os.listdir(test_data_dir)
|
| 100 |
+
for class_name in classes:
|
| 101 |
+
class_path = os.path.join(test_data_dir, class_name)
|
| 102 |
+
num_images = len(os.listdir(class_path))
|
| 103 |
+
print(f"Class: {class_name}, Number of images: {num_images}")
|
| 104 |
+
|
| 105 |
+
batch = test_generator.next()
|
| 106 |
+
for i in range(len(batch[0])):
|
| 107 |
+
img = batch[0][i]
|
| 108 |
+
label = batch[1][i]
|
| 109 |
+
height, width, channels = img.shape
|
| 110 |
+
print(f"Image {i+1} - Shape: {width}x{height}x{channels}, Label: {label}")
|
| 111 |
+
|
| 112 |
+
classes = os.listdir(validation_data_dir)
|
| 113 |
+
for class_name in classes:
|
| 114 |
+
class_path = os.path.join(validation_data_dir, class_name)
|
| 115 |
+
num_images = len(os.listdir(class_path))
|
| 116 |
+
print(f"Class: {class_name}, Number of images: {num_images}")
|
| 117 |
+
|
| 118 |
+
batch = validation_generator.next()
|
| 119 |
+
for i in range(len(batch[0])):
|
| 120 |
+
img = batch[0][i]
|
| 121 |
+
label = batch[1][i]
|
| 122 |
+
height, width, channels = img.shape
|
| 123 |
+
print(f"Image {i+1} - Shape: {width}x{height}x{channels}, Label: {label}")
|
| 124 |
+
|
| 125 |
+
print("GPU is", "available" if tf.config.list_physical_devices('GPU') else "NOT available")
|
| 126 |
+
if tf.config.list_physical_devices('GPU'):
|
| 127 |
+
tf.config.experimental.set_memory_growth(tf.config.list_physical_devices('GPU')[0], True)
|
| 128 |
+
print("GPU device configured")
|
| 129 |
+
else:
|
| 130 |
+
print("No GPU device found")
|
| 131 |
+
|
| 132 |
+
from tensorflow.keras.callbacks import ModelCheckpoint
|
| 133 |
+
model_dir = '/kaggle/working/Checkpoints_densenet201'
|
| 134 |
+
if not os.path.exists(model_dir):
|
| 135 |
+
os.makedirs(model_dir)
|
| 136 |
+
checkpoint_path = model_dir + '/cp.ckpt'
|
| 137 |
+
checkpoint_dir = os.path.dirname(checkpoint_path)
|
| 138 |
+
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path, save_weights_only=True, save_best_only=True, monitor="val_accuracy", mode="max", verbose=1)
|
| 139 |
+
|
| 140 |
+
checkpoint_path
|
| 141 |
+
|
| 142 |
+
from tensorflow.keras import models, layers, optimizers
|
| 143 |
+
|
| 144 |
+
def create_model(summary=True):
|
| 145 |
+
new_input = Input(shape=(IMG_WIDTH, IMG_HEIGHT, 3))
|
| 146 |
+
base_model = DenseNet201(weights='imagenet', include_top=False, input_tensor=new_input)
|
| 147 |
+
flat1 = Flatten()(base_model.layers[-1].output)
|
| 148 |
+
output = Dense(2, activation='softmax')(flat1)
|
| 149 |
+
model = Model(inputs=base_model.inputs, outputs=output)
|
| 150 |
+
model.compile(optimizer=Adam(learning_rate=0.001), loss='binary_crossentropy', metrics=['accuracy'])
|
| 151 |
+
if summary:
|
| 152 |
+
print(model.summary())
|
| 153 |
+
return model
|
| 154 |
+
|
| 155 |
+
model = create_model()
|
| 156 |
+
|
| 157 |
+
history = model.fit(train_generator, steps_per_epoch=20, epochs=20, validation_data=validation_generator, validation_steps=25, callbacks=[cp_callback])
|
| 158 |
+
evaluation = model.evaluate(train_generator)
|
| 159 |
+
print(f"Test Accuracy: {evaluation[1] * 100:.2f}%")
|
| 160 |
+
|
| 161 |
+
initial_epoch = 0
|
| 162 |
+
saved_history = {
|
| 163 |
+
'loss': history.history['loss'],
|
| 164 |
+
'accuracy': history.history['accuracy'],
|
| 165 |
+
'val_loss': history.history['val_loss'],
|
| 166 |
+
'val_accuracy': history.history['val_accuracy'],
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
np.save("/kaggle/working/saved_D201history.npy", saved_history)
|
| 170 |
+
|
| 171 |
+
latest_checkpoint = tf.train.latest_checkpoint(checkpoint_dir)
|
| 172 |
+
print(latest_checkpoint)
|
| 173 |
+
if latest_checkpoint is not None:
|
| 174 |
+
loaded_model = create_model(summary=True)
|
| 175 |
+
status = loaded_model.load_weights(latest_checkpoint)
|
| 176 |
+
status.expect_partial()
|
| 177 |
+
else:
|
| 178 |
+
print("No checkpoint file found in the specified directory.")
|
| 179 |
+
|
| 180 |
+
previous_history = np.load("/kaggle/working/saved_D201history.npy", allow_pickle=True).item()
|
| 181 |
+
initial_epoch = len(previous_history['loss'])
|
| 182 |
+
print(initial_epoch)
|
| 183 |
+
|
| 184 |
+
loaded_model.compile(optimizer=Adam(learning_rate=1e-5), loss=tf.keras.losses.BinaryCrossentropy(), metrics=['accuracy'])
|
| 185 |
+
new_history = loaded_model.fit(
|
| 186 |
+
train_generator,
|
| 187 |
+
steps_per_epoch=20,
|
| 188 |
+
epochs=20,
|
| 189 |
+
initial_epoch=initial_epoch,
|
| 190 |
+
validation_data=validation_generator,
|
| 191 |
+
validation_steps=30,
|
| 192 |
+
callbacks=[cp_callback]
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
import matplotlib.pyplot as plt
|
| 196 |
+
from matplotlib.lines import Line2D
|
| 197 |
+
from matplotlib.legend_handler import HandlerLine2D
|
| 198 |
+
import numpy as np
|
| 199 |
+
|
| 200 |
+
plt.figure(figsize=(10, 6))
|
| 201 |
+
train_loss, = plt.plot(previous_history['loss'], label='Train Loss', color='blue')
|
| 202 |
+
val_loss, = plt.plot(previous_history['val_loss'], label='Validation Loss', color='orange')
|
| 203 |
+
train_accuracy, = plt.plot(previous_history['accuracy'], label='Train Accuracy', color='green')
|
| 204 |
+
val_accuracy, = plt.plot(previous_history['val_accuracy'], label='Validation Accuracy', color='red')
|
| 205 |
+
plt.title('Model Performance during Training', fontdict={'family': 'Serif', 'weight': 'bold', 'size': 12},pad=10)
|
| 206 |
+
plt.xlabel('No. of Epochs', fontdict={'family': 'Serif', 'weight': 'bold', 'size': 12})
|
| 207 |
+
plt.xticks(np.linspace(0, 150, num=16), fontname='Serif', weight='bold')
|
| 208 |
+
plt.yticks(np.linspace(0, 5, num=11), fontname='Serif', weight='bold')
|
| 209 |
+
plt.xlim(0, 150)
|
| 210 |
+
plt.ylim(0, 5)
|
| 211 |
+
legend_lines = [
|
| 212 |
+
Line2D([0], [0], color='blue', lw=3),
|
| 213 |
+
Line2D([0], [0], color='orange', lw=3),
|
| 214 |
+
Line2D([0], [0], color='green', lw=3),
|
| 215 |
+
Line2D([0], [0], color='red', lw=3)
|
| 216 |
+
]
|
| 217 |
+
plt.legend(legend_lines, ['Train Loss', 'Validation Loss', 'Train Accuracy', 'Validation Accuracy'],
|
| 218 |
+
loc='lower center', bbox_to_anchor=(0.5, 1.1), ncol=5,
|
| 219 |
+
prop={'family': 'Serif', 'weight': 'bold', 'size': 8}, frameon=False,
|
| 220 |
+
handler_map={Line2D: HandlerLine2D(numpoints=5)})
|
| 221 |
+
plt.gca().xaxis.labelpad = 10
|
| 222 |
+
plt.gca().spines['top'].set_visible(False)
|
| 223 |
+
plt.gca().spines['right'].set_visible(False)
|
| 224 |
+
plt.tight_layout()
|
| 225 |
+
plt.show()
|
| 226 |
+
|
| 227 |
+
latest_checkpoint = tf.train.latest_checkpoint(checkpoint_dir)
|
| 228 |
+
print(checkpoint_dir)
|
| 229 |
+
if latest_checkpoint is not None:
|
| 230 |
+
loaded_model = create_model(summary=True)
|
| 231 |
+
status = loaded_model.load_weights(latest_checkpoint)
|
| 232 |
+
status.expect_partial()
|
| 233 |
+
else:
|
| 234 |
+
print("No checkpoint file found in the specified directory.")
|
| 235 |
+
|
| 236 |
+
loaded_model.compile(optimizer=Adam(learning_rate=1e-3), loss=tf.keras.losses.BinaryCrossentropy(), metrics=['accuracy'])
|
| 237 |
+
|
| 238 |
+
test_loss, test_acc = loaded_model.evaluate(test_generator)
|
| 239 |
+
print(f"Test Accuracy: {test_acc}")
|
| 240 |
+
|
| 241 |
+
# Commented out IPython magic to ensure Python compatibility.
|
| 242 |
+
# %whos
|
| 243 |
+
|
| 244 |
+
true_classes = [1, 0, 1, 1, 0]
|
| 245 |
+
predicted_classes = [1, 1, 0, 1, 0]
|
| 246 |
+
print(f"Accuracy: {accuracy_score(true_classes, predicted_classes)}")
|
| 247 |
+
print(f"Precision: {precision_score(true_classes, predicted_classes)}")
|
| 248 |
+
print(f"Recall: {recall_score(true_classes, predicted_classes)}")
|
| 249 |
+
print(f"F1 Score: {f1_score(true_classes, predicted_classes)}")
|
| 250 |
+
print(f"Log Loss: {log_loss(true_classes, predicted_classes)}")
|
| 251 |
+
print(f"Jaccard Score: {jaccard_score(true_classes, predicted_classes)}")
|
| 252 |
+
|
| 253 |
+
print("\nClassification Report:")
|
| 254 |
+
print(classification_report(true_classes, predicted_classes,digits=4))
|
| 255 |
+
|
| 256 |
+
conf_matrix = confusion_matrix(true_classes, predicted_classes)
|
| 257 |
+
plt.figure(figsize=(6, 4.5))
|
| 258 |
+
custom_palette = sns.color_palette(palette='blend:#7AB,#EDA')
|
| 259 |
+
font = {'family': 'Serif', 'weight': 'bold', 'size': 12}
|
| 260 |
+
heatmap = sns.heatmap(conf_matrix, annot=True, fmt='d', cmap=custom_palette,vmin=0,vmax=350,
|
| 261 |
+
xticklabels=['Fractured', 'Non_fractured'], yticklabels=['Fractured', 'Non_fractured'],annot_kws={"family": "Serif",'weight': 'bold', 'size': 12})
|
| 262 |
+
heatmap.set_xlabel('Predicted Labels', fontdict=font)
|
| 263 |
+
heatmap.set_ylabel('True Labels', fontdict=font)
|
| 264 |
+
heatmap.set_title('Fracture Classification', fontdict=font, pad=12)
|
| 265 |
+
heatmap.set_xticklabels(heatmap.get_xticklabels(), fontname='Serif', fontsize=12)
|
| 266 |
+
heatmap.set_yticklabels(heatmap.get_yticklabels(), fontname='Serif', fontsize=12)
|
| 267 |
+
cbar = heatmap.collections[0].colorbar
|
| 268 |
+
cbar.set_label('Count', fontdict=font)
|
| 269 |
+
cbar.ax.tick_params(labelsize=10)
|
| 270 |
+
plt.gca().xaxis.labelpad = 10
|
| 271 |
+
plt.tight_layout()
|
| 272 |
+
plt.show()
|
| 273 |
+
|
| 274 |
+
import numpy as np
|
| 275 |
+
|
| 276 |
+
print(type(true_classes))
|
| 277 |
+
print(type(predictions))
|
| 278 |
+
|
| 279 |
+
!pip install scikit-learn
|
| 280 |
+
!pip install matplotlib
|
| 281 |
+
|
| 282 |
+
from sklearn.metrics import roc_curve, roc_auc_score
|
| 283 |
+
import matplotlib.pyplot as plt
|
| 284 |
+
from matplotlib.patches import Patch
|
| 285 |
+
|
| 286 |
+
print(type(predictions))
|
| 287 |
+
|
| 288 |
+
predictions = np.array(predictions)
|
| 289 |
+
|
| 290 |
+
def save_and_display_gradcam(img_path, heatmap, alpha=0.7):
|
| 291 |
+
img = cv2.imread(img_path)
|
| 292 |
+
img = cv2.resize(img, (299, 299))
|
| 293 |
+
heatmap = cv2.resize(heatmap, (img.shape[1], img.shape[0]))
|
| 294 |
+
heatmap = np.uint8(255 * heatmap)
|
| 295 |
+
heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_PLASMA)
|
| 296 |
+
superimposed_img = cv2.addWeighted(heatmap, alpha, img, 1 - alpha, 0)
|
| 297 |
+
plt.figure(figsize=(4, 4))
|
| 298 |
+
plt.imshow(cv2.cvtColor(superimposed_img, cv2.COLOR_BGR2RGB))
|
| 299 |
+
plt.title('GradCAM', fontdict={'family': 'Serif', 'weight': 'bold', 'size': 12})
|
| 300 |
+
plt.axis('off')
|
| 301 |
+
plt.tight_layout()
|
| 302 |
+
plt.show()
|
| 303 |
+
|
| 304 |
+
def make_gradcam_heatmap(img_array, model, last_conv_layer_name, pred_index=None):
|
| 305 |
+
model.layers[-1].activation = None
|
| 306 |
+
grad_model = tf.keras.models.Model(
|
| 307 |
+
[model.inputs], [model.get_layer(last_conv_layer_name).output, model.output]
|
| 308 |
+
)
|
| 309 |
+
with tf.GradientTape() as tape:
|
| 310 |
+
last_conv_layer_output, preds = grad_model(img_array)
|
| 311 |
+
if pred_index is None:
|
| 312 |
+
pred_index = tf.argmax(preds[0])
|
| 313 |
+
class_channel = preds[:, pred_index]
|
| 314 |
+
grads = tape.gradient(class_channel, last_conv_layer_output)
|
| 315 |
+
pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))
|
| 316 |
+
last_conv_layer_output = last_conv_layer_output[0]
|
| 317 |
+
heatmap = last_conv_layer_output @ pooled_grads[..., tf.newaxis]
|
| 318 |
+
heatmap = tf.squeeze(heatmap)
|
| 319 |
+
heatmap = tf.maximum(heatmap, 0) / tf.math.reduce_max(heatmap)
|
| 320 |
+
return heatmap.numpy()
|
| 321 |
+
|
| 322 |
+
def make_prediction_and_visualize_():
|
| 323 |
+
img_path = '/content/drive/MyDrive/BoneFractureDataset/testing/fractured/3.jpg'
|
| 324 |
+
img = cv2.imread(img_path)
|
| 325 |
+
img = cv2.resize(img, (299, 299))
|
| 326 |
+
rescaled_img = img/255.0
|
| 327 |
+
batch_pred = np.expand_dims(rescaled_img, 0)
|
| 328 |
+
last_conv_layer_name = 'conv5_block32_concat'
|
| 329 |
+
heatmap = make_gradcam_heatmap(batch_pred, loaded_model, last_conv_layer_name)
|
| 330 |
+
save_and_display_gradcam(img_path, heatmap)
|
| 331 |
+
make_prediction_and_visualize_()
|
| 332 |
+
|
| 333 |
+
def save_and_display_gradcam_plusplus(img_path, heatmap, alpha=0.7):
|
| 334 |
+
img = cv2.imread(img_path)
|
| 335 |
+
img = cv2.resize(img, (299, 299))
|
| 336 |
+
heatmap = cv2.resize(heatmap, (img.shape[1], img.shape[0]))
|
| 337 |
+
heatmap = np.uint8(255 * heatmap)
|
| 338 |
+
heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_PLASMA)
|
| 339 |
+
superimposed_img = cv2.addWeighted(heatmap, alpha, img, 1 - alpha, 0)
|
| 340 |
+
plt.figure(figsize=(4, 4))
|
| 341 |
+
plt.imshow(cv2.cvtColor(superimposed_img, cv2.COLOR_BGR2RGB))
|
| 342 |
+
plt.title('GradCAM++', fontdict={'family': 'Serif', 'weight': 'bold', 'size': 12})
|
| 343 |
+
plt.axis('off')
|
| 344 |
+
plt.tight_layout()
|
| 345 |
+
plt.show()
|
| 346 |
+
|
| 347 |
+
def make_gradcam_plusplus_heatmap(img_array, model, last_conv_layer_name, pred_index=None):
|
| 348 |
+
model.layers[-1].activation = None
|
| 349 |
+
grad_model = tf.keras.models.Model(
|
| 350 |
+
[model.inputs], [model.get_layer(last_conv_layer_name).output, model.output]
|
| 351 |
+
)
|
| 352 |
+
with tf.GradientTape() as tape:
|
| 353 |
+
last_conv_layer_output, preds = grad_model(img_array)
|
| 354 |
+
if pred_index is None:
|
| 355 |
+
pred_index = tf.argmax(preds[0])
|
| 356 |
+
class_output = preds[:, pred_index]
|
| 357 |
+
conv_output = last_conv_layer_output[0]
|
| 358 |
+
grads = tape.gradient(class_output, last_conv_layer_output)
|
| 359 |
+
pooled_grads = tf.reduce_mean(grads[0], axis=(0, 1, 2))
|
| 360 |
+
last_conv_layer_output = last_conv_layer_output[0]
|
| 361 |
+
guided_grads = tf.cast(last_conv_layer_output > 0, 'float32') * grads[0]
|
| 362 |
+
weights = tf.reduce_mean(guided_grads, axis=(0, 1))
|
| 363 |
+
heatmap = tf.reduce_sum(tf.multiply(weights, last_conv_layer_output), axis=-1)
|
| 364 |
+
heatmap = tf.maximum(heatmap, 0) / tf.reduce_max(heatmap)
|
| 365 |
+
return heatmap.numpy()
|
| 366 |
+
|
| 367 |
+
def make_prediction_and_visualize_gradcam_plusplus():
|
| 368 |
+
img_path = '/content/drive/MyDrive/testing/not_fractured/1-rotated1-rotated1-rotated1-rotated1.jpg'
|
| 369 |
+
img = cv2.imread(img_path)
|
| 370 |
+
img = cv2.resize(img, (299, 299))
|
| 371 |
+
rescaled_img = img / 255.0
|
| 372 |
+
batch_pred = np.expand_dims(rescaled_img, 0)
|
| 373 |
+
last_conv_layer_name = 'conv5_block32_concat'
|
| 374 |
+
heatmap = make_gradcam_plusplus_heatmap(batch_pred, loaded_model, last_conv_layer_name)
|
| 375 |
+
save_and_display_gradcam_plusplus(img_path, heatmap)
|
| 376 |
+
make_prediction_and_visualize_gradcam_plusplus()
|
| 377 |
+
|
| 378 |
+
def save_and_display_scorecam(img_path, heatmap, alpha=0.7):
|
| 379 |
+
img = cv2.imread(img_path)
|
| 380 |
+
img = cv2.resize(img, (299, 299))
|
| 381 |
+
heatmap = cv2.resize(heatmap, (img.shape[1], img.shape[0]))
|
| 382 |
+
heatmap = np.uint8(255 * heatmap)
|
| 383 |
+
heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_PLASMA)
|
| 384 |
+
superimposed_img = cv2.addWeighted(heatmap, alpha, img, 1 - alpha, 0)
|
| 385 |
+
plt.figure(figsize=(4, 4))
|
| 386 |
+
plt.imshow(cv2.cvtColor(superimposed_img, cv2.COLOR_BGR2RGB))
|
| 387 |
+
plt.title('ScoreCAM', fontdict={'family': 'Serif', 'weight': 'bold', 'size': 12})
|
| 388 |
+
plt.axis('off')
|
| 389 |
+
plt.tight_layout()
|
| 390 |
+
plt.show()
|
| 391 |
+
|
| 392 |
+
import tensorflow as tf
|
| 393 |
+
def make_scorecam_heatmap(img_array, model, last_conv_layer_name, pred_index=None):
|
| 394 |
+
model.layers[-1].activation = None
|
| 395 |
+
grad_model = tf.keras.models.Model(
|
| 396 |
+
[model.inputs], [model.get_layer(last_conv_layer_name).output, model.output]
|
| 397 |
+
)
|
| 398 |
+
with tf.GradientTape() as tape:
|
| 399 |
+
last_conv_layer_output, preds = grad_model(img_array)
|
| 400 |
+
if pred_index is None:
|
| 401 |
+
pred_index = tf.argmax(preds[0])
|
| 402 |
+
class_output = preds[:, pred_index]
|
| 403 |
+
conv_output = last_conv_layer_output[0]
|
| 404 |
+
grads = tape.gradient(class_output, last_conv_layer_output)
|
| 405 |
+
guided_grads = tf.cast(grads[0] > 0, 'float32') * grads[0]
|
| 406 |
+
weights = tf.reduce_mean(guided_grads, axis=(0, 1))
|
| 407 |
+
cam = tf.reduce_sum(tf.multiply(weights, conv_output), axis=-1)
|
| 408 |
+
cam = tf.maximum(cam, 0)
|
| 409 |
+
cam /= tf.reduce_max(cam)
|
| 410 |
+
return cam.numpy()
|
| 411 |
+
|
| 412 |
+
def make_prediction_and_visualize_scorecam():
|
| 413 |
+
img_path = '/content/drive/MyDrive/BoneFractureDataset/training/fractured/10.jpg'
|
| 414 |
+
img = cv2.imread(img_path)
|
| 415 |
+
img = cv2.resize(img, (299, 299))
|
| 416 |
+
rescaled_img = img/255.0
|
| 417 |
+
batch_pred = np.expand_dims(rescaled_img, 0)
|
| 418 |
+
last_conv_layer_name = 'conv5_block32_concat'
|
| 419 |
+
heatmap = make_scorecam_heatmap(batch_pred, loaded_model, last_conv_layer_name)
|
| 420 |
+
save_and_display_scorecam(img_path, heatmap)
|
| 421 |
+
make_prediction_and_visualize_scorecam()
|
| 422 |
+
|
| 423 |
+
def save_and_display_faster_scorecam(img_path, heatmap, alpha=0.7):
|
| 424 |
+
img = cv2.imread(img_path)
|
| 425 |
+
img = cv2.resize(img, (299, 299))
|
| 426 |
+
heatmap = cv2.resize(heatmap, (img.shape[1], img.shape[0]))
|
| 427 |
+
heatmap = np.uint8(255 * heatmap)
|
| 428 |
+
heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_PLASMA)
|
| 429 |
+
superimposed_img = cv2.addWeighted(heatmap, alpha, img, 1 - alpha, 0)
|
| 430 |
+
plt.figure(figsize=(4, 4))
|
| 431 |
+
plt.imshow(cv2.cvtColor(superimposed_img, cv2.COLOR_BGR2RGB))
|
| 432 |
+
plt.title('Faster ScoreCAM', fontdict={'family': 'Serif', 'weight': 'bold', 'size': 12})
|
| 433 |
+
plt.axis('off')
|
| 434 |
+
plt.tight_layout()
|
| 435 |
+
plt.show()
|
| 436 |
+
|
| 437 |
+
def faster_scorecam_heatmap(img_array, model, last_conv_layer_name, pred_index=None):
|
| 438 |
+
model.layers[-1].activation = None
|
| 439 |
+
grad_model = tf.keras.models.Model(
|
| 440 |
+
[model.inputs], [model.get_layer(last_conv_layer_name).output, model.output]
|
| 441 |
+
)
|
| 442 |
+
with tf.GradientTape() as tape:
|
| 443 |
+
last_conv_layer_output, preds = grad_model(img_array)
|
| 444 |
+
if pred_index is None:
|
| 445 |
+
pred_index = tf.argmax(preds[0])
|
| 446 |
+
class_output = preds[:, pred_index]
|
| 447 |
+
conv_output = last_conv_layer_output[0]
|
| 448 |
+
grads = tape.gradient(class_output, last_conv_layer_output)[0]
|
| 449 |
+
weights = tf.reduce_mean(grads, axis=(0, 1))
|
| 450 |
+
weights = tf.reshape(weights, (1, 1, -1))
|
| 451 |
+
conv_output = tf.expand_dims(conv_output, axis=0)
|
| 452 |
+
conv_output = tf.expand_dims(conv_output, axis=-1)
|
| 453 |
+
cam = tf.matmul(weights, conv_output)
|
| 454 |
+
cam = tf.squeeze(cam)
|
| 455 |
+
cam = tf.maximum(cam, 0)
|
| 456 |
+
cam /= tf.reduce_max(cam)
|
| 457 |
+
return cam.numpy()
|
| 458 |
+
|
| 459 |
+
def make_prediction_and_visualize_faster_scorecam():
|
| 460 |
+
img_path = '/content/drive/MyDrive/BoneFractureDataset/testing/fractured/3.jpg'
|
| 461 |
+
img = cv2.imread(img_path)
|
| 462 |
+
img = cv2.resize(img, (299, 299))
|
| 463 |
+
rescaled_img = img/255.0
|
| 464 |
+
batch_pred = np.expand_dims(rescaled_img, 0)
|
| 465 |
+
last_conv_layer_name = 'conv5_block32_concat'
|
| 466 |
+
heatmap = faster_scorecam_heatmap(batch_pred, loaded_model, last_conv_layer_name)
|
| 467 |
+
save_and_display_faster_scorecam(img_path, heatmap)
|
| 468 |
+
make_prediction_and_visualize_faster_scorecam()
|
| 469 |
+
|
| 470 |
+
def save_and_display_layercam(img_path, heatmap, alpha=0.7):
|
| 471 |
+
img = cv2.imread(img_path)
|
| 472 |
+
img = cv2.resize(img, (299, 299))
|
| 473 |
+
heatmap = cv2.resize(heatmap, (img.shape[1], img.shape[0]))
|
| 474 |
+
heatmap = np.uint8(255 * heatmap)
|
| 475 |
+
heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_PLASMA)
|
| 476 |
+
superimposed_img = cv2.addWeighted(heatmap, alpha, img, 1 - alpha, 0)
|
| 477 |
+
plt.figure(figsize=(4, 4))
|
| 478 |
+
plt.imshow(cv2.cvtColor(superimposed_img, cv2.COLOR_BGR2RGB))
|
| 479 |
+
plt.title('LayerCAM', fontdict={'family': 'Serif', 'weight': 'bold', 'size': 12})
|
| 480 |
+
plt.axis('off')
|
| 481 |
+
plt.tight_layout()
|
| 482 |
+
plt.show()
|
| 483 |
+
|
| 484 |
+
import tensorflow as tf
|
| 485 |
+
def generate_layercam_heatmap(img_array, model, last_conv_layer_name, target_class_index=None):
|
| 486 |
+
model.layers[-1].activation = None
|
| 487 |
+
grad_model = tf.keras.models.Model(
|
| 488 |
+
[model.inputs], [model.get_layer(last_conv_layer_name).output, model.output]
|
| 489 |
+
)
|
| 490 |
+
with tf.GradientTape() as tape:
|
| 491 |
+
last_conv_layer_output, preds = grad_model(img_array)
|
| 492 |
+
if target_class_index is None:
|
| 493 |
+
target_class_index = tf.argmax(preds[0])
|
| 494 |
+
class_output = preds[:, target_class_index]
|
| 495 |
+
conv_output = last_conv_layer_output[0]
|
| 496 |
+
grads = tape.gradient(class_output, last_conv_layer_output)[0]
|
| 497 |
+
weights = tf.reduce_mean(grads, axis=(0, 1))
|
| 498 |
+
weights = tf.reshape(weights, (1, 1, -1))
|
| 499 |
+
conv_output = tf.expand_dims(conv_output, axis=0)
|
| 500 |
+
conv_output = tf.expand_dims(conv_output, axis=-1)
|
| 501 |
+
cam = tf.matmul(weights, conv_output)
|
| 502 |
+
cam = tf.squeeze(cam)
|
| 503 |
+
cam = tf.maximum(cam, 0)
|
| 504 |
+
cam /= tf.reduce_max(cam)
|
| 505 |
+
return cam.numpy()
|
| 506 |
+
|
| 507 |
+
def make_prediction_and_visualize_layercam():
|
| 508 |
+
img_path = '/content/drive/MyDrive/BoneFractureDataset/testing/fractured/3.jpg'
|
| 509 |
+
img = cv2.imread(img_path)
|
| 510 |
+
img = cv2.resize(img, (299, 299))
|
| 511 |
+
rescaled_img = img/255.0
|
| 512 |
+
batch_pred = np.expand_dims(rescaled_img, 0)
|
| 513 |
+
last_conv_layer_name = 'conv5_block32_concat'
|
| 514 |
+
heatmap = generate_layercam_heatmap(batch_pred, loaded_model, last_conv_layer_name)
|
| 515 |
+
save_and_display_layercam(img_path, heatmap)
|
| 516 |
+
make_prediction_and_visualize_layercam()
|
| 517 |
+
|
| 518 |
+
def save_and_display_saliency_map(img_path, saliency_map):
|
| 519 |
+
img = cv2.imread(img_path)
|
| 520 |
+
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 521 |
+
saliency_map = cv2.resize(saliency_map, (img.shape[1], img.shape[0]))
|
| 522 |
+
saliency_map = (saliency_map - saliency_map.min()) / (saliency_map.max() - saliency_map.min())
|
| 523 |
+
heatmap = cv2.applyColorMap(np.uint8(255 * saliency_map), cv2.COLORMAP_JET)
|
| 524 |
+
heatmap = cv2.cvtColor(heatmap, cv2.COLOR_BGR2RGB)
|
| 525 |
+
alpha = 0.4
|
| 526 |
+
blended = cv2.addWeighted(img, alpha, heatmap, 1 - alpha, 0)
|
| 527 |
+
plt.figure(figsize=(4, 4))
|
| 528 |
+
plt.imshow(blended)
|
| 529 |
+
plt.title('Vanilla Saliency', fontdict={'family': 'Serif', 'weight': 'bold', 'size': 12})
|
| 530 |
+
plt.axis('off')
|
| 531 |
+
plt.tight_layout()
|
| 532 |
+
plt.show()
|
| 533 |
+
|
| 534 |
+
def generate_vanilla_saliency_map(img_array, model):
|
| 535 |
+
img_tensor = tf.convert_to_tensor(img_array)
|
| 536 |
+
img_tensor = tf.expand_dims(img_tensor, axis=0)
|
| 537 |
+
with tf.GradientTape() as tape:
|
| 538 |
+
tape.watch(img_tensor)
|
| 539 |
+
preds = model(img_tensor)
|
| 540 |
+
top_pred_index = tf.argmax(preds[0])
|
| 541 |
+
top_class_score = preds[:, top_pred_index]
|
| 542 |
+
grads = tape.gradient(top_class_score, img_tensor)
|
| 543 |
+
saliency_map = tf.abs(grads)
|
| 544 |
+
saliency_map = tf.reduce_max(saliency_map, axis=-1)
|
| 545 |
+
return saliency_map[0].numpy()
|
| 546 |
+
|
| 547 |
+
def make_prediction_and_visualize_vanilla_saliency():
|
| 548 |
+
img_path = '/content/drive/MyDrive/BoneFractureDataset/testing/fractured/3.jpg'
|
| 549 |
+
img = cv2.imread(img_path)
|
| 550 |
+
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 551 |
+
img = cv2.resize(img, (299, 299))
|
| 552 |
+
img = img / 255.0
|
| 553 |
+
saliency_map = generate_vanilla_saliency_map(img, loaded_model)
|
| 554 |
+
save_and_display_saliency_map(img_path, saliency_map)
|
| 555 |
+
make_prediction_and_visualize_vanilla_saliency()
|
| 556 |
+
|
| 557 |
+
def save_and_display_SmoothGrad(img_path, saliency_map):
|
| 558 |
+
img = cv2.imread(img_path)
|
| 559 |
+
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 560 |
+
saliency_map = cv2.resize(saliency_map, (img.shape[1], img.shape[0]))
|
| 561 |
+
saliency_map = (saliency_map - saliency_map.min()) / (saliency_map.max() - saliency_map.min())
|
| 562 |
+
heatmap = cv2.applyColorMap(np.uint8(255 * saliency_map), cv2.COLORMAP_JET)
|
| 563 |
+
heatmap = cv2.cvtColor(heatmap, cv2.COLOR_BGR2RGB)
|
| 564 |
+
alpha = 0.4
|
| 565 |
+
blended = cv2.addWeighted(img, alpha, heatmap, 1 - alpha, 0)
|
| 566 |
+
plt.figure(figsize=(4, 4))
|
| 567 |
+
plt.imshow(blended)
|
| 568 |
+
plt.title('Smooth Grad', fontdict={'family': 'Serif', 'weight': 'bold', 'size': 12})
|
| 569 |
+
plt.axis('off')
|
| 570 |
+
plt.tight_layout()
|
| 571 |
+
plt.show()
|
| 572 |
+
|
| 573 |
+
def generate_smoothgrad_saliency_map(img_array, model, n=50, sigma=1.0):
|
| 574 |
+
img_tensor = tf.convert_to_tensor(img_array)
|
| 575 |
+
img_tensor = tf.expand_dims(img_tensor, axis=0)
|
| 576 |
+
img_tensor = tf.cast(img_tensor, dtype=tf.float32)
|
| 577 |
+
with tf.GradientTape() as tape:
|
| 578 |
+
tape.watch(img_tensor)
|
| 579 |
+
preds = model(img_tensor)
|
| 580 |
+
top_pred_index = tf.argmax(preds[0])
|
| 581 |
+
top_class_score = preds[:, top_pred_index]
|
| 582 |
+
total_gradients = tf.zeros_like(img_tensor)
|
| 583 |
+
for _ in range(n):
|
| 584 |
+
noise = tf.random.normal(shape=img_tensor.shape, mean=0.0, stddev=sigma)
|
| 585 |
+
perturbed_img = img_tensor + noise
|
| 586 |
+
with tf.GradientTape() as perturbed_tape:
|
| 587 |
+
perturbed_tape.watch(perturbed_img)
|
| 588 |
+
perturbed_preds = model(perturbed_img)
|
| 589 |
+
perturbed_top_class_score = perturbed_preds[:, top_pred_index]
|
| 590 |
+
perturbed_grads = perturbed_tape.gradient(perturbed_top_class_score, perturbed_img)
|
| 591 |
+
total_gradients += perturbed_grads
|
| 592 |
+
averaged_gradients = total_gradients / n
|
| 593 |
+
saliency_map = tf.abs(averaged_gradients)
|
| 594 |
+
saliency_map = tf.reduce_max(saliency_map, axis=-1)
|
| 595 |
+
return saliency_map[0].numpy()
|
| 596 |
+
|
| 597 |
+
def make_prediction_and_visualize_smoothgrad_saliency():
|
| 598 |
+
img_path = '/content/drive/MyDrive/BoneFractureDataset/testing/fractured/3.jpg'
|
| 599 |
+
img = cv2.imread(img_path)
|
| 600 |
+
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 601 |
+
img = cv2.resize(img, (299, 299))
|
| 602 |
+
img = img / 255.0
|
| 603 |
+
heatmap = generate_smoothgrad_saliency_map(img, loaded_model)
|
| 604 |
+
save_and_display_SmoothGrad(img_path, heatmap)
|
| 605 |
+
make_prediction_and_visualize_smoothgrad_saliency()
|
| 606 |
+
|
ResNet/ResNet.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
ResNet/ResNet.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""ResNet50.ipynb
|
| 3 |
+
|
| 4 |
+
Automatically generated by Colaboratory.
|
| 5 |
+
|
| 6 |
+
Original file is located at
|
| 7 |
+
https://colab.research.google.com/drive/1Ztagc2mpxc2YEeFMut7EwFhL8SFY2gAm
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
import pandas as pd
|
| 12 |
+
from PIL import Image
|
| 13 |
+
import pickle
|
| 14 |
+
from sklearn.utils import shuffle
|
| 15 |
+
from sklearn.model_selection import train_test_split
|
| 16 |
+
from tensorflow.keras.preprocessing.image import ImageDataGenerator
|
| 17 |
+
from tensorflow.keras.models import Sequential
|
| 18 |
+
from tensorflow.keras.layers import Dense
|
| 19 |
+
import os
|
| 20 |
+
from tensorflow.keras.applications import ResNet50
|
| 21 |
+
from tensorflow.keras.applications.resnet50 import preprocess_input
|
| 22 |
+
|
| 23 |
+
datagen = ImageDataGenerator(rescale=1.0/255.0, rotation_range=20, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='nearest')
|
| 24 |
+
|
| 25 |
+
batch_size = 20
|
| 26 |
+
train_data_dir = '/content/drive/MyDrive/BoneFractureDataset/training'
|
| 27 |
+
validation_data_dir = '/content/drive/MyDrive/BoneFractureDataset/testing'
|
| 28 |
+
train_generator = datagen.flow_from_directory( train_data_dir,
|
| 29 |
+
target_size=(224, 224),
|
| 30 |
+
batch_size=batch_size,
|
| 31 |
+
class_mode='binary',
|
| 32 |
+
shuffle=True )
|
| 33 |
+
validation_generator = datagen.flow_from_directory(
|
| 34 |
+
validation_data_dir,
|
| 35 |
+
target_size=(224, 224),
|
| 36 |
+
batch_size=batch_size,
|
| 37 |
+
class_mode='binary',
|
| 38 |
+
shuffle=False
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
!ls /kaggle/input/resnet50-weights/
|
| 42 |
+
|
| 43 |
+
!stat /kaggle/input/resnet50-weights/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5
|
| 44 |
+
|
| 45 |
+
!wget https://storage.googleapis.com/tensorflow/keras-applications/resnet/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5 -P /kaggle/input/resnet50-weights/
|
| 46 |
+
|
| 47 |
+
!cat /kaggle/input/resnet50-weights/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5
|
| 48 |
+
|
| 49 |
+
!ls -l /kaggle/input/resnet50-weights/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5
|
| 50 |
+
|
| 51 |
+
!wget https://storage.googleapis.com/tensorflow/keras-applications/resnet/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5 -P /kaggle/input/resnet50-weights
|
| 52 |
+
|
| 53 |
+
resModel = Sequential()
|
| 54 |
+
resModel.add(ResNet50(
|
| 55 |
+
include_top=False,
|
| 56 |
+
pooling='avg',
|
| 57 |
+
weights=None,
|
| 58 |
+
))
|
| 59 |
+
resModel.add(Dense(1, activation='sigmoid'))
|
| 60 |
+
for layer in resModel.layers[0].layers[-50:]:
|
| 61 |
+
layer.trainable = True
|
| 62 |
+
|
| 63 |
+
from tensorflow.keras.optimizers import Adam
|
| 64 |
+
from tensorflow.keras.callbacks import ReduceLROnPlateau
|
| 65 |
+
optimizer = Adam(learning_rate=0.001)
|
| 66 |
+
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=3, min_lr=0.0001)
|
| 67 |
+
resModel.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy'])
|
| 68 |
+
epochs = 10
|
| 69 |
+
history = resModel.fit(train_generator, epochs=epochs, validation_data=validation_generator, callbacks=[reduce_lr])
|
| 70 |
+
evaluation = resModel.evaluate(train_generator)
|
| 71 |
+
print(f"Test Accuracy: {evaluation[1] * 100:.2f}%")
|
| 72 |
+
|
| 73 |
+
initial_epoch = 0
|
| 74 |
+
saved_history = {
|
| 75 |
+
'loss': history.history['loss'],
|
| 76 |
+
'accuracy': history.history['accuracy'],
|
| 77 |
+
'val_loss': history.history['val_loss'],
|
| 78 |
+
'val_accuracy': history.history['val_accuracy'],
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
import matplotlib.pyplot as plt
|
| 82 |
+
from matplotlib.lines import Line2D
|
| 83 |
+
from matplotlib.legend_handler import HandlerLine2D
|
| 84 |
+
import numpy as np
|
| 85 |
+
|
| 86 |
+
initial_epoch = 10
|
| 87 |
+
saved_history = {
|
| 88 |
+
'loss': history.history['loss'],
|
| 89 |
+
'accuracy': history.history['accuracy'],
|
| 90 |
+
'val_loss': history.history['val_loss'],
|
| 91 |
+
'val_accuracy': history.history['val_accuracy'],
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
!ls /kaggle/working
|
| 95 |
+
|
| 96 |
+
!ls -l /kaggle/working/saved_D201history.npy
|
| 97 |
+
|
| 98 |
+
!find / -name saved_D201history.npy
|
| 99 |
+
|
| 100 |
+
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, log_loss, jaccard_score
|
| 101 |
+
true_classes = [1, 0, 1, 1, 0]
|
| 102 |
+
predicted_classes = [1, 1, 0, 1, 0]
|
| 103 |
+
print(f"Accuracy: {accuracy_score(true_classes, predicted_classes)}")
|
| 104 |
+
print(f"Precision: {precision_score(true_classes, predicted_classes)}")
|
| 105 |
+
print(f"Recall: {recall_score(true_classes, predicted_classes)}")
|
| 106 |
+
print(f"F1 Score: {f1_score(true_classes, predicted_classes)}")
|
| 107 |
+
print(f"Log Loss: {log_loss(true_classes, predicted_classes)}")
|
| 108 |
+
print(f"Jaccard Score: {jaccard_score(true_classes, predicted_classes)}")
|
| 109 |
+
|
| 110 |
+
from sklearn.metrics import classification_report
|
| 111 |
+
|
| 112 |
+
print("\nClassification Report:")
|
| 113 |
+
print(classification_report(true_classes, predicted_classes,digits=4))
|
| 114 |
+
|
| 115 |
+
from sklearn.metrics import roc_curve, roc_auc_score
|
| 116 |
+
import matplotlib.pyplot as plt
|
| 117 |
+
from matplotlib.patches import Patch
|
| 118 |
+
|
| 119 |
+
def save_and_display_gradcam(img_path, heatmap, alpha=0.7):
|
| 120 |
+
img = cv2.imread(img_path)
|
| 121 |
+
img = cv2.resize(img, (299, 299))
|
| 122 |
+
heatmap = cv2.resize(heatmap, (img.shape[1], img.shape[0]))
|
| 123 |
+
heatmap = np.uint8(255 * heatmap)
|
| 124 |
+
heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_PLASMA)
|
| 125 |
+
superimposed_img = cv2.addWeighted(heatmap, alpha, img, 1 - alpha, 0)
|
| 126 |
+
plt.figure(figsize=(4, 4))
|
| 127 |
+
plt.imshow(cv2.cvtColor(superimposed_img, cv2.COLOR_BGR2RGB))
|
| 128 |
+
plt.title('GradCAM', fontdict={'family': 'Serif', 'weight': 'bold', 'size': 12})
|
| 129 |
+
plt.axis('off')
|
| 130 |
+
plt.tight_layout()
|
| 131 |
+
plt.show()
|
| 132 |
+
|
| 133 |
+
def make_gradcam_heatmap(img_array, model, last_conv_layer_name, pred_index=None):
|
| 134 |
+
model.layers[-1].activation = None
|
| 135 |
+
grad_model = tf.keras.models.Model(
|
| 136 |
+
[model.inputs], [model.get_layer(last_conv_layer_name).output, model.output]
|
| 137 |
+
)
|
| 138 |
+
with tf.GradientTape() as tape:
|
| 139 |
+
last_conv_layer_output, preds = grad_model(img_array)
|
| 140 |
+
if pred_index is None:
|
| 141 |
+
pred_index = tf.argmax(preds[0])
|
| 142 |
+
class_channel = preds[:, pred_index]
|
| 143 |
+
grads = tape.gradient(class_channel, last_conv_layer_output)
|
| 144 |
+
pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))
|
| 145 |
+
last_conv_layer_output = last_conv_layer_output[0]
|
| 146 |
+
heatmap = last_conv_layer_output @ pooled_grads[..., tf.newaxis]
|
| 147 |
+
heatmap = tf.squeeze(heatmap)
|
| 148 |
+
heatmap = tf.maximum(heatmap, 0) / tf.math.reduce_max(heatmap)
|
| 149 |
+
return heatmap.numpy()
|
| 150 |
+
|
| 151 |
+
import cv2
|
| 152 |
+
|
| 153 |
+
abcd = cv2.imread('/content/drive/MyDrive/BoneFractureDataset/testing/fractured/3.jpg')
|
| 154 |
+
|
| 155 |
+
plt.imshow(abcd)
|