Tarun Reddy's other Models Reports

Major Concepts

 

Sign-Up/Login to access Several ML Models and also Deploy & Monetize your own ML solutions for free

Models Home » Domain Usecases » Health Care and Pharmaceuticals » CNN Brain Tumor Detection using optimizers.

CNN Brain Tumor Detection using optimizers.

Models Status

Model Overview





The Human body is made out of various sorts of cells. Every cell has a particular capacity. These cells in the body develop and partition in an orchestrated way and structure some new cells. These new cells help to keep the human body solid and guarantee legitimate working. At the point when a portion of the cells loses their capacity to control their development, they develop with no organization. The extra cells formed from a mass of tissue which is called a tumor. A brain tumor is an assortment of unusual cells in the brain. Tumors can be amiable or harmful. Malignant tumors lead to cancer while benign tumors are not cancerous. Symptoms include new or increasingly strong headaches, blurred vision, loss of balance, confusion, and seizures. In some cases, there may be no symptoms. Treatments include surgery, radiation, and chemotherapy.


The conventional method for tumor detection in magnetic resonance brain images is human inspection. The observations from humans in predicting the tumor may mislead due to noise and distortions found in the image. This method is impractical for a large amount of data and also very time-consuming.

So, automated tumor detection methods are developed as it would save radiologists time. MRI brain tumor detection is a complex task due to the complexity and variant of tumors. The tumor is identified in brain MRI using Machine Learning algorithms.

APPLICATIONS :
The main aim of the usecase is to identify tumors and diagnosis them. This is used for drug recovery and manufacturing. The manual identification is not so fast, accurate and efficient, therefore to overcome these problems this application is designed.

ACCURACY :

Accuracy: 86


Validation Accuracy: 85


Let us now import the required libraries

import os
import keras
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, BatchNormalization
from PIL import Image
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('dark_background')
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder

 


In the next step let us use OneHotEncoder and encode the dataset. Tumour is indicated by 0 and Normal is indicated by 1.

encoder = OneHotEncoder()
encoder.fit([[0], [1]])


Now let us create three empty lists named data, paths, and results. The data list contains NumPy forms of images. Path lists contain the path of each and every image and the result list contains the target class whether zero or one.

data = []
paths = []
result = []

for r, d, f in os.walk('E:\\braintumour\\yes'):
for file in f:
if '.jpg' in file:
paths.append(os.path.join(r, file))

for path in paths:
img = Image.open(path)
img = img.resize((128,128))
img = np.array(img)
if(img.shape == (128,128,3)):
data.append(np.array(img))
result.append(encoder.transform([[0]]).toarray())


In the above step, we resized the image and converted those into NumPy array.
Now let us follow the same steps and do it for the no tumor folder.

# This cell updates result list for images without tumor

paths = []
for r, d, f in os.walk("E:\\braintumour\\/no"):
for file in f:
if '.jpg' in file:
paths.append(os.path.join(r, file))

for path in paths:
img = Image.open(path)
img = img.resize((128,128))
img = np.array(img)
if(img.shape == (128,128,3)):
data.append(np.array(img))
result.append(encoder.transform([[1]]).toarray())


Now let us check the shape of the data.

data = np.array(data)
data.shape



result = np.array(result)
result = result.reshape(139,2)


Now let's split the data into training and testing 

x_train,x_test,y_train,y_test = train_test_split(data, result, test_size=0.2, shuffle=True, random_state=0)


MODEL BUILDING :

Batch normalization is a technique for training very deep neural networks that standardizes the inputs to a layer for each mini-batch. This has the effect of stabilizing the learning process and dramatically reducing the number of training epochs required to train deep networks.
For creating the model we are going to use a sequential model that we mostly use for CNN

model = Sequential()

model.add(Conv2D(32, kernel_size=(2, 2), input_shape=(128, 128, 3), padding = 'Same'))
model.add(Conv2D(32, kernel_size=(2, 2), activation ='relu', padding = 'Same'))


model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Conv2D(64, kernel_size = (2,2), activation ='relu', padding = 'Same'))
model.add(Conv2D(64, kernel_size = (2,2), activation ='relu', padding = 'Same'))

model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2)))
model.add(Dropout(0.25))

model.add(Flatten())

model.add(Dense(512, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(2, activation='softmax'))

model.compile(loss = "categorical_crossentropy", optimizer='Adamax', metrics=['accuracy'])
print(model.summary())


In the above step, we compiled the model and used adamax optimizer.


Now let us check the shape of training set.

y_train.shape



Let us now fit the data into my model

history = model.fit(x_train, y_train, epochs = 40, batch_size = 50, verbose = 1,validation_data = (x_test, y_test))



now let's check the model

def names(number):
if number==0:
return 'Its a Tumor'
else:
return 'No, Its not a tumor'

from matplotlib.pyplot import imshow


let us now pass the image through the model and see the results. In the first process,  we pass a no tumor image and check the model accuracy.

img = Image.open("E:\\braintumour\\no\\No20.jpg")
x = np.array(img.resize((128,128)))
x = x.reshape(1,128,128,3)
res = model.predict_on_batch(x)
classification = np.where(res == np.amax(res))[1][0]
imshow(img)
print(str(res[0][classification]*100) + '% Confidence This Is ' + names(classification))




We got 96% accuracy on the image.

Now let us pass a tumor image into the model and check the accuracy.

img = Image.open("E:\\braintumour\\yes\\Y1.jpg")
x = np.array(img.resize((128,128)))
x = x.reshape(1,128,128,3)
res = model.predict_on_batch(x)
classification = np.where(res == np.amax(res))[1][0]
imshow(img)
print(str(res[0][classification]*100) + '% Confidence This Is ' + names(classification))




We can see the model predicted the tumor with 100% accuracy.


0 comments