Neural Network for Pneumonia Detection Chest X-Ray Images¶
In [5]:
import tensorflow as tf
import numpy as np
import os
import sys
import cv2
import matplotlib.pyplot as plt
import pickle
import random
import pandas as pd
import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense,Dropout,Activation, Flatten,Conv2D,MaxPooling2D
import pickle
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
%matplotlib inline
In [3]:
class MasterImage(object):
def __init__(self,PATH='', IMAGE_SIZE = 50, CATEGORIES=[]):
self.PATH = PATH
self.IMAGE_SIZE = IMAGE_SIZE
self.CATEGORIES = CATEGORIES
self.image_data = []
self.x_data = []
self.y_data = []
def Process_Image(self):
"""
Return Numpy array of image
:return: X_Data, Y_Data
"""
for categories in self.CATEGORIES: # Iterate over categories
train_folder_path = os.path.join(self.PATH, categories) # Folder Path
class_index = self.CATEGORIES.index(categories) # this will get index for classification
for img in os.listdir(train_folder_path): # This will iterate in the Folder
new_path = os.path.join(train_folder_path, img) # image Path
try: # if any image is corrupted
image_data_temp = cv2.imread(new_path,cv2.IMREAD_GRAYSCALE) # Read Image as numbers
image_temp_resize = cv2.resize(image_data_temp,(self.IMAGE_SIZE,self.IMAGE_SIZE))
self.image_data.append([image_temp_resize,class_index])
except:
pass
data = np.asanyarray(self.image_data)
# Iterate over the Data
for x in data:
self.x_data.append(x[0]) # Get the X_Data
self.y_data.append(x[1]) # get the label
X_Data = np.asarray(self.x_data) / (255.0) # Normalize Data
Y_Data = np.asarray(self.y_data)
return X_Data,Y_Data
def pickle_image(self):
"""
:return: None Creates a Pickle Object of DataSet
"""
X_Data,Y_Data = self.Process_Image()
pickle_out = open('X_Data','wb')
pickle.dump(X_Data, pickle_out)
pickle_out.close()
pickle_out = open('Y_Data', 'wb')
pickle.dump(Y_Data, pickle_out)
pickle_out.close()
print("Pickled Image Successfully ")
return X_Data,Y_Data
def load_dataset(self):
try:
X_Temp = open('X_Data','rb')
X_Data = pickle.load(X_Temp)
Y_Temp = open('Y_Data','rb')
Y_Data = pickle.load(Y_Temp)
print('Reading Dataset from PIckle Object')
return X_Data,Y_Data
except:
print('Could not Found Pickle File ')
print('Loading File and Dataset ..........')
X_Data,Y_Data = self.pickle_image()
return X_Data,Y_Data
In [10]:
a = MasterImage(PATH='/Users/soumilshah/IdeaProjects/mytensorflow/Dataset/chest_xray/train',
IMAGE_SIZE=80,
CATEGORIES=['NORMAL','PNEUMONIA'])
X_Data,Y_Data = a.load_dataset()
X_Data = X_Data.reshape(-1,80,80,1)
print(X_Data.shape)
In [11]:
X_Train, X_Test, Y_Train, Y_Test = train_test_split(X_Data, Y_Data, test_size=0.3,random_state=101)
In [12]:
model = Sequential()
model.add(Conv2D(200, (3, 3), input_shape=X_Data.shape[1:]))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(100, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(80))
model.add(Dense(1))
model.add(Activation('sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])
In [13]:
model.fit(X_Data, Y_Data, batch_size=40, epochs=3, validation_split=0.3)
model.save('doc.model')
In [50]:
model.evaluate(X_Test,Y_Test,batch_size=40)
Out[50]:
In [ ]:
Test the DataSet¶
In [20]:
def prepare(filepath):
training_date = []
img_array = cv2.imread(filepath,cv2.IMREAD_GRAYSCALE)
new_array = cv2.resize(img_array,(80,80))
new_image = new_array.reshape(-1,80,80,1)
return new_image
In [21]:
model = tf.keras.models.load_model('doc.model')
In [29]:
filepath = '/Users/soumilshah/Downloads/NORMAL2-IM-1427-0001.jpeg'
img_array = cv2.imread(filepath)
plt.imshow(img_array)
Out[29]:
Lets See what our Network has to say¶
In [30]:
test = model.predict([prepare(filepath=filepath)])
In [31]:
CATEGORIES=['NORMAL','PNEUMONIA']
In [41]:
print(CATEGORIES[int(test[0][0])])
Great Lets Try Normal case¶
In [44]:
filepath = '/Users/soumilshah/Downloads/n.jpeg'
img_array = cv2.imread(filepath)
plt.imshow(img_array)
Out[44]:
In [48]:
test = model.predict([prepare(filepath=filepath)])
CATEGORIES=['NORMAL','PNEUMONIA']
print(CATEGORIES[int(test[0][0])])
No comments:
Post a Comment