<reponame>anmolpant/Detecting-COVID-19-from-X-Ray
# -*- coding: utf-8 -*-
"""Covid 19 Prediction from X-Ray.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1yLlGEmSuWIu4HBAM129BV6pcNDFoHEdg
"""

!wget http://cb.lk/covid_19

!unzip covid_19

TRAIN_PATH = "CovidDataset/Train"
VAL_PATH = "CovidDataset/Val"

import numpy as np
import matplotlib.pyplot as plt
import keras
from keras.layers import *
from keras.models import *
from keras.preprocessing import image

# CNN Based Model in Keras

model = Sequential()
model.add(Conv2D(32, kernel_size=(3,3), activation='relu', input_shape = (224,224,3)))

model.add(Conv2D(64,(3,3),activation='relu'))  #5x5 ka filter using 2 Conv layers
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))

model.add(Conv2D(64,(3,3),activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))

model.add(Conv2D(128,(3,3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))

model.add(Flatten())
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))

model.add(Dense(1,activation='sigmoid'))

model.compile(loss=keras.losses.binary_crossentropy, optimizer='adam', metrics = ['accuracy'])

model.summary()

#Training from scratch

train_datagen = image.ImageDataGenerator(
    rescale = 1./255,
    shear_range = 0.2,
    zoom_range = 0.2,
    horizontal_flip = True,
)

test_dataset = image.ImageDataGenerator(rescale=1./255)

train_generator = train_datagen.flow_from_directory(
    'CovidDataset/Train',
    target_size = (224,224),
    batch_size = 32,
    class_mode='binary'
)

train_generator.class_indices

validation_generator = test_dataset.flow_from_directory(
    'CovidDataset/Val',
    target_size = (224,224),
    batch_size = 32,
    class_mode = 'binary'
)

hist = model.fit_generator(
    train_generator,
    steps_per_epoch = 8,
    epochs = 10,
    validation_data = validation_generator,
    validation_steps = 2
)

model.save("model_adv.h5")

model.evaluate_generator(train_generator)

model.evaluate_generator(validation_generator)

"""## Test Images"""

model = load_model('model_adv.h5')

import os

train_generator.class_indices

y_actual = []
y_test = []

for i in os.listdir("./CovidDataset/Val/Normal/"):
  img = image.load_img("./CovidDataset/Val/Normal/"+i, target_size=(224,224))
  img = image.img_to_array(img)
  img = np.expand_dims(img, axis=0)
  p = model.predict_classes(img)
  y_test.append(p[0,0])
  y_actual.append(1)

for i in os.listdir("./CovidDataset/Val/Covid/"):
  img = image.load_img("./CovidDataset/Val/Covid/"+i, target_size=(224,224))
  img = image.img_to_array(img)
  img = np.expand_dims(img, axis=0)
  p = model.predict_classes(img)
  y_test.append(p[0,0])
  y_actual.append(0)

y_actual = np.array(y_actual)
y_test = np.array(y_test)

from sklearn.metrics import confusion_matrix

cm = confusion_matrix(y_actual, y_test)

import seaborn as sns

sns.heatmap(cm, cmap="plasma", annot=True)

"""**True Positives:** All people having Covid-19 (30), have been correctly classified.

**False Negatives:** Patients that were positive but were classified as negative, we get a zero (0) in this column, indicating that our classifier did a good job in classifying patients who actually had COVID-19.

**True negatives:** Patients which were normal and were classified as normal, we get a value of 28 in this cell, indicating our classifier correctly diagnosed 28/30 people who didn't have COVID-19 as normal.

False Positives: Two normal patients were falsely classified as COVID +ve by our classifier.
;-;

A good classifier in this case, satisfies two parameters:


*   True positive and true negative should be high
*   False positive and false negative should be close to zero.

Our classifier does well on both these fronts and hence I am satisfied with its overall performance.
"""


# -*- coding: utf-8 -*-
"""Covid 19 Prediction from X-Ray.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1yLlGEmSuWIu4HBAM129BV6pcNDFoHEdg
"""

!wget http://cb.lk/covid_19

!unzip covid_19

TRAIN_PATH = "CovidDataset/Train"
VAL_PATH = "CovidDataset/Val"

import numpy as np
import matplotlib.pyplot as plt
import keras
from keras.layers import *
from keras.models import *
from keras.preprocessing import image

# CNN Based Model in Keras

model = Sequential()
model.add(Conv2D(32, kernel_size=(3,3), activation='relu', input_shape = (224,224,3)))

model.add(Conv2D(64,(3,3),activation='relu'))  #5x5 ka filter using 2 Conv layers
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))

model.add(Conv2D(64,(3,3),activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))

model.add(Conv2D(128,(3,3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))

model.add(Flatten())
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))

model.add(Dense(1,activation='sigmoid'))

model.compile(loss=keras.losses.binary_crossentropy, optimizer='adam', metrics = ['accuracy'])

model.summary()

#Training from scratch

train_datagen = image.ImageDataGenerator(
    rescale = 1./255,
    shear_range = 0.2,
    zoom_range = 0.2,
    horizontal_flip = True,
)

test_dataset = image.ImageDataGenerator(rescale=1./255)

train_generator = train_datagen.flow_from_directory(
    'CovidDataset/Train',
    target_size = (224,224),
    batch_size = 32,
    class_mode='binary'
)

train_generator.class_indices

validation_generator = test_dataset.flow_from_directory(
    'CovidDataset/Val',
    target_size = (224,224),
    batch_size = 32,
    class_mode = 'binary'
)

hist = model.fit_generator(
    train_generator,
    steps_per_epoch = 8,
    epochs = 10,
    validation_data = validation_generator,
    validation_steps = 2
)

model.save("model_adv.h5")

model.evaluate_generator(train_generator)

model.evaluate_generator(validation_generator)

"""## Test Images"""

model = load_model('model_adv.h5')

import os

train_generator.class_indices

y_actual = []
y_test = []

for i in os.listdir("./CovidDataset/Val/Normal/"):
  img = image.load_img("./CovidDataset/Val/Normal/"+i, target_size=(224,224))
  img = image.img_to_array(img)
  img = np.expand_dims(img, axis=0)
  p = model.predict_classes(img)
  y_test.append(p[0,0])
  y_actual.append(1)

for i in os.listdir("./CovidDataset/Val/Covid/"):
  img = image.load_img("./CovidDataset/Val/Covid/"+i, target_size=(224,224))
  img = image.img_to_array(img)
  img = np.expand_dims(img, axis=0)
  p = model.predict_classes(img)
  y_test.append(p[0,0])
  y_actual.append(0)

y_actual = np.array(y_actual)
y_test = np.array(y_test)

from sklearn.metrics import confusion_matrix

cm = confusion_matrix(y_actual, y_test)

import seaborn as sns

sns.heatmap(cm, cmap="plasma", annot=True)

"""**True Positives:** All people having Covid-19 (30), have been correctly classified.

**False Negatives:** Patients that were positive but were classified as negative, we get a zero (0) in this column, indicating that our classifier did a good job in classifying patients who actually had COVID-19.

**True negatives:** Patients which were normal and were classified as normal, we get a value of 28 in this cell, indicating our classifier correctly diagnosed 28/30 people who didn't have COVID-19 as normal.

False Positives: Two normal patients were falsely classified as COVID +ve by our classifier.
;-;

A good classifier in this case, satisfies two parameters:


*   True positive and true negative should be high
*   False positive and false negative should be close to zero.

Our classifier does well on both these fronts and hence I am satisfied with its overall performance.
"""
# -*- coding: utf-8 -*- Covid 19 Prediction from X-Ray.ipynb  Automatically generated by Colaboratory.  Original file is located at     https://colab.research.google.com/drive/1yLlGEmSuWIu4HBAM129BV6pcNDFoHEdg # CNN Based Model in Keras #5x5 ka filter using 2 Conv layers #Training from scratch ## Test Images **True Positives:** All people having Covid-19 (30), have been correctly classified.  **False Negatives:** Patients that were positive but were classified as negative, we get a zero (0) in this column, indicating that our classifier did a good job in classifying patients who actually had COVID-19.  **True negatives:** Patients which were normal and were classified as normal, we get a value of 28 in this cell, indicating our classifier correctly diagnosed 28/30 people who didn't have COVID-19 as normal.  False Positives: Two normal patients were falsely classified as COVID +ve by our classifier. ;-;  A good classifier in this case, satisfies two parameters:   *   True positive and true negative should be high *   False positive and false negative should be close to zero.  Our classifier does well on both these fronts and hence I am satisfied with its overall performance.