-
Notifications
You must be signed in to change notification settings - Fork 6
/
pulmonary_chest_xray.py
226 lines (158 loc) · 6.57 KB
/
pulmonary_chest_xray.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
# -*- coding: utf-8 -*-
"""Pulmonary Chest XRay.ipynb
Automatically generated by Colaboratory.
"""
#Token and User Id hidden
!cp /content/.kaggle/kaggle.json ~/.kaggle/kaggle.json
!kaggle config set -n path -v{/content}
!chmod 600 /root/.kaggle/kaggle.json
!kaggle datasets download -d kmader/pulmonary-chest-xray-abnormalities -p /content
!unzip pulmonary-chest-xray-abnormalities.zip
!ls
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import os
import cv2
from sklearn.model_selection import train_test_split
from keras.utils import to_categorical
import keras
from keras import layers
from keras.models import Sequential
from keras.layers import Input,Dense,Conv2D,Activation,AveragePooling2D,BatchNormalization,MaxPooling2D,Dropout,Flatten
from keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
from keras.callbacks import ReduceLROnPlateau
import seaborn as sn
from keras.utils import plot_model
from sklearn.metrics import confusion_matrix,classification_report
from keras.models import Model
from keras.callbacks import ReduceLROnPlateau,ModelCheckpoint
from shutil import copyfile
!ls ChinaSet_AllFiles/
!ls Montgomery/MontgomerySet/CXR_png
files1 = os.listdir('ChinaSet_AllFiles/ChinaSet_AllFiles/CXR_png/')
files2 = os.listdir('Montgomery/MontgomerySet/CXR_png')
files1.remove('Thumbs.db')
files2.remove('Thumbs.db')
labels = []
paths = []
for i in files1:
i1 = i.split('_')[2]
labels.append(i1.split('.')[0])
paths.append('ChinaSet_AllFiles/ChinaSet_AllFiles/CXR_png/'+i)
for i in files2:
i1 = i.split('_')[2]
labels.append(i1.split('.')[0])
paths.append('Montgomery/MontgomerySet/CXR_png/'+i)
df = pd.DataFrame()
df['path'] = paths
df['label'] = labels
datagen = ImageDataGenerator(rescale = 1./255,validation_split = 0.2,horizontal_flip = True)
train = datagen.flow_from_dataframe(dataframe = df,x_col = 'path',y_col = 'label',target_size=(256,256),subset = 'training')
test = datagen.flow_from_dataframe(dataframe = df,x_col = 'path',y_col = 'label',target_size=(256,256),subset = 'validation',batch_size = 1)
os.mkdir('Pos')
os.mkdir('Neg')
os.mkdir('Data')
os.mkdir('Data/Pos')
os.mkdir('Data/Neg')
for i in files1:
i1 = i.split('_')[2]
labels.append(i1.split('.')[0])
if i1.split('.')[0]=='0':
copyfile('ChinaSet_AllFiles/ChinaSet_AllFiles/CXR_png/'+i,'Data/Neg/'+i)
else:
copyfile('ChinaSet_AllFiles/ChinaSet_AllFiles/CXR_png/'+i,'Data/Pos/'+i)
!ls Montgomery/MontgomerySet/
len(os.listdir('Data/Pos'))
img_in = Input((256,256,3))
x = Conv2D(filters=16, kernel_size=(3, 3), activation='relu', padding='same')(img_in)
x = Conv2D(filters=32, kernel_size=(3, 3), activation='relu', padding='same')(x)
x = Conv2D(filters=32, kernel_size=(3, 3), activation='relu', padding='same')(x)
x = BatchNormalization()(x)
x = MaxPooling2D(pool_size=(2, 2))(x)
x = Conv2D(filters=64, kernel_size=(3, 3), activation='relu', padding='same')(x)
x = Conv2D(filters=64, kernel_size=(3, 3), activation='relu', padding='same')(x)
x = Conv2D(filters=64, kernel_size=(3, 3), activation='relu', padding='same')(x)
x = BatchNormalization()(x)
x = MaxPooling2D(pool_size=(2, 2))(x)
x = Conv2D(filters=128, kernel_size=(4,4), activation='relu', padding='same')(x)
x = Conv2D(filters=128, kernel_size=(4,4), activation='relu', padding='same')(x)
x = Conv2D(filters=128, kernel_size=(4,4), activation='relu', padding='same')(x)
x = BatchNormalization()(x)
x = MaxPooling2D(pool_size=(2, 2))(x)
x = Flatten()(x)
x = Dense(units=1024, activation='relu')(x)
x = Dropout(rate=0.3)(x)
x = Dense(units=128, activation='relu')(x)
x = Dropout(rate=0.3)(x)
output = Dense(units=1, activation='sigmoid')(x)
model = Model(inputs=img_in, outputs=output)
model.compile(optimizer=keras.optimizers.Adam(0.0001), loss='binary_crossentropy', metrics=['accuracy'])
lr = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=2, verbose=2, mode='max')
mc = ModelCheckpoint('best_model4.h5',save_best_only = True)
from keras.utils import plot_model
plot_model(model,show_layer_names=False,show_shapes=True,dpi = 120)
train = datagen.flow_from_directory('Data',target_size=(256,256),class_mode = 'binary',subset = 'training')
test = datagen.flow_from_directory('Data',target_size=(256,256),class_mode = 'binary',subset = 'validation')
model.compile(optimizer=keras.optimizers.Nadam(0.00001), loss='binary_crossentropy', metrics=['accuracy'])
!ls
hist = model.fit_generator(train, epochs=10, validation_data=test, callbacks=[lr,mc])
model.load_weights('/content/drive/My Drive/best_model4.h5')
model.evaluate_generator(train)
test2 = datagen.flow_from_directory('Data',target_size=(256,256),class_mode = 'binary',shuffle=False)
model.evaluate_generator(test2)
preds = model.predict_generator(test2)
pred = []
for i in preds:
if i>0.45:
pred.append(1)
else:
pred.append(0)
print(classification_report(test2.classes,pred))
print(confusion_matrix(test2.classes,pred))
model = Sequential()
model.add(Conv2D(32,(3,3), activation ='relu',input_shape = (256,256,3)))
model.add(Conv2D(32, (3,3),activation ='relu'))
model.add(Conv2D(32, (3,3),activation ='relu'))
model.add(MaxPooling2D(pool_size = (2,2)))
model.add(Dropout(0.25))
model.add(Conv2D(64,(3,3), activation ='relu'))
model.add(Conv2D(64, (3,3),activation ='relu'))
model.add(Conv2D(64, (3,3),activation ='relu'))
model.add(MaxPooling2D(pool_size = (3,3)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(256, activation = "relu"))
model.add(Dropout(0.4))
model.add(Dense(64, activation = "relu"))
model.add(Dropout(0.4))
model.add(Dense(1, activation = "softmax"))
from sklearn.metrics import roc_curve
hist.history.keys()
plt.plot(hist.history['acc'])
plt.plot(hist.history['val_acc'])
plt.legend(['train','test'])
plt.plot(hist.history['loss'])
plt.plot(hist.history['val_loss'])
plt.legend(['train','test'])
fpr,tpr,_ = roc_curve(test.classes,pred)
plt.plot(fpr,tpr)
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC-AUC Curve')
plt.figure(figsize = (11,8))
plt.plot(fpr,tpr,label = 'Tuberculosis Prediction')
plt.plot([0,1],[0,1],'r--')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC-AUC Curve')
plt.legend(loc = 4)
cm = confusion_matrix(test2.classes,pred)
sn.set(font_scale = 2.5)
plt.figure(figsize = (11,8))
hm = sn.heatmap(cm,cmap = 'Blues_r',annot = True,xticklabels=['Normal','Tuberculosis'],yticklabels=['Normal','Tuberculosis'])
hm.set_yticklabels(rotation = 0,labels = hm.get_yticklabels())
model.summary()
from google.colab import drive
drive.mount('/content/drive')
!cp best_model4.h5 drive/My\ Drive