AI-MediSphere™ - The Cardiovascular Prognosticator
Tags: aws, healthcare, ai, hackathon
Published: 2023-06-30 17:32:41

## Overview
Heart diseases are the #1 cause of death every year. Why? It’s usually already too late when people realise something is wrong and contact a medic. How can we help people realise sooner, and simultaneously, how can we help medics save lives?


![A Heart Image - Generated by Generative AI Tool](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yavdq8e5rcn0ifkbl8au.png)

Our app, powered by a chatbot AI, collects minimal but crucial user data related to cardiovascular health, including age, weight, gender, lifestyle factors, blood pressure, cholesterol, and glucose levels. With this information, the chatbot provides personalized explanations and recommendations, guiding users to consult a medical professional if necessary. By offering tailored insights, our app aims to empower individuals to take proactive steps towards their cardiovascular well-being, potentially saving lives through early detection and intervention.

## Problem statement
The aim of this project is to detect the presence or absence of cardiovascular disease in a person based on a set of given features. The features available for analysis include the parameters like Age, Height, Weight, Gender, Physical Activity Level, Drinking habits, Various Blood Pressure parameters,  Cholesterol level, Glucose level et cetera.

## Proposed Solution and Approach
We want to save the lives of many. The best way to approach people and drive use is with a non-invasive user-friendly solution. We preferred a simple and achievable goal to a technically complex solution that didn’t add value. So we decided to build an app with chatbot AI to collect just the minimum set of data (the most important features) and make a personalized explanation and recommendation, based on the User’s knowledge and data available, to consult a medic eventually. We use known and proven components, only in a different way.

### There are two parts to this project. 

1. One, we trained an ML model to predict cardiovascular diseases from decisive inputs.

2. Two, the frontend chatbot application. With today’s countless alternatives, we preferred to focus on the back end on milestone 1. 

> Today it’s not about the code. effective communication is the most important part of the stack. The most important step is getting users to use the app, understand it, and act.

![The Architecture Diagram of AI-Medisphere](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q309d2gx66franar25wt.png)

### Step-by-Step Solution Details:
Classification The Cardio Vascular Prediction solution utilizes the powerful and widely acclaimed XGBoost algorithm for accurate predictions. XGBoost, also known as Extreme Gradient Boosting, is a supervised learning algorithm that excels in both regression and classification tasks. Its success lies in its ability to combine predictions from multiple weak models, forming a robust ensemble.

![XG Boost](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kynw6on0ioc7pprvqbkh.png)

XGBoost's strength stems from its adaptability to various data types and complex distributions. This makes it a suitable choice for cardiovascular prediction, where the dataset is often diverse and intricate. 

Additionally, XGBoost offers a multitude of hyperparameters that can be tuned to enhance the model's performance and fit. 

By leveraging ensemble techniques like bagging and boosting, XGBoost combines a group of relatively average models to create a potent algorithm. This approach is analogous to a powerful random forest algorithm, where multiple decision trees collaborate to achieve superior results. Ensemble techniques, such as bagging and boosting, enable the solution to reduce variance, mitigate overfitting, and enhance the model's robustness. 

Similar to a group of blind men describing an elephant, each contributing their unique perspective, the collaboration of models in the ensemble brings diverse experiences and backgrounds to solve the prediction problem, resulting in more accurate and reliable outcomes. 

By leveraging the immense capabilities of XGBoost, the Cardio Vascular Prediction solution on AWS ensures high-quality predictions while considering the complexity and diversity of cardiovascular data.

### Model Performance Assessment (Confusion Matrix)

A confusion matrix is a valuable tool for evaluating the performance of a classification model. It provides a comprehensive view of how well the model predicts the classes of the data. The matrix consists of four elements: 

#### True positives (TP):
These are the cases in which the classifier correctly predicted the positive class (e.g., a patient having a disease), and the actual class was indeed positive. 

#### True negatives (TN):
These are the cases in which the classifier accurately predicted the negative class (e.g., a patient without a disease), and the actual class was indeed negative.

#### False positives (FP) (Type I error):
These occur when the classifier incorrectly predicted the positive class, indicating that a patient has the disease, but the actual class was negative (e.g., a false alarm or a patient wrongly identified as having the disease).

#### False negatives (FN) (Type II error):
These occur when the classifier incorrectly predicted the negative class, suggesting that a patient does not have the disease, while the actual class was positive (e.g., a failure to identify a patient who actually has the disease) 

> By analyzing the values in the confusion matrix, we can assess the model's performance, identify areas where it excels, and pinpoint potential weaknesses. This information enables us to fine-tune the model, optimize its accuracy, and ensure reliable predictions in real-world scenarios.


### Architecture Explanation

> The proposed solution is an intelligent health monitoring system that utilizes various AWS services and the OpenAI platform to analyze input data and provide valuable insights to end users. The system incorporates data from multiple sources, including objective and subjective features, to predict the presence or absence of cardiovascular disease. The system follows a series of stages, involving API Gateway, AWS Lambda, AWS Sagemaker, and OpenAI endpoints, to process and deliver the final response to the end user.


![Application Flow](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i9rn7f018aqrb5521jm2.png)

#### Stage 1: Input Processing
The system begins by receiving input data through the API Gateway. The input data consists of various features related to an individual's health, such as age, height, weight, gender, blood pressure, cholesterol level, glucose level, smoking habits, alcohol intake, physical activity, and the presence or absence of cardiovascular disease. This data is passed to the AWS Lambda function for further processing. 

#### Stage 2: AWS Lambda Function
In this stage, the AWS Lambda function receives the input data from the API Gateway. The Lambda function acts as the central processing unit, extracting the relevant information from the input and performing any necessary data transformations or validations. The extracted data is prepared for further analysis and passed on to the next stage.

#### Stage 3:AWS Sagemaker Endpoint
After preprocessing the data, the Lambda function invokes the AWS Sagemaker endpoint. Sagemaker is a fully managed machine learning service provided by AWS. The endpoint is responsible for deploying and running the machine learning model that predicts the presence or absence of cardiovascular disease. The processed data is sent to the Sagemaker endpoint for inference.

#### Stage 4:Sagemaker Endpoint Response
The Sagemaker endpoint performs inference using the deployed machine learning model and returns the prediction results back to the Lambda function. The results include a raw output that indicates the likelihood of the presence or absence of cardiovascular disease based on the input data. The Lambda function receives this output for further processing.

#### Stage 5: OpenAI Endpoint
In this stage, the Lambda function utilizes the OpenAI platform to enhance the raw output received from the Sagemaker endpoint. OpenAI is an AI-powered platform capable of generating human-like text. The Lambda function sends the raw output to the OpenAI endpoint for further analysis and processing.

#### Stage 6: OpenAI Response and API Gateway
The OpenAI endpoint processes the raw output and generates a processed and curated response. This response contains valuable insights and explanations regarding the prediction of cardiovascular disease. The Lambda function receives the processed output from OpenAI and prepares it to be served back to the end user. Finally, the processed output is returned via the API Gateway as a response to the end user, providing them with valuable health-related information based on the input data.

## Outcomes, Learnings, and Best Practices Learned in the Process 
Today, AI is no longer solely about writing elite code. With the availability of large pre-trained models and numerous developed technologies, AI has become a journey towards solving meaningful challenges and building something together.

In this pursuit, we, as technical builders at heart, are passionate about problem-solving and are driven by the desire to make a real difference. During our exploration, we came across a startling fact: every year, more people lose their lives to heart diseases than even to cancer and epidemics combined. What makes this even more tragic is that most of these deaths are preventable. 

This realization presented us with an opportunity to have a tangible impact on the lives of countless individuals. Throughout our journey, we've come to understand a crucial lesson: there is an abundance of architectures and solutions available today. It's incredibly easy to get side-tracked and lose sight of what truly matters. 

Therefore, we made a conscious decision to stay laser-focused on what will ultimately help us achieve our goal of saving lives. We carefully considered various options and weighed their significance. By narrowing down our focus, we ensured that our efforts are directed towards solutions that directly address the problem at hand. Our commitment to making a difference serves as our guiding principle, guiding us towards the most effective paths.

In our quest to combat heart diseases and save lives, we are determined to leverage the advancements in AI and technology. By doing so, we believe we can bring about substantial improvements in detection, prevention, and treatment. Through collaboration, innovation, and unwavering dedication, we are optimistic that we can make a significant impact and help save lives affected by heart diseases.

#### Examples of prompts and chatbot responses
**No risk**

```
Hello, Mary Sue! Based on the information you provided, I'm glad to inform you that you are currently at a lower risk of heart disease. Let's explore each factor that contributes to your positive health profile:

Age: At 25 years old, you are at an age where heart diseases are less common. However, it's still important to maintain a healthy lifestyle to prevent future risks.

Gender: Being female typically provides certain cardiovascular advantages, resulting in a lower risk of heart disease compared to males.

Body Measurements: Your height of 1.80m and weight of 70kg indicate a healthy body mass index (BMI), which suggests that you are within a desirable weight range.

Blood Pressure: Your blood pressure readings of 100/80 mmHg (high/low) fall within the normal range, indicating a healthy blood pressure level.

Cholesterol Levels: Having low cholesterol levels implies that you have a decreased risk of plaque buildup in your arteries, reducing the likelihood of heart disease.

Blood Glucose Level: A normal blood glucose level indicates that you have a well-regulated metabolism, which contributes to a lower risk of heart disease.

Smoking: Not smoking is a significant advantage since smoking is a major risk factor for heart disease. Your decision to abstain from smoking protects your heart health.

Alcohol Consumption: Avoiding alcohol consumption is beneficial, as excessive alcohol intake can elevate blood pressure and increase the risk of heart disease.

Physical Activity: Engaging in regular physical activity is excellent for heart health. Your commitment to regular exercise strengthens the heart, improves blood flow, and lowers the risk of heart disease.

Given your positive health profile, you are not currently at high risk for heart disease. However, it's still essential to maintain a healthy lifestyle, including regular exercise, a balanced diet, and routine health check-ups. By prioritizing these aspects, you can continue to safeguard your heart health and overall well-being. If you have any concerns or experience changes in your health, it's always wise to consult a doctor for personalized guidance. Keep up the good work in taking care of yourself!
```

**Risk - uneducated (young) user**

```
Hello John Doe! I'm here to discuss an important matter related to your health. Based on the information you provided, there are several factors that indicate you may be at a high risk of heart disease. Let's take a closer look at each risk factor:

Age: Being 18 years old doesn't guarantee protection against heart diseases. While it's less common at a young age, certain risk factors can still contribute to heart problems.

Gender: Men, like you, have a higher risk of heart disease due to biological and lifestyle factors.

Body Measurements: Your height of 1.80m and weight of 95kg indicate that your body mass index (BMI) is higher than the recommended range. This suggests that you might be carrying excess weight, which can strain your heart and increase the risk of heart disease.

Blood Pressure: Your high blood pressure reading of 150 and low blood pressure reading of 120 are both concerning. Consistently elevated or fluctuating blood pressure levels can damage your blood vessels, putting you at a higher risk of heart disease.

Cholesterol Levels: High cholesterol levels can lead to the buildup of plaque in your arteries, restricting blood flow and increasing the risk of heart disease.

Blood Glucose Level: High blood glucose levels suggest that you may have elevated blood sugar. This can contribute to the development of diabetes, which in turn increases the risk of heart disease.

Smoking: Smoking is extremely harmful to your heart and blood vessels. The chemicals in cigarettes damage the arteries, increase blood pressure, and elevate the risk of heart disease.

Alcohol Consumption: Excessive alcohol consumption, such as drinking several glasses per day, can lead to high blood pressure, irregular heart rhythms, and other heart-related problems.

Physical Inactivity: Not engaging in regular physical activity puts you at a higher risk of heart disease. Exercise helps maintain a healthy weight, lower blood pressure, and improve overall cardiovascular health.

Considering all these risk factors, it is crucial for you to consult a doctor as soon as possible. They can evaluate your health comprehensively, conduct necessary tests, and provide personalized guidance to manage and mitigate these risks effectively. Taking proactive steps and seeking medical advice will greatly improve your chances of preventing heart disease. Your health is important, so please prioritize it by consulting a doctor promptly.
```


**Risk - experienced and adult user**

```
Dear Mr. John Doe, based on the provided information, I must emphasize that your current health profile places you at a significantly high risk of heart disease. Allow me to elaborate on each risk factor and its potential detrimental effects:

Age: At 58 years old, the risk of developing heart disease tends to increase due to the natural aging process and cumulative exposure to various risk factors over time.

Gender: Being male, you are more predisposed to heart diseases compared to females, as hormonal and genetic factors contribute to a higher prevalence.

Body Measurements: With a height of 1.80m and a weight of 95kg, your body mass index (BMI) indicates that you are overweight. Excessive weight puts strain on your heart and elevates the risk of cardiovascular complications.

Blood Pressure: Your blood pressure readings of 150/120 mmHg (high/low) demonstrate hypertension, a condition that burdens the heart and blood vessels, potentially leading to heart disease, stroke, and organ damage.

Cholesterol Levels: Elevated cholesterol levels, especially if your low-density lipoprotein (LDL) cholesterol is high, promote the deposition of fatty plaques in arterial walls, obstructing blood flow and heightening the likelihood of heart diseases.

Blood Glucose Level: High blood glucose levels suggest impaired glucose regulation, potentially indicating diabetes or prediabetes. Elevated blood sugar levels contribute to the development of atherosclerosis, increasing the risk of heart disease.

Smoking: Smoking is a significant risk factor that damages the inner lining of blood vessels, accelerates the formation of arterial plaques, and raises blood pressure, significantly increasing the likelihood of heart disease.

Alcohol Consumption: Consuming several glasses of alcohol per day contributes to high blood pressure, irregular heart rhythms, and weakening of heart muscles, augmenting the risk of heart diseases.

Physical Inactivity: The absence of regular physical activity reduces cardiovascular fitness, weakens the heart muscle, and impairs overall heart health, increasing the susceptibility to heart diseases.

Considering these multiple risk factors, I strongly urge you to promptly consult a doctor. Medical professionals can assess your specific circumstances, conduct comprehensive evaluations, and develop a personalized plan to manage and mitigate these risks. By taking proactive measures and seeking professional guidance, you can significantly improve your cardiovascular health and reduce the chances of heart disease. Your well-being is paramount, so please prioritize your health and seek medical attention without delay.

```
## Conclusion
The intelligent health monitoring system described above utilizes AWS services, such as API Gateway, Lambda, and Sagemaker, along with the OpenAI platform, to process input data and deliver valuable insights to end users. By leveraging machine learning and natural language processing capabilities, the system can predict the presence or absence of cardiovascular disease and provide detailed explanations for the prediction. This solution enables users to monitor their health more effectively and make informed decisions regarding their well-being.

## Next Steps
We’ll build the front end to consume the model, support all major platforms, and sources of input, like Apple Health and other integrations to make this completely automatic, with less need for the user to answer the chatbot manually. The less work from the user, the higher the adoption rate. We want to save lives, so it’s critical we make it easy. Later on, we may create APIs for medics and labs to read and write - provided regulatory compliance. We’ll also train the model to add fine-grained information on different heart diseases.

## This Blog post was Co-Authored by 

**Ermanno Attardo**
https://www.linkedin.com/in/ebjattardo/
Website: www.ermannoattardo.com
**Govind Kumar**
https://www.linkedin.com/in/elngovind/
Website: www.elngovind.com

Github Link: https://github.com/AI-MediSphere/PredictionModel