# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     name: python3
# ---

# + colab={"base_uri": "https://localhost:8080/"} id="1oK7ivgft4ss" outputId="f7b1a05d-d0f4-4a60-8f78-6f4d7eee4c77"
# Dataset : https://cb.lk/covid_19

# !wget https://cb.lk/covid_19

# + colab={"base_uri": "https://localhost:8080/"} id="HjSGvC6hv6JY" outputId="6cf4dd30-b3f0-4fb8-de29-95be3fc2f64d"
# !unzip covid_19

# + id="xAqGYAjpx10D"
TRAIN_PATH = "CovidDataset/Train"
TEST_PATH = "CovidDataset/Val"



# + id="g_oVYpRczIql"
import numpy as np
import matplotlib.pyplot as plt
import keras
from keras.layers import *
from keras.models import *
from keras.preprocessing import image


# + id="owk9DwhJzyI5"
# 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'))
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'])

# + colab={"base_uri": "https://localhost:8080/"} id="NQgrrWGF8Y8V" outputId="38a71fe1-88ce-4c31-cd45-1202ff00b5fb"
model.summary()

# + id="CvO6hJCc-qRj"
# Train from scratch
train_datagen = image.ImageDataGenerator(
    rescale = 1./255, # Normalise the to converge
    shear_range = 0.2,
    zoom_range = 0.2,
    horizontal_flip = True,
)

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

# + colab={"base_uri": "https://localhost:8080/"} id="DB2qcsAH_97G" outputId="ce8097ca-ce6c-4a34-e35b-4842a6afc4c1"
train_generator = train_datagen.flow_from_directory(
    'CovidDataset/Train',
    target_size = (224,224),
    batch_size = 32,
    class_mode = 'binary')

# + colab={"base_uri": "https://localhost:8080/"} id="6KRt1BcSBNWy" outputId="c499be9f-1a05-4a7d-cca3-e35bae43dfbc"
train_generator.class_indices

# + colab={"base_uri": "https://localhost:8080/"} id="Ct0Ugr_0BQ_r" outputId="6d11d433-6178-47f9-eee6-f97d0a7046cb"
validation_generator = test_datagen.flow_from_directory(
    'CovidDataset/Val',
    target_size = (224,224),
    batch_size = 32,
    class_mode = 'binary')

# + colab={"base_uri": "https://localhost:8080/"} id="CTgmI-2hDFgP" outputId="ccb469db-ac71-4365-c8ca-e753a9f00bb2"
hist = model.fit_generator(
    train_generator,
    steps_per_epoch=6,
    epochs = 10,
    validation_data = validation_generator,
    validation_steps = 2
)

# + id="AwV7k1sWTZ5k"
# Class Activation Maps  
# Grad-CAM both used to visualize the how a network is differentiating feature 

# + [markdown] id="2n0nv4NScOP3"
# # Loss is very small and decreasing 

# + id="YC1N-flUTd44"
model.save("model_adv.h5")

# + colab={"base_uri": "https://localhost:8080/"} id="TDHkMQfOVVTq" outputId="725e4a13-dc24-44c3-f3dd-6bc2fa425315"
model.evaluate_generator(train_generator)

# + colab={"base_uri": "https://localhost:8080/"} id="l3T6VKjqVrAj" outputId="b8f0d90b-15f4-4d4c-eb56-2f6b1fce2107"
model.evaluate_generator(validation_generator)

# + [markdown] id="W1vCQwwTWWpC"
# # **Test Image With Confusion Metrics**

# + id="zg7vh-OhWe5j"
model = load_model('model_adv.h5')

# + id="FNt4V-UBWuLu"
import os

# + colab={"base_uri": "https://localhost:8080/"} id="GZocl7IWWv_X" outputId="e912d139-882f-4fe0-8c83-f75685337323"
train_generator.class_indices

# + id="tnq-2ZpQW1Du"
y_actual = []
y_test = []

# + id="ooQK_ejKXBCj" colab={"base_uri": "https://localhost:8080/", "height": 195} outputId="6bf9998b-5ac1-4174-88d5-ee557f978d4b"
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)
  predict_x=model.predict(img) 
  classes_x=np.argmax(predict_x,axis=1)
  y_test.append(predict_x[0,0])
  y_actual(1)


StarcoderdataJupyterScriptsDedupFiltered