The latest outbreak of monkeypox has now become a source of concern for healthcare professionals throughout the
world. It is essential to have an early diagnosis in order to slow down its rapid progression. For this purpose, we have created a new skin image-based dataset for the detection of monkeypox disease.
This dataset consists of four classes: Monkeypox, Chickenpox, Measles, and Normal.
All the image classes are collected from internet-based sources. The entire dataset has been developed by the Department of Computer Science and Engineering, Islamic University, Kushtia-7003, Bangladesh.
Source Of Dataset:-
https://www.kaggle.com/datasets/dipuiucse/monkeypoxskinimagedataset
Let us now import the required libraries
import os
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dropout, BatchNormalization
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
# Deep learning
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense
plt.style.use('default')
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
In the next step let us use OneHotEncoder and encode the dataset. Monkeypox is indicated by 0 and Normal is indicated by 1.
encoder = OneHotEncoder()
encoder.fit([[0], [1]])
Now let us create three empty lists named data, paths, and results. The data list contains NumPy forms of images. Path lists contain the path of each and every image and the result list contains the target class whether zero or one.
Now let us give images with monkeypox
# This cell updates result list for images with Monkeypox
data = []
paths = []
result = []
for r, d, f in os.walk('C:\\Users\\vaibhav1.mali\\PycharmProjects\\Monkeypox_Dataset\\Monkey Pox'):
for file in f:
if '.jpg' in file:
paths.append(os.path.join(r, file))
for path in paths:
img = Image.open(path)
img = img.resize((128,128))
img = np.array(img)
if(img.shape == (128,128,3)):
data.append(np.array(img))
result.append(encoder.transform([[0]]).toarray())
In the above step, we resized the image and converted those into NumPy array.Now let us follow the same steps and do it for the no Monkeypox folder.
Now provided Images without monkeypox
# This cell updates result list for images without Monkeypox
paths = []
for r, d, f in os.walk("C:\\Users\\vaibhav1.mali\\PycharmProjects\\Monkeypox_Dataset\\/Others"):
for file in f:
if '.jpg' in file:
paths.append(os.path.join(r, file))
for path in paths:
img = Image.open(path)
img = img.resize((128,128))
img = np.array(img)
if(img.shape == (128,128,3)):
data.append(np.array(img))
result.append(encoder.transform([[1]]).toarray())
Now let us check the shape of the data.
data = np.array(data)
print(data.shape)
result = np.array(result)
result = result.reshape(3462,2)
Now let's split the data into training and testing
x_train,x_test,y_train,y_test = train_test_split(data, result, test_size=0.2, shuffle=True, random_state=0)
MODEL BUILDING :
Batch normalization is a technique for training very deep neural networks that standardizes the inputs to a layer for each mini-batch. This has the effect of stabilizing the learning process and dramatically reducing the number of training epochs required to train deep networks.
For creating the model we are going to use a sequential model that we mostly use for CNN
model = Sequential()
model.add(Conv2D(32, kernel_size=(2, 2), input_shape=(128, 128, 3), padding = 'Same'))
model.add(Conv2D(32, kernel_size=(2, 2), activation ='relu', padding = 'Same'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(64, kernel_size = (2,2), activation ='relu', padding = 'Same'))
model.add(Conv2D(64, kernel_size = (2,2), activation ='relu', padding = 'Same'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(2, activation='softmax'))
model.compile(loss = "categorical_crossentropy", optimizer='Adamax', metrics=['accuracy'])
print(model.summary())
print(y_train.shape)
Let us now fit the data into my model
history = model.fit(x_train, y_train, epochs = 100, batch_size = 50, verbose = 1,validation_data = (x_test, y_test))
print(history)
Now Check For Model Accuracy
# Visualization of model accuracy
model_accuracy = pd.DataFrame()
model_accuracy['accuracy'] = history.history['accuracy']
model_accuracy['val_accuracy'] = history.history['val_accuracy']
plt.figure(figsize = (9, 6))
sns.lineplot(data = model_accuracy['accuracy'], label = 'Train')
sns.lineplot(data = model_accuracy['val_accuracy'], label = 'Test')
plt.title('Model accuracy', fontsize = 14)
plt.ylabel('Accuracy', fontsize = 14)
plt.xlabel('Epoch', fontsize = 14)
plt.legend()
plt.show()
Now Check For Model Loss
# Visualization of model loss
model_loss = pd.DataFrame()
model_loss['loss'] = history.history['loss']
model_loss['val_loss'] = history.history['val_loss']
plt.figure(figsize = (9, 6))
sns.lineplot(data = model_loss['loss'], label = 'Train')
sns.lineplot(data = model_loss['val_loss'], label = 'Test')
plt.title('Model loss', fontsize = 14)
plt.ylabel('Loss', fontsize = 14)
plt.xlabel('Epoch', fontsize = 14)
plt.legend()
plt.show()
y_pred = model.predict(x_test)
print(y_pred)
now let's check the model
def names(number):
if number==0:
return 'Its a Monkeypox'
else:
return 'No, Its not a Monkeypox'
let us now pass the image through the model and see the results. In the first process, we pass a Monkeypox image and check the model accuracy.
img = Image.open("C:\\Users\\vaibhav1.mali\\PycharmProjects\\Monkeypox_Dataset\\Monkey Pox\\M32_03.jpg")
x = np.array(img.resize((128,128)))
x = x.reshape(1,128,128,3)
res = model.predict_on_batch(x)
classification = np.where(res == np.amax(res))[1][0]
plt.imshow(img)
print(str(res[0][classification]*100) + '% Confidence This Is ' + names(classification))
99.50% Confidence This Is Its a Monkeypox
Now let us pass a No Monkeypox image into the model and check the accuracy.
img = Image.open("C:\\Users\\vaibhav1.mali\\PycharmProjects\\Monkeypox_Dataset\\Others\\NM07_01.jpg")
x = np.array(img.resize((128,128)))
x = x.reshape(1,128,128,3)
res = model.predict_on_batch(x)
classification = np.where(res == np.amax(res))[1][0]
plt.imshow(img)
print(str(res[0][classification]*100) + '% Confidence This Is ' + names(classification))
98.50% Confidence This Is No, Its not a Monkeypox
Saving the model
# Saving the model
model.save('model.h5')
Load the model and check the accuracy
# Loading the model
model_tuned_loaded = tf.keras.models.load_model('model.h5')
model_tuned_loaded.summary()
loss, acc=model_tuned_loaded.evaluate(x_test, y_test, verbose=2)
print(loss)
print(acc)
Loss :- 0.8014618754386902
Accuracy :- 0.8975468873977661
Now Check out the classification report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score, roc_auc_score, precision_score, recall_score, f1_score
y_pred=model.predict(x_test)
y_pred=np.argmax(y_pred, axis=1)
y_test=np.argmax(y_test, axis=1)
mylist = []
# Confusion Matrix
cm = confusion_matrix(y_test, y_pred)
print(cm)
# accuracy score
acc = accuracy_score(y_test, y_pred)
mylist.append(acc)
print(cm)
print(acc)
# Evaluation metrics
acc = accuracy_score(y_test, y_pred)
roc_auc = roc_auc_score(y_test, y_pred)
precision = precision_score(y_test, y_pred)
recall = recall_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)
print(pd.Series({"Accuracy": acc,
"ROC-AUC": roc_auc,
"Precision": precision,
"Recall": recall,
"F1-score": f1}).to_string())
We have given decent accuracy. So our model perform Well