Multi Classification Covid and Pneumonia Model with TensorFlow and CNN.
This is Multi Classification Model using CNN, Python and TensorFlow. It was trained using the following Kaggle Dataset which has more than 300 X-Rays Images. The Model classifies if a person has Viral Pneumonia, Covid-19 or none of them, by checking their X-Ray, since there are only 3 possible classes, the softmax activation function is going to be used at the last output neuron.
Module Need
- TensorFlow
import tensorflow as tf
The X-Ray Images are going to be loaded with the ImageDataGenerator tool from the Keras API, with a weight and height of 256x256 pixels and a Batch Size of 8.
BATCH_SIZE = 8
PIC_SIZE = 256
train_data = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1/255, rotation_range=20, width_shift_range = 0.1, height_shift_range = 0.1, shear_range= 15, zoom_range= [0.5, 1.5])
validation_data = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1/255)
train = train_data.flow_from_directory("./Covid19-dataset/train", target_size=(PIC_SIZE,PIC_SIZE), batch_size=BATCH_SIZE, class_mode="categorical", color_mode='grayscale')
validation = validation_data.flow_from_directory("./Covid19-dataset/test", target_size=(PIC_SIZE,PIC_SIZE), batch_size=BATCH_SIZE, class_mode="categorical", color_mode='grayscale')
Model Structure
Structure of the Model using CNN and with the softmax activation function at the last neuron:
model = tf.keras.Sequential()
model.add(tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(PIC_SIZE, PIC_SIZE, 1), kernel_initializer = "he_normal", strides=1,
padding='same'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=(3, 3), strides=(3, 3), padding="same"))
model.add(tf.keras.layers.Conv2D(64, (3,3), activation='relu', kernel_regularizer = tf.keras.regularizers.l2(0.01), kernel_initializer = "he_normal", strides=1,
padding='same'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=(3, 3), strides=(3, 3), padding="same"))
model.add(tf.keras.layers.Conv2D(128, (3,3), activation='relu', kernel_regularizer = tf.keras.regularizers.l2(0.01), kernel_initializer = "he_normal", strides=1,
padding='same'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=(3, 3), strides=(3, 3), padding="same"))
model.add(tf.keras.layers.Dropout(0.5))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(512, activation='relu', kernel_regularizer = tf.keras.regularizers.l2(0.01), kernel_initializer = "he_normal"))
model.add(tf.keras.layers.Dropout(0.5))
model.add(tf.keras.layers.Dense(256, activation='relu', kernel_regularizer = tf.keras.regularizers.l2(0.01), kernel_initializer = "he_normal"))
model.add(tf.keras.layers.Dropout(0.4))
model.add(tf.keras.layers.Dense(64, activation='relu', kernel_regularizer = tf.keras.regularizers.l2(0.01), kernel_initializer = "he_normal"))
model.add(tf.keras.layers.Dropout(0.1))
model.add(tf.keras.layers.Dense(3, activation='softmax'))
Compiling and Training the Model
The model was compiled using the Categorical Crossentropy Loss, Nadam as an optimizer with a Learning Rate of 0.001, and training during 40 epochs.
model.compile(
optimizer=tf.keras.optimizers.experimental.Nadam(learning_rate=0.001),
loss=tf.keras.losses.CategoricalCrossentropy(),
metrics=['acc']
)
history = model.fit(train,
epochs=40,
validation_data=validation)
Testing
The Model has 80% Accuracy.
test_img = tf.keras.preprocessing.image.load_img("./0102.JPEG", target_size=(256, 256), color_mode='grayscale')
plt.imshow(test_img)
X = tf.keras.preprocessing.image.img_to_array(test_img)
X = np.expand_dims(X, axis = 0)
prediction = np.vstack([X])
result = model.predict(prediction)
print(result)
arg_max_result = np.argmax(result)
if arg_max_result == 0 :
print("The Patient has Covid")
elif arg_max_result == 1 :
print("The Patient has a Normal X-Ray")
elif arg_max_result == 2 :
print("The Patient has Viral Pneumonia")