Automatic Stroke Prediction Using Android App

Md. Jahirul lslam
5 min readMay 2, 2024
Photo by Natasha Connell on Unsplash

Introduction:

In recent years, the integration of machine learning techniques into mobile applications has revolutionized the healthcare industry. One such advancement is the development of an Android application for automatic stroke prediction.

In this blog post, we’ll discuss the process of creating an Android app that predicts the likelihood of stroke based on various health parameters using machine learning algorithms.

Overview of the Project:

The project aims to develop an Android application capable of predicting the probability of stroke for an individual based on their health attributes. The prediction model is built using artificial neural networks (ANN) and deployed on the Android platform for real-time prediction.

1. Model Development:

Photo by Markus Winkler on Unsplash

1.1 Loading Python Modules/Packages: The project begins with importing necessary Python libraries for data manipulation, model training, and evaluation.

import pandas as pd
import numpy as np
import seaborn as sns
import tensorflow as tf
import matplotlib.pyplot as plt

1.2 Loading Dataset : This stroke dataset has collect from Kaggle and it is loaded into a Google Colab environment.In this dataset ,Input Features are Gender,Age,Hypertension,Heart Disease,Ever Married,Work Type,Residence Type,Average Glucose Level,BMI (Body Mass Index),Smoking Status and Label Feature is Stroke .Additional Information:The “id” feature is an identifier and does not affect the prediction of stroke.

dataset = pd.read_csv('healthcare-dataset-stroke-data.csv')

1.3 Data Preprocessing:

Handling Missing Data: There are 201 missing value of BMI .Those missing values in the dataset are filled using mean value to maintain data integrity.

Removing Irrelevant Columns: Columns like ‘id’ are removed from the dataset as they do not contribute to the prediction.

Ordinal Encoding: Categorical variables are encoded using ordinal encoding for numerical representation.

Gender : Female->0 , Male ->1 , Other->3

Ever_married : No->0, Yes->1

Work_type : children->0, Govt_job->1,Self-employed->2, Private->3, Never_worked->4

Residence_type : Urban->0, Rural->1

Smoking_status : never smoked->0, formerly smoked->1, smokes->2, Unknown->3

1.4 Splitting Dataset: The dataset is split into training and testing sets for model evaluation.

from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size= 0.2, random_state= 0)

1.5 Balancing Dataset: To handle class imbalance, the Synthetic Minority Over-sampling Technique (SMOTE) is applied to balance the dataset.

from imblearn.over_sampling import SMOTE
sm = SMOTE(random_state=2)
x_train_res, y_train_res = sm.fit_resample(x_train, y_train.ravel())

1.6 Model Training: An artificial neural network (ANN) is implemented using the Keras library. The model architecture consists of multiple layers with appropriate activation functions.

##model selection
from sklearn import metrics
from sklearn.metrics import recall_score, f1_score, precision_score
from numpy import loadtxt
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
model = Sequential()
model.add(Dense(12, input_shape=(10,), activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(16, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

# Fit the model to the training data
model.fit(x_train_res, y_train_res, epochs=50, batch_size=10)

y_pred = model.predict(x_test)
# Threshold predictions
y_pred_binary = (y_pred > 0.5).astype(int)

1.7 Model Evaluation: The trained model is evaluated using performance metrics such as accuracy, precision, recall, and F1-score.

1.8 Save the model and create h5 and tflite file format: Once the model is trained and evaluated satisfactorily, it is converted into the TensorFlow Lite (TFLite) format for deployment on the Android platform.

import tensorflow as tf
from tensorflow import keras, lite

# Corrected quotation marks
keras_file = "Stroke_Prediction.h5"
tf.keras.models.save_model(model, keras_file)

converter = lite.TFLiteConverter.from_keras_model(model)
tfmodel = converter.convert()

open("Stroke_Prediction.tflite", "wb").write(tfmodel)

2. Android App Development:

Photo by CARTIST on Unsplash

The Android application is developed using Java programming languages. The TFLite model for stroke prediction is integrated into the Android app. The app provides a user-friendly interface for inputting health 10 parameters and receiving predictions in real-time.

Create Android Application

Goto Android Studio -> Create New Project.

Initially, you need to add below dependencies in the code:

  1. Add following package inside dependencies of build.gradle file -

‘implementation ‘org.tensorflow:tensorflow-lite:2.15.0’

2. Add the tflite file inside the assets folder of the Android project.

3. Add the below function in the Java file

private ByteBuffer loadModelFile() throws IOException {
AssetFileDescriptor assetFileDescriptor = this.getAssets().openFd(“Stroke_Prediction.tflite”);
FileInputStream fileInputStream = new FileInputStream(assetFileDescriptor.getFileDescriptor());
FileChannel fileChannel = fileInputStream.getChannel();

long startOffset = assetFileDescriptor.getStartOffset();
long length = assetFileDescriptor.getLength();

ByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, length);
fileInputStream.close(); // Close the FileInputStream after mapping

return buffer;
}

This will convert the tflite model file into MappedByteBuffer format. It is an optimized format that will help us to increase efficiency and speed.

4. Add an Interpreter which will interpret the input and output of data using the model.

try {
interpreter = new Interpreter(loadModelFile());
} catch (IOException e) {
e.printStackTrace();
}

5. Add below doInference() function to evaluate the expression and get the output with the help of the model.

float output = doInference(input);
long prediction = Math.round(output);

public float doInference(float[] input) {
float[][] output = new float[1][1];
interpreter.run(input, output);
return output[0][0];
}

The parameter input is the input value given by the user.

The integration of machine learning algorithms into mobile applications has immense potential in healthcare. The development of an Android app for automatic stroke prediction demonstrates how advanced technologies can be leveraged to improve healthcare outcomes. With further refinement and validation, such applications can become valuable tools for early detection and prevention of life-threatening conditions like stroke.

Input Interface:

Taking Input Interface

Output Interface :

Output Interface

Conclusion:

In conclusion, the development of an Android application for automatic stroke prediction showcases the power of machine learning in healthcare. By leveraging artificial neural networks and mobile technology, we can create innovative solutions that have the potential to save lives. With continued research and development, such applications can make significant contributions to public health and wellness .

I hope you enjoyed the blog!!!

Please feel free to post your comments and feedback….

Don’t forget to hit claps if you liked it :)

Also, new ideas are welcomed.

Thank You! :)

--

--

Md. Jahirul lslam

Machine learning , Deep learning , NLP , Data science Enthusiastic