-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
COV19-CT-DB-CNN-model.py
160 lines (127 loc) · 4.5 KB
/
COV19-CT-DB-CNN-model.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 23 21:29:01 2021
@author: idu
"""
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 7 00:28:03 2021
@author: idu
"""
import os, glob
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow import keras
from keras import backend as K
from tensorflow.keras.optimizers import Adam
from keras import layers, models
from tensorflow.keras import activations
####### Generatiiing Data
#batch_size = 32
#batch_size = 64
batch_size = 128
SIZE = 512
train_datagen = ImageDataGenerator(rescale=1./255)
#Change the training path '/home/idu/Desktop/COV19D/train/' to where your training set's directory is
train_generator = train_datagen.flow_from_directory(
'/home/idu/Desktop/COV19D/train/', ## COV19-CT-DB Training set (335672 Images)
target_size=(SIZE, SIZE),
batch_size=batch_size,
color_mode='grayscale',
classes = ['covid','non-covid'],
class_mode='binary')
val_datagen = ImageDataGenerator(rescale=1./255)
# Change the training path '/home/idu/Desktop/COV19D/validation/' to where your validaiton set's directory is
val_generator = val_datagen.flow_from_directory(
'/home/idu/Desktop/COV19D/validation/', ## COV19-CT-DB Validation set (75532 images)
target_size=(SIZE, SIZE),
batch_size=batch_size,
color_mode='grayscale',
classes = ['covid','non-covid'],
class_mode='binary')
################ CNN Model Architecture
def make_model():
model = models.Sequential()
# Convulotional Layer 1
model.add(layers.Conv2D(16,(3,3),input_shape=(SIZE,SIZE,1), padding="same"))
model.add(layers.BatchNormalization())
model.add(layers.ReLU())
model.add(layers.MaxPooling2D((2,2)))
# Convulotional Layer 2
model.add(layers.Conv2D(32,(3,3), padding="same"))
model.add(layers.BatchNormalization())
model.add(layers.ReLU())
model.add(layers.MaxPooling2D((2,2)))
# Convulotional Layer 3
model.add(layers.Conv2D(64,(3,3), padding="same"))
model.add(layers.BatchNormalization())
model.add(layers.ReLU())
model.add(layers.MaxPooling2D((2,2)))
# Convulotional Layer 4
model.add(layers.Conv2D(128,(3,3), padding="same"))
model.add(layers.BatchNormalization())
model.add(layers.ReLU())
model.add(layers.MaxPooling2D((2,2)))
# Fully Connected Layer
model.add(layers.Flatten())
model.add(layers.Dense(256))
model.add(layers.BatchNormalization())
model.add(layers.ReLU())
model.add(layers.Dropout(0.1))
# Dense Layer
model.add(layers.Dense(1,activation='sigmoid'))
return model
model = make_model()
###################################### Compiling and Training the model
n_epochs= 70
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=[tf.keras.metrics.Precision(),tf.keras.metrics.Recall(),'accuracy'])
history=model.fit(train_generator,
steps_per_epoch=250,
validation_data=val_generator,
validation_steps=78,
verbose=2,
epochs=n_epochs)
######################## Evaluating
print (history.history.keys())
Train_accuracy = history.history['accuracy']
print(Train_accuracy)
print(np.mean(Train_accuracy))
val_accuracy = history.history['val_accuracy']
print(val_accuracy)
print( np.mean(val_accuracy))
epochs = range(1, len(Train_accuracy)+1)
plt.figure(figsize=(12,6))
plt.plot(epochs, Train_accuracy, 'g', label='Training acc')
plt.plot(epochs, val_accuracy, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.xlabel('Epochs')
plt.ylabel('accuracy')
plt.ylim(0.45,1)
plt.xlim(0,50)
plt.legend()
plt.show()
val_recall = history.history['val_recall']
print(val_recall)
avg_recall = np.mean(val_recall)
avg_recall
val_precision = history.history['val_precision']
avg_precision = np.mean(val_precision)
avg_precision
epochs = range(1, len(Train_accuracy)+1)
plt.figure(figsize=(12,6))
plt.plot(epochs, val_recall, 'g', label='Validation Recall')
plt.plot(epochs, val_precision, 'b', label='Validation Prcision')
plt.title('Validation recall and Validation Percision')
plt.xlabel('Epochs')
plt.ylabel('Recall and Precision')
plt.legend()
plt.ylim(0,1)
plt.show()
Macro_F1score = (2*avg_precision*avg_recall)/ (avg_precision + avg_recall)
Macro_F1score