-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCOVID-19-Prediction.py
207 lines (145 loc) · 5.97 KB
/
COVID-19-Prediction.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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# -*- coding: utf-8 -*-
"""COVID-19 Prediction.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1oeA2Rp5B_8VWtOXEoY7R4dQMaO4pZe_y
# 1) IMPORTING LIBRARIES
"""
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPool2D,Dropout, Flatten, Dense
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
"""# 2) CLONING DATASET"""
# CLONING THE DATASET FROM THE GITHUB REPOSITORY
!git clone https://github.com/RishitToteja/Chext-X-ray-Images-Data-Set.git
import os
main_dir = "/content/Chext-X-ray-Images-Data-Set/DataSet/Data"
# SETTING TRAIN AND TEST DIRECTORY
train_dir = os.path.join(main_dir, "train")
test_dir = os.path.join(main_dir, "test")
#SETING DIRECTORY FOR COVID AND NORMAL IMAGES DIRECTORY
train_covid_dir = os.path.join(train_dir, "COVID19")
train_normal_dir = os.path.join(train_dir, "NORMAL")
test_covid_dir = os.path.join(test_dir, "COVID19")
test_normal_dir = os.path.join(test_dir, "NORMAL")
# MAKING SEPERATE FILES :
train_covid_names = os.listdir(train_covid_dir)
train_normal_names = os.listdir(train_normal_dir)
test_covid_names = os.listdir(test_covid_dir)
test_normal_names = os.listdir(test_normal_dir)
"""# 3) PERFORMING DATA VISUALIZATION
"""
import matplotlib.image as mpimg
rows = 4
columns = 4
fig = plt.gcf()
fig.set_size_inches(12,12)
covid_img = [os.path.join(train_covid_dir, filename) for filename in train_covid_names[0:8]]
normal_img = [os.path.join(train_normal_dir, filename) for filename in train_normal_names[0:8]]
print(covid_img)
print(normal_img)
merged_img = covid_img + normal_img
for i, img_path in enumerate(merged_img):
title = img_path.split("/", 6)[6]
plot = plt.subplot(rows, columns, i+1)
plot.axis("Off")
img = mpimg.imread(img_path)
plot.set_title(title, fontsize = 11)
plt.imshow(img, cmap= "gray")
plt.show()
"""# 4) DATA PREPROCESSING AND AUGMENTATION"""
# CREATING TRAINING, TESTING AND VALIDATION BATCHES
dgen_train = ImageDataGenerator(rescale = 1./255,
validation_split = 0.2,
zoom_range = 0.2,
horizontal_flip = True)
dgen_validation = ImageDataGenerator(rescale = 1./255,
)
dgen_test = ImageDataGenerator(rescale = 1./255,
)
train_generator = dgen_train.flow_from_directory(train_dir,
target_size = (150, 150),
subset = 'training',
batch_size = 32,
class_mode = 'binary')
validation_generator = dgen_train.flow_from_directory(train_dir,
target_size = (150, 150),
subset = "validation",
batch_size = 32,
class_mode = "binary")
test_generator = dgen_test.flow_from_directory(test_dir,
target_size = (150, 150),
batch_size = 32,
class_mode = "binary")
print("Class Labels are: ", train_generator.class_indices)
print("Image shape is : ", train_generator.image_shape)
"""# 5) BUILDING CONVOLUTIONAL NEURAL NETWORK MODEL"""
from tensorflow.keras.layers import Conv2D, MaxPooling2D
model = Sequential()
# 1) CONVOLUTIONAL LAYER - 1
model.add(Conv2D(32, (5,5), padding = "same", activation = "relu", input_shape = train_generator.image_shape))
# 2) POOLING LAYER - 1
model.add(MaxPooling2D(pool_size=(2,2)))
# 3) DROPOUT LAYER -2
model.add(Dropout(0.5))
# 4) CONVOLUTIONAL LAYER - 2
model.add(Conv2D(64, (5,5), padding = "same", activation = "relu"))
# 5) POOLING LAYER - 2
model.add(MaxPooling2D(pool_size=(2,2)))
# 6) DROPOUT LAYER - 2
model.add(Dropout(0.5))
# 7) FLATTENING LAYER TO 2D SHAPE
model.add(Flatten())
# 8) ADDING A DENSE LAYER
model.add(Dense(256, activation = 'relu'))
# 9 DROPOUT LAYER - 3
model.add(Dropout(0.5))
# 10) FINAL OUTPUT LAYER
model.add(Dense(1, activation = 'sigmoid'))
### PRINTING MODEL SUMMARY
model.summary()
"""# 6) COMPILING AND TRAINING THE NEURAL NETWORK MODEL"""
# COMPILING THE MODEL
model.compile(Adam(learning_rate = 0.001), loss = 'binary_crossentropy', metrics = ['accuracy'])
# TRAINING THE MODEL
history = model.fit(train_generator,
epochs = 35,
validation_data = validation_generator)
"""# 7) PERFORMING EVALUATION
"""
# KEYS OF HISTORY OBJECT
history.history.keys()
# PLOT GRAPH BETWEEN TRAINING AND VALIDATION LOSS
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.legend(['Training', 'Validation'])
plt.title("Training and validation losses")
plt.xlabel('epoch')
# PLOT GRAPH BETWEEN TRAINING AND VALIDATION ACCURACY
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.legend(['Training', 'Validation'])
plt.title("Training and validation accuracy")
plt.xlabel('epoch')
# GETTING TEST ACCURACY AND LOSS
test_loss, test_acc = model.evaluate(test_generator)
print("Test Set Loss : ", test_loss)
print("Test Set Accuracy : ", test_acc)
"""# 9) PREDICTION ON NEW DATA (UPLOAD FILES)"""
from google.colab import files
from keras.preprocessing import image
uploaded = files.upload()
for filename in uploaded.keys():
img_path = '/content/' + filename
img = image.load_img(img_path, target_size = (150,150))
images = image.img_to_array(img)
images = np.expand_dims(images, axis = 0)
prediction = model.predict(images)
if prediction == 0:
print("The report is COVID-19 Positive")
else:
print("The report is COVID-19 Negative")
model.save("my_model.h5")