/
breastCancerClassification.py
321 lines (237 loc) · 9.28 KB
/
breastCancerClassification.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
import os
import cv2
import glob
import numpy as np
import pandas as pd
import time
import sklearn.utils
import matplotlib.pyplot as plt
import random
import fnmatch
import seaborn as sns
from imutils import paths
from sklearn.model_selection import train_test_split
from keras.utils.np_utils import to_categorical
from sklearn.metrics import accuracy_score
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
import itertools
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D
from keras.optimizers import RMSprop
from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import ReduceLROnPlateau
import warnings
# IGNORE WARNINGS
warnings.filterwarnings("ignore")
seconds = time.time()
time_start = time.ctime(seconds) # The time.ctime() function takes seconds passed as an argument and returns a string representing time.
print("start time:", time_start,"\n")
images =[]
imagePatches = glob.glob('E:\\ML assignments\\datasets\\BreaKHis_v1\\histology_slides\\breast\\**\\*.png', recursive=True)
'''
#sample imagePaths
for filename in imagePatches[0:30]:
images.append(filename)
#print(filename)
# PLOTTING an IMAGE
def plotImage(image_location):
image = cv2.imread(image_name)
image = cv2.resize(image,(200,200))
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
cv2.imshow("image",image)
return
image_name='E:\\ML assignments\\datasets\\BreaKHis_v1\\histology_slides\\breast\\benign\\SOB\\adenosis\\SOB_B_A_14-22549AB\\40X\\SOB_B_A-14-22549AB-40-001.png'
#plotImage(image_name)
'''
pattern_benign = '*benign*'
pattern_malignant = '*malignant*'
benign_class = fnmatch.filter(imagePatches, pattern_benign)
malignant_class = fnmatch.filter(imagePatches, pattern_malignant)
print("benign_class\n\n",benign_class[0:2],'\n')
print("malignant_class\n\n",malignant_class[0:2],'\n')
def proc_images(lowerIndex,upperIndex):
"""
Returns two arrays:
x is an array of resized images
y is an array of labels
"""
x = []
y = []
WIDTH = 100
HEIGHT = 100
for img in imagePatches[lowerIndex:upperIndex]:
full_size_image = cv2.imread(img)
x.append(cv2.resize(full_size_image, (WIDTH,HEIGHT), interpolation=cv2.INTER_CUBIC))
if img in benign_class:
y.append(0) # benign = 0
elif img in malignant_class:
y.append(1) # malignant = 1
else:
return
return x,y
X,Y = proc_images(0,7909)
#dataset=pd.DataFrame({"images":X,"labels":Y})
#dataset.to_csv("new_dataset.csv")
df = pd.DataFrame()
df["images"] = X
df["labels"] = Y
X2 = df["images"]
Y2 = df["labels"]
X2 = np.array(X2)
imgs_benign = []
imgs_malignant = []
imgs_benign = X2[Y2==0] # benign = 0
imgs_malignant = X2[Y2==1] # malignant = 1
def describeData(a,b):
print('Total number of images: {}'.format(len(X2)))
print('Number of benign Images: {}'.format(np.sum(Y2==0)))
print('Number of malignant Images: {}'.format(np.sum(Y2==1)))
print('Image shape (Width, Height, Channels): {}'.format(X2[0].shape))
describeData(X2,Y2)
'''
def plotOne(a,b):
"""
Plot one numpy array
"""
plt.subplot(1,2,1)
plt.title('benign')
plt.imshow(a[0])
plt.subplot(1,2,2)
plt.title('malignant')
plt.imshow(b[0])
plt.show()
#plotOne(imgs_benign, imgs_malignant)
#PLOTTING HISTOGRAM
def plotHistogram(a):
"""
Plot histogram of RGB Pixel Intensities
"""
plt.figure(figsize=(10,5))
plt.subplot(1,2,1)
plt.imshow(a)
plt.axis('off')
plt.title('malignant' if Y[1] else 'benign')
histo = plt.subplot(1,2,2)
histo.set_ylabel('Count')
histo.set_xlabel('Pixel Intensity')
n_bins = 30
plt.hist(a[:,:,0].flatten(), bins= n_bins, lw = 0, color='r', alpha=0.5);
plt.hist(a[:,:,1].flatten(), bins= n_bins, lw = 0, color='g', alpha=0.5);
plt.hist(a[:,:,2].flatten(), bins= n_bins, lw = 0, color='b', alpha=0.5);
plt.show()
#plotHistogram(X2[100])
'''
X = np.array(X)
X = X/255.0
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)
# Reduce Sample Size for DeBugging
X_train = X_train[0:300000]
Y_train = Y_train[0:300000]
X_test = X_test[0:300000]
Y_test = Y_test[0:300000]
print("\n\nTraining Data Shape:", X_train.shape)
print("Testing Data Shape:", X_test.shape, '\n')
# Encode labels to hot vectors (ex : 2 -> [0,0,1,0,0,0,0,0,0,0])
Y_trainHot = to_categorical(Y_train, num_classes = 2)
Y_testHot = to_categorical(Y_test, num_classes = 2)
'''
#plotting the labels count
lab = df['labels']
dist = lab.value_counts()
sns.countplot(lab)
#plt.show()
'''
# Split the train and the validation set for the fitting
X_train, X_val, Y_trainHot, Y_valHot = train_test_split(X_train, Y_trainHot, test_size = 0.1, random_state=2)
print("\nAfter train and validation set split for model fitting :\n X_train, Y_train, X_validation, Y_validation :",X_train.shape,Y_trainHot.shape,X_val.shape,Y_valHot.shape,'\n')
# Define CNN model architecture
batch_size = 128
num_classes = 2
epochs = 8 #achieved an accuracy of 85.39% at epochs = 8
img_rows,img_cols=100,100
input_shape = (img_rows, img_cols, 3)
model = Sequential()
model.add(Conv2D(32, kernel_size = (3, 3),
activation='relu',
input_shape = input_shape,strides=2))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPool2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))
# Compile the model
model.compile(loss='categorical_crossentropy', optimizer='Adadelta', metrics=['accuracy'])
datagen = ImageDataGenerator(
featurewise_center=False, # set input mean to 0 over the dataset
samplewise_center=False, # set each sample mean to 0
featurewise_std_normalization=False, # divide inputs by std of the dataset
samplewise_std_normalization=False, # divide each input by its std
zca_whitening=False, # apply ZCA whitening
rotation_range=20, # randomly rotate images in the range (degrees, 0 to 180)
width_shift_range=0.2, # randomly shift images horizontally (fraction of total width)
height_shift_range=0.2, # randomly shift images vertically (fraction of total height)
horizontal_flip=True, # randomly flip images
vertical_flip=True) # randomly flip images
# Model Training
history = model.fit_generator(datagen.flow(X_train, Y_trainHot, batch_size = 32),
steps_per_epoch = len(X_train) / 32,
epochs = epochs,
validation_data = [X_val, Y_valHot])
print("\n","****************MODEL EVALUATION ************************\n")
# Model Evaluation on Test data
score = model.evaluate(X_test,Y_testHot, verbose=1)
print('\nCNN model #1C - accuracy:', score[1],'\n')
y_pred = model.predict(X_test)
map_characters = {0: 'Benign', 1: 'Malignant'}
print('\n',classification_report(np.where(Y_testHot > 0)[1], np.argmax(y_pred, axis=1), target_names=list(map_characters.values())), sep='')
Y_pred_classes = np.argmax(y_pred, axis=1)
Y_true = np.argmax(Y_testHot, axis=1)
# compute the confusion matrix
confusion_mtx = confusion_matrix(Y_true, Y_pred_classes)
seconds = time.time()
time_stop = time.ctime(seconds) # The time.ctime() function takes seconds passed since epoch
print("stop time:", time_stop,"\n") # as an argument and returns a string representing time.
# saving the model
model.save("breastCancerClassification.h5")
# Training and validation curves
# Plotting the loss and accuracy curves for training and validation
fig, ax = plt.subplots(2,1)
ax[0].plot(history.history['loss'], color='b', label="Training loss")
ax[0].plot(history.history['val_loss'], color='r', label="validation loss",axes =ax[0])
legend = ax[0].legend(loc='best', shadow=True)
ax[1].plot(history.history['accuracy'], color='b', label="Training accuracy")
ax[1].plot(history.history['val_accuracy'], color='r',label="Validation accuracy")
legend = ax[1].legend(loc='best', shadow=True)
plt.savefig("Loss and Accuracy curves.png")
plt.show()
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, cm[i, j],
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.savefig('confusion_matrix.png')
plt.show()
plot_confusion_matrix(confusion_mtx, classes = range(2))