-
Notifications
You must be signed in to change notification settings - Fork 0
/
cnn_model (2).py
352 lines (252 loc) · 8.65 KB
/
cnn_model (2).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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
# -*- coding: utf-8 -*-
"""Cnn_model.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/gist/raaaouf/7eba4d9dcdcd30ea1023d8a923e612d4/cnn_model.ipynb
this project is hosted on google colab to try it jusy press on the open in colab link
# Dataset :
[Covid-19 data on github
](https://github.com/ieee8023/covid-chestxray-dataset)
[Normal data on kaggle](https://https://www.kaggle.com/paultimothymooney/chest-xray-pneumonia/data#)
# Libraries
"""
from keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.layers import AveragePooling2D
from tensorflow.keras.layers import Dropout
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Input
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.utils import to_categorical
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from imutils import paths
import tensorflow as tf
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten
from tensorflow.keras.layers import Conv2D, MaxPooling2D
import pickle
import matplotlib.pyplot as plt
import numpy as np
import argparse
import cv2
import os
from tqdm import tqdm
"""# Creat the Dataset"""
DATADIR = "dataset"
CATEGORIES = ["Covid", "NotCovid"]
# Just for test
for category in CATEGORIES:
path = os.path.join(DATADIR,category)
for img in os.listdir(path):
print(category,img, "\n")
img_array = cv2.imread(os.path.join(path,img))
plt.imshow(img_array) # graph it
plt.show() # display!
break
dataSet = []
IMG_SIZE = 224
def create_training_data():
for category in CATEGORIES:
path = os.path.join(DATADIR,category)
print(path)
class_num = CATEGORIES.index(category) # get the classification (0 or a 1). 0=Covid+ 1=Covid-
print(class_num)
for img in tqdm(os.listdir(path)):
try:
img_array = cv2.imread(os.path.join(path,img)) # convert to array
new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE)) # resize to normalize data size
dataSet.append([new_array, class_num]) # add this to our dataset
except Exception as e: # in the interest in keeping the output clean...
#except OSError as e:
print("OSErrroBad img most likely", e, os.path.join(path,img))
#except Exception as e:
print("general exception", e, os.path.join(path,img))
create_training_data()
print(len(dataSet))
import random
random.shuffle(dataSet)
for sample in dataSet[:10]:
print(sample[1])
# grab the list of images in our dataset directory, then initialize
# the list of data (i.e., images) and class images
X = []
y = []
for features,label in dataSet:
features = cv2.resize(features, (224, 224))
X.append(features)
y.append(label)
# y = np.array(label)
# X = np.array(X).reshape(IMG_SIZE, IMG_SIZE) / 255.0
# # X = np.array(X) / 255.0
# y = np.array(y)
# # X = X/255.0
X = np.array(X) / 255.0
y = np.array(y)
# X = X/255.0
"""### Create the *Training* and *Validation* datasets
---
"""
from sklearn.model_selection import train_test_split
(trainX, testX, trainY, testY) = train_test_split(X, y,
test_size=0.20, stratify=y, random_state=42)
y
trainY
import pickle
pickle_out = open("X.pickle","wb")
pickle.dump(X, pickle_out)
pickle_out.close()
pickle_out = open("y.pickle","wb")
pickle.dump(y, pickle_out)
pickle_out.close()
"""# Model settings"""
# initialize the training data augmentation object
trainAug = ImageDataGenerator(
rotation_range=15,
fill_mode="nearest")
INIT_LR = 1e-3
EPOCHS = 15
BS = 8
"""# Model1:"""
# 2ed Model
nClasses = 2
model2 = Sequential()
model2.add ( Conv2D ( 32 , ( 3 , 3 ), padding= 'same' , activation= 'relu'))
model2.add ( Conv2D ( 32 , ( 3 , 3 ), activation= 'relu' ))
model2.add ( MaxPooling2D ( pool_size= ( 2 , 2 )))
model2.add ( Dropout ( 0.5 ))
model2.add ( Conv2D ( 64 , ( 3 , 3 ), padding= 'same' , activation= 'relu' ))
model2.add ( Conv2D ( 64 , ( 3 , 3 ), activation= 'relu' ))
model2.add ( MaxPooling2D ( pool_size= ( 2 , 2 )))
model2.add ( Dropout ( 0.5 ))
model2.add ( Conv2D ( 64 , ( 3 , 3 ), padding= 'same' , activation= 'relu' ))
model2.add ( Conv2D ( 64 , ( 3 , 3 ), activation= 'relu' ))
model2.add ( MaxPooling2D ( pool_size= ( 2 , 2 )))
model2.add ( Dropout ( 0.5 ))
model2.add ( Flatten ())
model2.add ( Dense ( 512 , activation= 'sigmoid' ))
model2.add ( Dropout ( 0.4 ))
model2.add ( Dense ( nClasses , activation= 'sigmoid'))
opt = Adam(lr=INIT_LR, decay=INIT_LR / EPOCHS)
model2.compile(loss="binary_crossentropy", optimizer=opt,
metrics=["accuracy"])
history2 = model2.fit_generator(
trainAug.flow(trainX, trainY, batch_size=BS),
steps_per_epoch=len(trainX) // BS,
validation_data=(testX, testY),
validation_steps=len(testX),
epochs=EPOCHS)
"""# Model 2:"""
model = Sequential()
model.add(Conv2D(256, (3, 3), input_shape=X.shape[1:]))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(256, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten()) # this converts our 3D feature maps to 1D feature vectors
model.add(Dense(64))
model.add(Dense(1))
model.add(Activation('sigmoid'))
opt = Adam(lr=INIT_LR, decay=INIT_LR / 20)
model.compile(loss="binary_crossentropy", optimizer=opt,
metrics=["accuracy"])
history1 = model.fit_generator(
trainAug.flow(trainX, trainY, batch_size=BS),
steps_per_epoch=len(trainX) // BS,
validation_data=(testX, testY),
validation_steps=len(testX),
epochs=20)
"""# Testing & Prediction"""
# *** TO DO : testing & Prediction
import matplotlib.pyplot as plt
from sklearn.metrics import classification_report
# make predictions on the testing set
predIdxs = model.predict(testX, batch_size=BS)
testY
# Prediction
import random
import cv2
try:
from google.colab.patches import cv2_imshow
except Exception:
def cv2_imshow(mat):
return cv2.imshow('img', mat)
def url_to_image(url):
from skimage import io
return cv2.cvtColor(io.imread(url), cv2.COLOR_BGR2RGB)
def convertData(image):
img = image.astype('float32')
img /= 255
c = np.zeros(224*224*3).reshape((1,224,224,3))
c[0] = img
return c
_labels = np.array([
'PosCovid-19', # class 0
'NegCovid-19'])# class 1
def CasePrediction(url):
img = url_to_image(url)
img = resized = cv2.resize(img, (224,224))
plt.figure(figsize=(16,16))
data = convertData(img)
plt.imshow(img)
ret = model.predict(data, batch_size=BS)
bestnum = 0.0
bestclass = 0
if ret[0] < 0.5:
bestclass = 0
else :
bestclass = 1
plt.title(_labels[bestclass])
plt.show()
# Pos Ex.
urlp = 'https://a.top4top.io/p_15402pp5p3.png'
# Neg Ex.
urln = 'https://k.top4top.io/p_1540g20th1.jpeg'
CasePrediction(urlp)
CasePrediction(urln)
"""# Ploting"""
history1.history.keys()
import matplotlib.pyplot as plt
print("Model : 1")
plt.style.use("ggplot")
plt.figure()
plt.plot(history1.history['acc'], label='Training accuracy')
plt.plot(history1.history['val_acc'], label='Validation accuracy')
plt.plot(history1.history['loss'], label='Training loss')
plt.plot(history1.history['val_loss'], label='Validation loss')
plt.xlim(left=1)
plt.ylim(top=1.1)
plt.legend()
plt.show()
print("Model : 2")
plt.style.use("ggplot")
plt.figure()
plt.plot(history2.history['acc'], label='Training accuracy')
plt.plot(history2.history['val_acc'], label='Validation accuracy')
plt.plot(history2.history['loss'], label='Training loss')
plt.plot(history2.history['val_loss'], label='Validation loss')
plt.xlim(left=1)
plt.ylim(top=1.1)
plt.legend()
plt.show()
# To Do: Fix
"optionnal: confusion matrix"
"""# Model 3"""
# TO DO: try this model
img_width = 224
img_height = 224
epochs = 100
base_model = tf.keras.applications.MobileNet(weights='imagenet', include_top=False,
input_shape=(img_width, img_height, 3))
output = tf.keras.layers.GlobalAveragePooling2D()(base_model.output)
output = tf.keras.layers.Dense(2, activation='softmax')(output)
model1 = tf.keras.Model(inputs=base_model.input, outputs=output)
model1.compile(optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss='categorical_crossentropy', metrics=['accuracy'])
model1.summary()