Note: If the author has requested for "Expert Guidance" and you can help, please start a New Topic in the "Discussions" Tab

Hashwanth Gogineni'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 » Alzheimer's brain Disease Detection

Alzheimer's brain Disease Detection

Models Status

Model Overview

Alzheimer's Disease


Alzheimer's disease is a progressive brain disease that wreaks havoc on memory and thinking skills, as well as the capacity to carry out even the most basic tasks. Symptoms of late-onset type occur in the mid-60s in the majority of patients with the condition. Early-onset Alzheimer's disease is extremely rare and occurs between the ages of 30 and 60. The most prevalent cause of dementia in elderly people is Alzheimer's disease.


Dr Alois Alzheimer is the name of the disease. Dr Alzheimer detected alterations in a woman's brain tissue after she died of an uncommon mental ailment in 1906. Memory loss, linguistic difficulties, and erratic behaviour were among her symptoms. He examined her brain after she died and discovered several aberrant clumps (now known as amyloid plaques) and tangled bundles of fibres (now called neurofibrillary, or tau, tangles). These plaques and tangles in the brain are still regarded to be some of Alzheimer's disease's most prominent symptoms. The loss of connections between nerve cells (neurons) in the brain is another hallmark. Neurons communicate between different sections of the brain as well as between the brain and muscles and organs throughout the body. Alzheimer's disease is thought to be caused by a variety of additional complex brain alterations.


The entorhinal cortex and hippocampus, which are crucial in memory, are the first areas of the brain to be damaged. Later on, it affects parts of the cerebral cortex that control language, logic, and social behaviour. Many other parts of the brain are eventually affected.



Why Alzheimer's Disease Detection?


The project can help healthcare organizations detect Alzheimer's Disease in patients using technology. 


Dataset


The data is hand collected from various websites with each and every label verified. The dataset includes '5,122 ' X-ray images of Healthy patients and Alzheimer's Disease patients i.e '2,561' images in each class.



Xception


'Xception' stands for 'extreme inception' and it pushes Inception's concepts to their logical conclusion. In Inception, 1x1 convolutions were used to compress the original input, and different types of filters were applied to each of the depth spaces based on the input spaces. Xception just reverses this process. Instead, it applies the filters to each depth map individually before compressing the input space using 1X1 convolution across the depth. This method is nearly identical to a depthwise separable convolution, a neural network design operation that has been utilised since 2014. One further distinction exists between Inception and Xception. After the initial operation, the presence or absence of a non-linearity. Both processes are followed by a ReLU non-linearity in the Inception model; however, Xception does not introduce any non-linearity.



Understanding Code


 First, let us import the required libraries for our project.


import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from pathlib import Path
from tensorflow.keras.preprocessing import image_dataset_from_directory
import tensorflow as tf
import cv2
from keras.layers import Input, Lambda, Dense, Flatten,GlobalAveragePooling2D, Dropout, Activation
from keras.models import Model
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator
from sklearn.metrics import classification_report, log_loss, accuracy_score


Now, let us load the data into our system and convert the data into a dataframe.


image_dir = Path('/content/sample_data/data/train')

# Get filepaths and labels
filepaths = list(image_dir.glob(r'**/*.jpg'))
labels = list(map(lambda x: os.path.split(os.path.split(x)[0])[1], filepaths))

filepaths = pd.Series(filepaths, name='Filepaths').astype(str)
labels = pd.Series(labels, name='Labels')

# Concatenate filepaths and labels
image_df = pd.concat([filepaths, labels], axis=1)

# Shuffle the DataFrame and reset index
image_df = image_df.sample(frac=1).reset_index(drop = True)

# Show the result
image_df.head()

As you can see, we extracted data from the data's directory and concatenated 'filepaths' and 'labels' into a dataframe.

Let us also split the dataframe for testing and training purposes.


# Separating train and test data
from sklearn.model_selection import train_test_split

train_df, test_df = train_test_split(image_df, train_size=0.85, shuffle=True, random_state=1)

As you can see, I used the "train_test_split" function to split the dataframe.


train_datagen = ImageDataGenerator(rescale=1./255, validation_split=0.15)

test_datagen = ImageDataGenerator(rescale=1./255)

As you can see, I used the 'ImageDataGenerator' function for data augmentation purposes.


train_images = train_datagen.flow_from_dataframe(
dataframe=train_df,
x_col='Filepaths',
y_col='Labels',
target_size=(150,150),
color_mode='rgb',
class_mode='categorical',
batch_size=64,
shuffle=True,
seed=42,
subset='training'
)

val_images = train_datagen.flow_from_dataframe(
dataframe=train_df,
x_col='Filepaths',
y_col='Labels',
target_size=(150, 150),
color_mode='rgb',
class_mode='categorical',
batch_size=64,
shuffle=True,
seed=42,
subset='validation'
)

test_images = test_datagen.flow_from_dataframe(
dataframe=test_df,
x_col='Filepaths',
y_col='Labels',
target_size=(150,150),
color_mode='rgb',
class_mode='categorical',
batch_size=32,
shuffle=False
)

Also, I loaded train and test data using the 'flow_from_dataframe' function into the kernel.

Next, let us get into the modelling part of the project.


from tensorflow.keras.applications import Xception
xcptn = Xception(include_top=False, weights='imagenet', input_shape=(150,150,3))
xcptn.summary()

So, I chose the 'Xception' model to get the best results.
I used 'imagenet' as weights for our model.


for layer in xcptn.layers:
layer.trainable=False

x = Flatten()(xcptn.output)
x = Dense(512,activation='relu')(x)
x = Dense(512,activation='relu')(x)
prediction = Dense(2, activation='softmax')(x)
model = Model(inputs=xcptn.input, outputs=prediction)
model.summary()

I also used neural network layers to the model for efficient results.

Now, let us compile our model and fit the data.


model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['accuracy'])

callback = tf.keras.callbacks.EarlyStopping(monitor='accuracy', patience=2)

history = model.fit_generator(train_images, validation_data=val_images, epochs=25, callbacks=callback)

As you can see, I used 'categorical_crossentropy' and 'accuracy' as metrics.

Now let us understand how our model performed.


 get_acc = history.history['accuracy']
value_acc = history.history['val_accuracy']
get_loss = history.history['loss']
validation_loss = history.history['val_loss']

epochs = range(len(get_acc))
plt.plot(epochs, get_acc, 'r', label='Accuracy of Training data')
plt.plot(epochs, value_acc, 'b', label='Accuracy of Validation data')
plt.title('Training vs validation accuracy')
plt.legend(loc=0)
plt.figure()
plt.show()


Finally, I used 'matplotlib.pyplot' to generate our model's performance graph.

Also, let us have a look at our model's classification report.


# Classification Report

from sklearn.metrics import classification_report

test_labels=test_images.classes
predictions=model.predict_generator(test_images, verbose=1)
y_pred = np.argmax(predictions, axis=-1)
print(classification_report(test_labels, y_pred))


As you can see we achieved good results.



Thank you for your time.


0 comments