# ---
# 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
# ---

# + [markdown] id="view-in-github"
# <a href="https://colab.research.google.com/github/RiturajSaha/Malaria-Detector-Application/blob/master/Malaria_Detector.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>

# + [markdown] id="AxaO8OLYIAX0"
# Importng Libraries

# + id="Z_K9lhKdB1ta" colab={"base_uri": "https://localhost:8080/", "height": 35} outputId="9973c6e3-b7ae-4206-f362-7cc32f10f5b5"
import numpy as np 
import pandas as pd
import os 
import cv2
import matplotlib.pyplot as plt 
import os
from PIL import Image
from keras.preprocessing.image import img_to_array
from keras.preprocessing.image import load_img
from keras.utils import np_utils
from tensorflow.python.keras.layers import Dense,Conv2D,Flatten,MaxPooling2D,GlobalAveragePooling2D,Activation,BatchNormalization,Dropout
from tensorflow.python.keras import Sequential,backend,optimizers

# + [markdown] id="a9SXe0ySITpn"
# Unzipping Dataset

# + id="TsvjrWNGT_B_"
from zipfile import ZipFile
file_name='/content/drive/My Drive/Colab Notebooks/Malaria Detector/mldataset.zip'
with ZipFile(file_name,'r') as zip:
          zip.extractall()

# + [markdown] id="2E8D87v6Iac6"
# Identifying Dependent and Independent Objects

# + id="d-8zz4TAVqjJ" colab={"base_uri": "https://localhost:8080/", "height": 52} outputId="c36a60e8-70bd-441b-f9fc-85f07e60200d"
parasitized_data = os.listdir('/content/mldataset/Parasitized')
uninfected_data = os.listdir('/content/mldataset/Uninfected/')
data = []
labels = []

for img in parasitized_data:
    try:
        img_read = plt.imread('/content/mldataset/Parasitized/' + img)
        img_resize = cv2.resize(img_read, (50, 50))
        img_array = img_to_array(img_resize)
        data.append(img_array)
        labels.append(1)
    except:
        None
        
for img in uninfected_data:
    try:
        img_read = plt.imread('/content/mldataset/Uninfected/' + img)
        img_resize = cv2.resize(img_read, (50, 50))
        img_array = img_to_array(img_resize)
        data.append(img_array)
        labels.append(0)
    except:
        None

image_data = np.array(data)
labels = np.array(labels)
print("image_data:",len(image_data))
print("labels:",len(labels))

# + [markdown] id="HxNoghL4IQTK"
# Data Visualization

# + id="SeI-FtbyT3ai" colab={"base_uri": "https://localhost:8080/", "height": 511} outputId="8492fb87-5df9-4242-de15-bc09a93eae85"
print("Parasitized Sample:\n")
plt.figure(figsize = (15,15))
for i in range(3):
    plt.subplot(4, 4, i+1)
    img = cv2.imread('/content/mldataset/Parasitized/'+ parasitized_data[i])
    plt.imshow(img)
plt.show()

print("Uninfected Sample:\n")
plt.figure(figsize = (15,15))
for i in range(3):
    plt.subplot(4, 4, i+1)
    img = cv2.imread('/content/mldataset/Uninfected/'+ uninfected_data[i])
    plt.imshow(img)
plt.show()

# + [markdown] id="VPFsBmD9IgRT"
# Dividng into train and test

# + id="KeFgC_oqV_nQ" colab={"base_uri": "https://localhost:8080/", "height": 87} outputId="09859c7f-d487-4a83-b5a6-0c7a52cce973"
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(image_data, labels, test_size = 0.2,random_state = 0)

y_train = np_utils.to_categorical(y_train, num_classes = 2)
y_test = np_utils.to_categorical(y_test, num_classes = 2)

print("X_train:",len(X_train))
print("X_test:",len(X_test))
print("y_train:",len(y_train))
print("y_test:",len(y_test))

# + [markdown] id="uvIuAxgMIvQt"
# Building the CNN model

# + id="Uru2WrqzWIyY" colab={"base_uri": "https://localhost:8080/", "height": 745} outputId="f063370b-9dd9-42a3-9e35-fbb072fb2726"
model = Sequential()
    
inputShape = (50, 50, 3)

if backend.image_data_format() == 'channels_first':
          inputShape = (3, 50, 50)
model.add(Conv2D(32, (3,3), activation = 'relu', input_shape = inputShape))
model.add(MaxPooling2D(2,2))
model.add(BatchNormalization(axis = -1))
model.add(Dropout(0.2))

model.add(Conv2D(32, (3,3), activation = 'relu'))
model.add(MaxPooling2D(2,2))
model.add(BatchNormalization(axis = -1))
model.add(Dropout(0.2))

model.add(Conv2D(32, (3,3), activation = 'relu'))
model.add(MaxPooling2D(2,2))
model.add(BatchNormalization(axis = -1))
model.add(Dropout(0.2))

model.add(Flatten())
    
model.add(Dense(512, activation = 'relu'))
model.add(BatchNormalization(axis = -1))
model.add(Dropout(0.5))
model.add(Dense(2, activation = 'softmax'))
    
model.summary()

# + [markdown] id="B3NBuKLrJOVZ"
# Compiling the model

# + id="qieD7ZErWNZe"
model.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy'])

# + [markdown] id="pl5mWgvxJZ5T"
# Fitting the model

# + id="ncKXN3QEWPtB" colab={"base_uri": "https://localhost:8080/", "height": 1000} outputId="f63cbaf7-74f6-40a0-f803-429e6c2d0572"
model.fit(X_train, y_train, epochs = 30, batch_size = 32)

# + [markdown] id="yBhqS3AYJnwO"
# Evaluating the model

# + id="LwJROPlkWSTe" colab={"base_uri": "https://localhost:8080/", "height": 69} outputId="72a98205-1535-48e7-fbe7-64c23e7ffa43"
predict = model.evaluate(X_test, y_test)
print("Loss: ",predict[0])
print("Accuracy: ",predict[1]*100)

# + [markdown] id="3mP1l8VKfqkV"
# Saving model

# + id="0DDVnynGhGiQ" colab={"base_uri": "https://localhost:8080/", "height": 763} outputId="d5aa7d69-103c-4e73-d7de-c59d5f6770dd"
# %cd "/content/drive/My Drive/Colab Notebooks/Malaria Detector"
model.save('malaria.h5')
from tensorflow.keras.models import load_model
model = load_model('malaria.h5')
model.summary()

StarcoderdataJupyterScriptsDedupFiltered