i have this code for testing the label for the input image:
!pip install tensorflow opencv-python matplotlib
"""#Importing Libraries"""
import numpy as np
import os
import cv2
import tensorflow as tf
from tensorflow.keras import layers, models
from sklearn.utils.class_weight import compute_class_weight
from sklearn.metrics import f1_score
from tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping
import matplotlib.pyplot as plt
"""# Downloading OASIS Alzheimer's Dataset from Kaggle"""
import kagglehub
import os
path = kagglehub.dataset_download("ninadaithal/imagesoasis")
print("Path to dataset files:", path)
source_folder = os.path.join(path, "Data")
destination_folder = '/content/OASIS_Alzheimers_Dataset/'
!cp -r "{source_folder}" "{destination_folder}"
data_dir = 'OASIS_Alzheimers_Dataset'
os.listdir(data_dir)
"""#Creating Data Pipeline"""
data = tf.keras.utils.image_dataset_from_directory('OASIS_Alzheimers_Dataset')
data_iterator = data.as_numpy_iterator()
data_iterator
"""#Images"""
batch = data_iterator.next()
batch[0].shape
"""#Labels for the images"""
batch[1]
fig, ax = plt.subplots(ncols=4, figsize=(15,10))
for idx, img in enumerate(batch[0][:4]):
ax[idx].imshow(img.astype(int))
ax[idx].title.set_text(batch[1][idx])
"""#Scale Data"""
data = data.map(lambda x,y: (x/255, y))
data.as_numpy_iterator().next()[0].min()
data.as_numpy_iterator().next()[0].max()
"""#Split Data"""
len(data)
train_size = int(len(data).7) # 1891
val_size = int(len(data).2) # 540
test_size = len(data) - train_size - val_size # 271
train = data.take(train_size)
val = data.skip(train_size).take(val_size)
test = data.skip(train_size+val_size).take(test_size)
len(test)
"""#Calculate Class Weights"""
class_labels = np.concatenate([y.numpy() for x, y in train])
class_weights = compute_class_weight('balanced', classes=np.unique(class_labels), y=class_labels)
class_weight_dict = dict(enumerate(class_weights))
class_weight_dict
"""#Build The Model"""
from tensorflow.keras.models import Sequential
from tensorflow.keras.applications import ResNet50V2
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dropout, Dense, GlobalAveragePooling2D, BatchNormalization, Flatten
base_model = ResNet50V2(weights='imagenet', include_top=False, input_shape=(256, 256, 3))
x = GlobalAveragePooling2D()(base_model.output)
x = Dense(1024, activation='relu')(x)
x = Dropout(0.5)(x)
x = Dense(4, activation='softmax')(x)
model = Model(inputs=base_model.input, outputs=x)
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.summary()
"""#Callbacks(reduce learning rate and early stopping)"""
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=3, min_lr=1e-6, verbose=1)
early_stopping = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)
"""#Train The Model"""
!mkdir logs
tensorboard_callback = tf.keras.callbacks.TensorBoard("logs")
history = model.fit(train, epochs=20, validation_data=val, class_weight=class_weight_dict, callbacks=[reduce_lr, early_stopping])
"""#Save the trained model"""
model.save('AD_Model.h5')
print("Model saved")
"""#Import the trained model"""
from google.colab import drive
import shutil
import os
Step 1: Mount Google Drive
drive.mount('/content/drive')
Step 2: Specify the path of the file you want to upload
For example, let's say you uploaded a file named 'your_file.txt' to the Colab environment.
source_file_path = '/content/AD_Model.h5' # Change this to your actual file name
Step 3: Specify the destination path in Google Drive
destination_file_path = '/content/drive/' # Change this to your desired destination
Step 4: Copy the file to Google Drive
shutil.copy(source_file_path, destination_file_path)
print(f'File uploaded to Google Drive at {destination_file_path}')
"""#Loss Curve"""
fig = plt.figure()
plt.plot(history.history['loss'], color='teal', label='loss')
plt.plot(history.history['val_loss'], color='orange', label='val_loss')
fig.suptitle('Loss', fontsize=20)
plt.legend(loc="upper left")
plt.show()
"""#Accuracy Curve"""
fig = plt.figure()
plt.plot(history.history['accuracy'], color='teal', label='accuracy')
plt.plot(history.history['val_accuracy'], color='orange', label='val_accuracy')
fig.suptitle('Accuracy', fontsize=20)
plt.legend(loc="upper left")
plt.show()
from tensorflow.keras.metrics import Precision, Recall, SparseCategoricalAccuracy
"""#Predict labels and update the metrics"""
precision = Precision()
recall = Recall()
accuracy = SparseCategoricalAccuracy()
y_true = []
y_pred = []
for batch in test.as_numpy_iterator():
x, y = batch
yhat = model.predict(x)
yhat_classes = np.argmax(yhat, axis=1)
precision.update_state(y, yhat_classes)
recall.update_state(y, yhat_classes)
accuracy.update_state(y, yhat_classes)
y_true.extend(y.tolist())
y_pred.extend(yhat_classes.tolist())
print("Precision:", precision.result().numpy())
print("Recall:", recall.result().numpy())
print("Sparse Categorical Accuracy:", accuracy.result().numpy())
f1 = f1_score(y_true, y_pred, average='weighted')
print("F1 Score:", f1)
"""#Predict the class label for an input image"""
def test_image(image_path):
# Example model prediction logic (this will vary depending on your model)
# Replace the next two lines with your actual model prediction logic
predicted_class = model.predict(image_path) # Replace with your prediction method
confidence_score = model.predict_proba(image_path) # Obtain the confidence score
# Example output, adjust according to your model's output
return predicted_class, confidence_score[predicted_class]
Load and predict
image_path = '/content/OAS1_0308_MR1_mpr-1_108.jpg'
predicted_class, confidence_score = test_image(image_path)
predicted_class_name = class_names[predicted_class]
confidence_percentage = confidence_score * 100 # Convert to percentage
print(f'The input image belongs to class: {predicted_class} - {predicted_class_name} with confidence: {confidence_percentage:.2f}%\n')
Load the original image for display
original_img = cv2.imread(image_path)
original_img = cv2.cvtColor(original_img, cv2.COLOR_BGR2RGB)
plt.imshow(original_img)
plt.title(f'Predicted Class: {predicted_class_name} (Confidence: {confidence_percentage:.2f}%)')
plt.axis('off')
plt.show()
def test_image(image_path):
img = cv2.imread(image_path)
img = cv2.resize(img, (256, 256))
img = img / 255.0
img = np.expand_dims(img, axis=0)
predictions = model.predict(img)
predicted_class = np.argmax(predictions)
return predicted_class
"""#Labels with their class names"""
class_names = {
0: "Mild Dementia",
1: "Moderate Dementia",
2: "Non Demented",
3: "Very Mild Dementia"
}
image_path = '/content/OAS1_0308_MR1_mpr-1_108.jpg'
predicted_class = test_image(image_path)
predicted_class_name = class_names[predicted_class]
print(f'The input image belongs to class: {predicted_class} - {predicted_class_name}\n')
original_img = cv2.imread(image_path)
original_img = cv2.cvtColor(original_img, cv2.COLOR_BGR2RGB)
plt.imshow(original_img)
plt.title(f'Predicted Class: {predicted_class_name}')
plt.axis('off')
plt.show()
change the code so that it says with what accuracy the image belongs to which class