-
Notifications
You must be signed in to change notification settings - Fork 1
/
CNN.py
165 lines (117 loc) · 4.71 KB
/
CNN.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
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import math
import cv2
import matplotlib.pyplot as plt
import os
import seaborn as sns
import umap
from PIL import Image
from scipy import misc
from os import listdir
from os.path import isfile, join
import numpy as np
from scipy import misc
from random import shuffle
from collections import Counter
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras.utils.np_utils import to_categorical
os.listdir('C:/BrainTumor/Brain Tumor Dataset/brain_tumor_dataset')
im =Image.open('C:/BrainTumor/Brain Tumor Dataset/no/1 no.jpeg').resize((128,128))
im
im =Image.open('C:/BrainTumor/Brain Tumor Dataset/yes/Y1.jpg').resize((128,128))
im
yes=os.listdir('C:/BrainTumor/Brain Tumor Dataset/yes')
no=os.listdir('C:/BrainTumor/Brain Tumor Dataset/no')
data=np.concatenate([yes,no])
len(data)==len(yes)+len(no)
target_x=np.full(len(yes),1)
target_y=np.full(len(no),0)
data_target=np.concatenate([target_x,target_y])
len(data_target)==len(target_x)+len(target_y)
len(data_target)==len(data)
data_target
data
yes_values=os.listdir('C:/BrainTumor/Brain Tumor Dataset/yes')
no_values=os.listdir('C:/BrainTumor/Brain Tumor Dataset/no')
X_data =[]
for file in yes_values:
#face = misc.imread('../input/brain_tumor_dataset/yes/'+file)
img = cv2.imread('C:/BrainTumor/Brain Tumor Dataset/yes/'+file)
face = cv2.resize(img, (32, 32) )
(b, g, r)=cv2.split(face)
img=cv2.merge([r,g,b])
X_data.append(img)
#X_data =[]
for file in no_values:
#face = misc.imread('../input/brain_tumor_dataset/yes/'+file)
img = cv2.imread('C:/BrainTumor/Brain Tumor Dataset/no/'+file)
face = cv2.resize(img, (32, 32) )
(b, g, r)=cv2.split(face)
img=cv2.merge([r,g,b])
X_data.append(img)
len(X_data)==len(data)==len(data_target)
X = np.squeeze(X_data)
X.shape
# normalize data
X = X.astype('float32')
X /= 255
data_target
(x_train, y_train), (x_test, y_test) = (X[:190],data_target[:190]) , (X[190:] , data_target[190:])
(x_valid , y_valid) = (x_test[:63], y_test[:63])
#(x_test, y_test) = (x_test[63:], y_test[63:])
model = tf.keras.Sequential()
# Must define the input shape in the first layer of the neural network
model.add(tf.keras.layers.Conv2D(filters=16,kernel_size=9, padding='same', activation='relu', input_shape=(32,32,3)))
model.add(tf.keras.layers.MaxPooling2D(pool_size=2))
model.add(tf.keras.layers.Dropout(0.45))
model.add(tf.keras.layers.Conv2D(filters=16,kernel_size=9,padding='same', activation='relu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=2))
model.add(tf.keras.layers.Dropout(0.25))
model.add(tf.keras.layers.Conv2D(filters=36, kernel_size=9, padding='same', activation='relu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=2))
model.add(tf.keras.layers.Dropout(0.25))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(512, activation='relu'))
model.add(tf.keras.layers.Dropout(0.15))
model.add(tf.keras.layers.Dense(1, activation='sigmoid'))
# Take a look at the model summary
model.summary()
model.compile(loss='binary_crossentropy',
optimizer=tf.keras.optimizers.Adam(),
metrics=['acc'])
model.fit(x_train,
y_train,
batch_size=128,
epochs=150,
validation_data=(x_valid, y_valid),)
from IPython.display import SVG
from keras.utils.vis_utils import model_to_dot
SVG(model_to_dot(model,show_shapes = True).create(prog='dot', format='svg'))
# Evaluate the model on test set
score = model.evaluate(x_test, y_test, verbose=0)
# Print test accuracy
print('\n', 'Test accuracy:', score[1])
labels =["Yes", # index 0
"No", # index 1
]
y_hat = model.predict(x_test)
# Plot a random sample of 10 test images, their predicted labels and ground truth
figure = plt.figure(figsize=(20, 8))
for i, index in enumerate(np.random.choice(x_test.shape[0], size=15, replace=False)):
ax = figure.add_subplot(3, 5, i + 1, xticks=[], yticks=[])
# Display each image
ax.imshow(np.squeeze(x_test[index]))
predict_index = np.argmax(y_hat[index])
true_index = np.argmax(y_test[index])
# Set the title for each image
ax.set_title("{} ({})".format(labels[predict_index],
labels[true_index]),
color=("green" if predict_index == true_index else "red"))
plt.show()