-
Notifications
You must be signed in to change notification settings - Fork 0
/
braintumor.py
175 lines (131 loc) · 4.12 KB
/
braintumor.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
# -*- coding: utf-8 -*-
"""BrainTumor.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1DWAMCDSmhd_JtBIkThzNWXGxiJTOLWHW
"""
from google.colab import files
files.upload()
!pip install -q kaggle
!mkdir -p ~/.kaggle
!cp kaggle.json ~/.kaggle/
!chmod 600 /root/.kaggle/kaggle.json
!kaggle datasets download -d navoneel/brain-mri-images-for-brain-tumor-detection
import keras
from keras.models import *
from keras.layers import *
from keras.preprocessing import image
import PIL
import pandas as pd
import matplotlib.pyplot as plt
!unzip "/content/brain-mri-images-for-brain-tumor-detection.zip"
import os
# assign directory
directory = '/content/no'
no=[]
# iterate over files in
# that directory
for filename in os.scandir(directory):
if filename.is_file():
no.append(filename.path)
len(no)
import os
# assign directory
directory = '/content/yes'
yes=[]
# iterate over files in
# that directory
for filename in os.scandir(directory):
if filename.is_file():
yes.append(filename.path)
len(yes)
x_train = no[:80] + yes[:130]
x_test = no[80:] + yes[130:]
y_train = []
for i in range(80):
y_train.append(0)
for i in range(130):
y_train.append(1)
len(y_train)
y_test =[]
for i in range(18):
y_test.append(0)
for i in range(25):
y_test.append(1)
len(y_test)
# Import the necessary libraries
import cv2
from numpy import asarray
import numpy as np
# load the image and convert into
# numpy array
x_train_final =[]
for i in x_train:
img =cv2.imread(i,0)
img=cv2.resize(img, (100, 100))
x_train_final.append(np.array(img).astype(np.uint8))
# data
print(x_train_final)
# Import the necessary libraries
import cv2
from numpy import asarray
import numpy as np
# load the image and convert into
# numpy array
x_test_final =[]
for i in x_test:
img =cv2.imread(i,0)
img=cv2.resize(img, (100, 100))
x_test_final.append(np.array(img).astype(np.uint8))
# data
print(x_test_final)
print(len(x_train_final))
print(len(x_test_final))
import numpy as np
x_train_final=np.array(x_train_final)
x_test_final=np.array(x_test_final)
y_train=np.array(y_train)
y_test=np.array(y_test)
print(x_train_final.shape)
print(x_test_final.shape)
# normlize the data
x_train = x_train_final/255.0
x_test = x_test_final/255.0
model=keras.Sequential() #Create a network sequence.
model.add(Input(shape=(100,100,1)))
model.add(Conv2D(filters=6,kernel_size = 3,strides = (2,2), padding = 'same',activation = 'relu'))
model.add(MaxPooling2D(pool_size=(2,2), strides = (2,2), padding = 'valid'))
model.add(Conv2D(filters=6,kernel_size = 3,strides = (2,2), padding = 'same',activation = 'relu'))
model.add(MaxPooling2D(pool_size=(2,2), strides = (2,2), padding = 'valid'))
model.add(Conv2D(filters=6,kernel_size = 3,strides = (2,2),padding = 'same',activation = 'relu'))
model.add(Conv2D(filters=7,kernel_size = 3,strides = (2,2),padding = 'same',activation = 'relu'))
model.add(Flatten())
model.add(Dense(84,activation = 'relu'))
model.add(Dense(70,activation = 'relu'))
model.add(Dense(10,activation = 'relu'))
model.add(Dense(1,activation="sigmoid"))
model.summary()
model.compile(optimizer='adam',loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),metrics=['accuracy'])
results= model.fit(x_train,y_train,epochs=100,batch_size=30,validation_data=(x_test, y_test),shuffle=True)
model.save("BrainTumor_CNN.h5")
from google.colab import drive
drive.mount('/content/drive')
from keras.models import load_model
!cp "/content/BrainTumor_CNN.h5" "/content/drive/MyDrive/H5_Folders"
model=load_model('/content/BrainTumor_CNN.h5')
y_pred=model.predict(x_test)
import matplotlib.pyplot as plt
plt.plot(results.history['loss'])
plt.plot(results.history['val_loss'])
plt.legend(['Training','Vaildation'])
plt.title('Training and Validation Losses')
plt.xlabel('epoches')
plt.ylabel('losses')
import matplotlib.pyplot as plt
plt.plot(results.history['accuracy'])
plt.plot(results.history['val_accuracy'])
plt.legend(['Training','Vaildation'])
plt.title('Training and Validation Accuracy')
plt.xlabel('epoches')
plt.ylabel('accuracy')
print(model.evaluate(x_test,y_test))