-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
153 lines (114 loc) · 4.63 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
"""
Problem Statement - The normal chest X-ray (left panel) depicts clear lungs without any areas of abnormal opacification (opaque/cloudy)
in the image. Bacterial pneumonia (middle) typically exhibits a focal lobar consolidation, in this case in the right upper lobe
(white arrows), whereas viral pneumonia (right) manifests with a more diffuse ‘‘interstitial’’ pattern in both lungs.
"""
# Importing Libraries
import numpy
import os
import random
import pandas as pd
import warnings
import matplotlib.pyplot as plt
import seaborn as sns
import cv2 as cv
from keras import backend as bknd
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Activation, Conv2D, MaxPool2D, Flatten, Dense, Dropout
warnings.filterwarnings("ignore")
# Base directory of dataset
base_dir = r'E:\Kaggle\Notebooks\Chest_X_Ray_Pneumonia\Dataset\chest_xray'
# Train, Test , Val dataset
train_dir = base_dir + r'\train'
test_dir = base_dir + r'\test'
val_dir = base_dir + r'\val'
# Categories location
normal_case_train = train_dir + r'\NORMAL'
pneumonia_case_train = train_dir + r'\PNEUMONIA'
# Read random training image
print("Random normal images : ")
for _ in range(3):
random_img = random.choice(os.listdir(normal_case_train))
print(random_img)
img_path = os.path.join(normal_case_train, random_img)
img_sample = cv.imread(img_path)
height, width, channels = img_sample.shape
print("Image size : ",(width, height, channels))
plt.figure()
plt.imshow(img_sample)
# Count Plot for both classes [NORMAL & PNEUMONIA]
# Creating DataFrame
train_df = []
# Assigning 0 to normal case
for img in os.listdir(normal_case_train):
train_df.append((img, 0))
for img in os.listdir(pneumonia_case_train):
train_df.append((img, 1))
train_df = pd.DataFrame(train_df, columns=['Image', 'Label'], index = None)
# Random shuffling complete dataset
train_df = train_df.sample(frac=1).reset_index(drop=True)
cnt_plt = sns.countplot(train_df.Label)
cnt_plt.set_title("Count of Positive (0) and Negative Cases (1)")
print(train_df.shape)
print(train_df.head())
# Data Augumentation
img_width, img_height = 250, 250
batch_size=20
epochs = 50
nb_val_samples = 1000
# Image shape
if bknd.image_data_format == "channels_first":
input_shape = (3, img_width, img_height)
else:
input_shape = (img_width, img_height, 3)
train_datagen = ImageDataGenerator(rescale=1./255,
shear_range = 0.2,
zoom_range=0.2,
horizontal_flip=True)
val_datagen = ImageDataGenerator(rescale=1./255,
shear_range = 0.2,
zoom_range=0.2,
horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)
# Apply on data
train_generator = train_datagen.flow_from_directory(train_dir, target_size=(img_width, img_height),
batch_size=batch_size,class_mode='binary')
val_generator = val_datagen.flow_from_directory(val_dir, target_size=(img_width, img_height),
batch_size=batch_size,class_mode='binary')
test_generator = test_datagen.flow_from_directory(test_dir, target_size=(img_width, img_height),
batch_size=batch_size,class_mode='binary')
# Model Building
"""
Steps:
1. Initializing the ConvNet
2. Define by adding layers
3. Compiling the model
4. Fit/Train model
"""
# Initialize model
model = Sequential()
# Defining model
model.add(Conv2D(32, kernel_size=(3,3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Conv2D(32, (3,3)))
model.add(Activation('relu'))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Conv2D(64, (3,3)))
model.add(Activation('relu'))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dropout(1))
model.add(Activation('sigmoid'))
model.summary()
# Compiling the model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# Training
model.fit(train_generator, steps_per_epochs=train_df.shape[0]//batch_size, epochs=epochs,
validation_data=val_generator, validation_steps=nb_val_samples//batch_size)
test_accuracy = model.evaluate_generator(test_generator)
print("The accuracy on test set : ", test_accuracy[1] * 100)