NYC Data Science Academy| Blog
Bootcamps
Lifetime Job Support Available Financing Available
Bootcamps
Data Science with Machine Learning Flagship ๐Ÿ† Data Analytics Bootcamp Artificial Intelligence Bootcamp New Release ๐ŸŽ‰
Free Lesson
Intro to Data Science New Release ๐ŸŽ‰
Find Inspiration
Find Alumni with Similar Background
Job Outlook
Occupational Outlook Graduate Outcomes Must See ๐Ÿ”ฅ
Alumni
Success Stories Testimonials Alumni Directory Alumni Exclusive Study Program
Courses
View Bundled Courses
Financing Available
Bootcamp Prep Popular ๐Ÿ”ฅ Data Science Mastery Data Science Launchpad with Python View AI Courses Generative AI for Everyone New ๐ŸŽ‰ Generative AI for Finance New ๐ŸŽ‰ Generative AI for Marketing New ๐ŸŽ‰
Bundle Up
Learn More and Save More
Combination of data science courses.
View Data Science Courses
Beginner
Introductory Python
Intermediate
Data Science Python: Data Analysis and Visualization Popular ๐Ÿ”ฅ Data Science R: Data Analysis and Visualization
Advanced
Data Science Python: Machine Learning Popular ๐Ÿ”ฅ Data Science R: Machine Learning Designing and Implementing Production MLOps New ๐ŸŽ‰ Natural Language Processing for Production (NLP) New ๐ŸŽ‰
Find Inspiration
Get Course Recommendation Must Try ๐Ÿ’Ž An Ultimate Guide to Become a Data Scientist
For Companies
For Companies
Corporate Offerings Hiring Partners Candidate Portfolio Hire Our Graduates
Students Work
Students Work
All Posts Capstone Data Visualization Machine Learning Python Projects R Projects
Tutorials
About
About
About Us Accreditation Contact Us Join Us FAQ Webinars Subscription An Ultimate Guide to
Become a Data Scientist
    Login
NYC Data Science Acedemy
Bootcamps
Courses
Students Work
About
Bootcamps
Bootcamps
Data Science with Machine Learning Flagship
Data Analytics Bootcamp
Artificial Intelligence Bootcamp New Release ๐ŸŽ‰
Free Lessons
Intro to Data Science New Release ๐ŸŽ‰
Find Inspiration
Find Alumni with Similar Background
Job Outlook
Occupational Outlook
Graduate Outcomes Must See ๐Ÿ”ฅ
Alumni
Success Stories
Testimonials
Alumni Directory
Alumni Exclusive Study Program
Courses
Bundles
financing available
View All Bundles
Bootcamp Prep
Data Science Mastery
Data Science Launchpad with Python NEW!
View AI Courses
Generative AI for Everyone
Generative AI for Finance
Generative AI for Marketing
View Data Science Courses
View All Professional Development Courses
Beginner
Introductory Python
Intermediate
Python: Data Analysis and Visualization
R: Data Analysis and Visualization
Advanced
Python: Machine Learning
R: Machine Learning
Designing and Implementing Production MLOps
Natural Language Processing for Production (NLP)
For Companies
Corporate Offerings
Hiring Partners
Candidate Portfolio
Hire Our Graduates
Students Work
All Posts
Capstone
Data Visualization
Machine Learning
Python Projects
R Projects
About
Accreditation
About Us
Contact Us
Join Us
FAQ
Webinars
Subscription
An Ultimate Guide to Become a Data Scientist
Tutorials
Data Analytics
  • Learn Pandas
  • Learn NumPy
  • Learn SciPy
  • Learn Matplotlib
Machine Learning
  • Boosting
  • Random Forest
  • Linear Regression
  • Decision Tree
  • PCA
Interview by Companies
  • JPMC
  • Google
  • Facebook
Artificial Intelligence
  • Learn Generative AI
  • Learn ChatGPT-3.5
  • Learn ChatGPT-4
  • Learn Google Bard
Coding
  • Learn Python
  • Learn SQL
  • Learn MySQL
  • Learn NoSQL
  • Learn PySpark
  • Learn PyTorch
Interview Questions
  • Python Hard
  • R Easy
  • R Hard
  • SQL Easy
  • SQL Hard
  • Python Easy
Data Science Blog > Machine Learning > Stroke Prediction EDA and Descriptive Modeling

Stroke Prediction EDA and Descriptive Modeling

Augi Bold
Posted on Aug 22, 2021

GitHub

The skills the author demonstrated here can be learned through taking Data Science with Machine Learning bootcamp with NYC Data Science Academy.

Introduction

Stroke is the fifth leading cause of death and disability in the United States according to the American Heart Association. Every 40 seconds in the US, someone experiences a stroke, and every four minutes, someone dies from it according to the CDC. A recent figure of stroke-related cost almost reached $46 billion. With my interest in healthcare and parents aging into a new decade, I chose this Stroke Prediction Dataset from Kaggle for my Python project. 

Objective

Through this project, I will explore which factors are the leading drivers for stroke and build a descriptive model using Machine Learning to bring awareness to individuals and help healthcare providers and insurers estimate risk and cost.  

Data

The Kaggle dataset is used to predict whether a patient is likely to get a stroke based on dependent variables like gender, age, various health conditions, and smoking status.  Each row in the data provides relevant information about the patient; there are 5110 observations with 12 features.  Of the features, 3 were numeric and continuous whereas the rest of the 8 features were categorical (7 dependent and 1 independent).  The target feature โ€˜strokeโ€™ was binary and therefore classification modeling was used.  

 

Exploratory Stroke Data Analysis

One of the very first things noticed was that the โ€˜bmiโ€™ (Body Mass Index) feature was the only feature that had null values.  The null values only made up 3.9% of the whole dataset. That seemed negligible until I realized upon further check that 20% of them made up 16% of all the strokes in the dataset.  So in order to keep all of the stroke positive observations, I filled the null values with the mean bmi.

This brings me to the next discovery of the dataset - the stroke percentage was only 4.9%. That meant that the dataset is imbalanced, making it hard for predictive modeling to classify correctly.  This imbalance issue had to be addressed before doing any modeling:

Stroke Prediction EDA and Descriptive Modeling

Next,  the โ€˜idโ€™ field was dropped because it was a unique identifier for the patients which was not useful for any modeling purposes as a feature.  Then I started to dig-in to the numbers by first looking at the numeric features.  

 

Numeric Features for Stroke Probability Analysis

A heatmap correlation was done on the 3 numeric features - โ€˜ageโ€™, โ€˜bmiโ€™, and  โ€˜avg_glucose_level.โ€™It revealed  that they were weakly correlated with each other:

Stroke Prediction EDA and Descriptive Modeling

As for the distribution, I contrasted each of them with respect to the presence of Stroke to see the difference:

Stroke Prediction EDA and Descriptive Modeling

The plot above makes it clear that the older you get, the higher your chance of experiencing a stroke becomes. That risk increases dramatically after the age of 50.

Stroke Prediction EDA and Descriptive Modeling

Interestingly, the plot above shows results that are contrary to my assumption of  a higher correlation between BMI and stroke.  My thinking was that higher BMI correlated to a  high body fat percentage in general. However,  the plot shows that high BMI is not necessarily a significant factor. There is  just a slight increase in the bmi range of overweight and obese (beyond the >25 bmi).  

The guide for BMI according to National Institute of Health (NIH):

  • Less than 18.5 means that a person is underweight
  • Between 18.5 and 24.9 is ideal
  • Between 25 and 29.9 is overweight
  • Over 30 indicates obesity

Stroke Prediction EDA and Descriptive Modeling

It can be seen from the distribution that most people in the set are in healthy range of blood sugar with the exception of some people who have higher than 180 mg/dL having above normal levels of blood sugar, making up 11% of the records. Upon further investigation, these same 11% of people who have higher than 180mg/dL accounted for 32% or a third of all strokes.  

From the Blood Sugar and Stroke Density Distribution above, thereโ€™s no clear correlation between a high avg_glucose_level and the risk of stroke. However, an explanation for the rise in stroke probability density among the higher than 180mg/dL glucose level group could be attributed to the presence of diabetes. According to the American Diabetes Association, a reading between 180-200mg/dL is categorized as prediabetic, and a reading of more than 200mg/dL falls within the diabetic category.  Given that someone who has  diabetes has 1.5 times higher odds of having a stroke, this could be a very probable explanation for the 2nd bell-curve of stroke in the plot above.  

 

Here is the guide for Average Glucose level according to experts for reference: 

Less than 70 means blood sugar is below normal levels and requires treatment.

71-90 means blood sugar should be monitored and treated as necessary.

90-140 means normal. 

140-199 indicates prediabetes.

Higher than 200 indicates diabetes.  

 

Categorical Features of Stroke

In order to explore the categorical features - since many of them were binary fields with yes or no answer, I used bar charts to first show the attribute amount/count and then on a separate graph, showed the stroke percentage within each attribute to observe any trend.  Here for the blog, I included the stacked bar charts with the percentage of strokes within each sub-category that showed some trends:

 

Out of the 7 categorical features, both โ€˜genderโ€™ and โ€˜Residence_typeโ€™ (urban vs rural) didnโ€™t have much difference in each of its percentage of stroke.  For the rest of the 5 features shown above, having been married and having heart disease as well as hypertension do matter and increase the risk of stroke.  Also, having formerly smoked and currently smoking seem to have a slight increase compared to people who have never smoked or in the unknown category.  As for the work_type feature, the Never_worked and children categories donโ€™t have any presence of stroke which makes sense.  

These bar charts seemed to be intuitive until I did further investigation and cross-referenced each of them with the one feature that showed the most stark trend so far - โ€˜age.โ€™  I found that there were correlations in most of the categorical features with respect to โ€˜age.โ€™  Notice the โ€˜ageโ€™ in each of the following tables of categorical features with respect to the presence of stroke (1):

 

Thus the impact of โ€˜ageโ€™ is seen in each of the categorical features indicating that the increase of stroke percentage in each subcategory is not entirely due to its own merit but to โ€˜ageโ€™ as well.  Later on this will cause multicollinearity among our predictor variables that will need to be handled before modeling.  

 

EDA Insight & Learnings on Stroke

1) Age is a strong driving factor for the risk of stroke. 

2) Contrary to my assumption, BMI was not highly correlated to risk of Stroke. This came as a surprise as BMI is used to diagnose obesity which is often linked to other risks like heart disease and stroke.

3) Blood sugar was not correlated to stroke risk however, diabetes is a risk for stroke because it raises the risk by 1.5 times if your avg_glucose_level is greater than 200mg/dL reaching the diabetic category and that was reflected in this dataset.

4) Sometimes what appears to be a correlation on the surface isn't. For example, attributes like Heart disease, hypertension, ever_married and smoking_status all upon further analysis, pointed to age.

5) When dealing with null values, it's good to check what impact they may have in your target feature before removing them. It was found that 20% of the missing BMI values made up 1/6th (16%) of all strokes. 

 

Feature Engineering for Stroke Data

Before feature engineering and modeling, first I checked logistic regression assumptions to see which ones I have yet to satisfy:

The logistic regression assumes that there is minimal or no multicollinearity among the independent variables as The Correlation Heatmap showed no collinearity among the Numeric Features but Variance Inflation Factor will be used later on to further check this)

The logistic regression assumes that the independent variables are linearly related to the log of odds: 

   

 

Logistic regression usually requires a large sample size to predict properly. (will Upsample the stroke data using SMOTE technique)

The logistic regression with two classes assumes that the dependent variable is binary (already binary)

Logistic regression assumes the observations to be independent of each other. (independent as far as the source goes - no duplicate subjects)

In order to fulfill the rest of the assumptions and perform feature engineering, we first label encoded the binary features - โ€˜genderโ€™(Male 1), โ€˜ever_marriedโ€™(Yes 1), โ€˜Residence_typeโ€™(Urban 1).  Then tried ordinally encoding the features - โ€˜smoking_statusโ€™ along with โ€˜work_typeโ€™ and label encoding the numeric features into binary - โ€˜ageโ€™(over 50 or not), โ€˜bmiโ€™(over 25 or not), โ€˜avg_glucose_levelโ€™(over 180 or not).  After trying different types of feature encoding and modeling multiple times, it was found that the best training accuracy score was obtained from keeping all of the numeric features as original and only ordinal-encoding the โ€˜work_typeโ€™ while turning the โ€˜smoking_statusโ€™ into a binary variable (having smoked or not).

 

Features For Stroke Data - Selection

For feature selection, chi-square test was used.  Three features - โ€˜smoking_status,โ€™ โ€˜gender,โ€™ and โ€˜Residence_typeโ€™-- were found to have p-values higher than 0.05 indicating that they have an insignificant effect on the log odds of experiencing stroke.  However, after converting โ€˜smoking_statusโ€™ from an ordinally encoded to binary encoded, the p-value decreased, and โ€˜smoking_statusโ€™ came to have a significant effect on the risk of stroke.  โ€˜Residence_typeโ€™ and โ€˜genderโ€™ were withheld from being dropped in order to see further supporting evidence.  

Variance Inflation Factor was used to detect multicollinearity among the predictor variables. โ€˜Work_typeโ€™ was found to have the highest VIF value of 19.25 and was dropped.  โ€˜Bmiโ€™ had the second highest VIF value of 14.83 the first time around and then lowered to a value of 9.05 after dropping โ€˜work_type,โ€™ but โ€˜bmiโ€™ was withheld from being dropped to see further supporting evidence.  

Modeling

Now that some feature selection analysis is done and the issue of multicollinearity addressed, the data set was prepped for modeling by first being split into train and test in a stratified fashion with a 70-30% ratio.  Next, the training dataset minority class was upsampled from about 5% to 20% using SMOTE, an oversampling technique that generates synthetic samples from the minority class to obtain class-balanced training dataset.  

With the training data upsampled, it was ready to start modeling. For modeling, I implemented API formula method for model interpretability, utilized Logistic Regression with GridSearch to find best hyperparameters for my linear model and Random Forest for my non-linear model to pick up any non-linear relation and associations missed by linear model.  

API formula method 

Statsmodels API logit model was used for model interpretability.  From the model summary, โ€˜bmiโ€™ feature had an insignificant effect on the log odds of getting stroke indicated by z value greater than 0.05.  This further supported the earlier finding of โ€˜bmiโ€™ having a high VIF value which indicates multicollinearity.  Thus the โ€˜bmiโ€™ feature was dropped.  From here on, 8 features were used for predictive modeling to classify the target variable of stroke.  

Logistic Regression 

To find the optimal hyperparameters, GridSearch with KFold cross-validation was used.  The best parameters were chosen as {'C': 4.2813, 'penalty': 'l2'} with the following scores:

 The following shows the Logistic Regression with Ridge coefficients: 

Random Forest

To capture any non-linear dynamic and relation of the features with the target variable, Random Forest was used with Randomized Grid Search to yield the following best hyperparameters and scores:

Also, Feature Importance was extracted from the Random Forest model to show which features were the most explanatory in predicting stroke:

Conclusion

From the two types of models, Random Forest performed best with the following mean accuracy scores (it also performed better in terms of โ€˜roc_aucโ€™ score):  

Finally, it was seen from both models that compared to all of the other features, โ€˜ageโ€™ and โ€˜average glucose levelโ€™ were the most important predictors of stroke, respectively, together accounting for more than 80% of the variance in the risk of stroke.

Lastly, utilizing the API formula method from statsmodels, the following was interpreted from the model summary:

  • the odds of experiencing a stroke increases by a factor of 1.08 every year a person gets older
  • every unit increase in a person's average glucose level, the odds of experiencing a stroke increases by a factor of 1.0
  • for people who...
    • have hypertension, the odds of experiencing stroke increases by a factor of 0.61 on average
    • smoke or have smoked, the odds of experiencing stroke increases by a factor of 0.59 on average
    • have been married, the odds of experiencing stroke increases by a factor of 0.52 on average
    • have heart disease, the odds of experiencing stroke increases by a factor of 0.45 on average
    • live in an urban setting, the odds of experiencing stroke increases by a factor of 0.41 on average
  • for men, the odds of experiencing stroke increases by a factor of 0.44 on average compared to women

 

 

About Author

Augi Bold

NYC Data Science Academy Fellow with an Industrial Engineering background and experience in operations management and consulting. A dynamic professional with a thorough approach equipped with Python, R, and machine learning skills as well as Oracle Database SQL...
View all posts by Augi Bold >

Related Articles

Capstone
Catching Fraud in the Healthcare System
Capstone
Acquisition Due Dilligence Automation for Smaller Firms
Machine Learning
Beware of Feature Importance for Business Decisions
Data Visualization
Ames Iowa Home Sale Prediction
Machine Learning
The Best Bang for Your Buck in Ames, Iowa

Leave a Comment

Stroke Prediction EDA and Descriptive Modeling - DevArena August 23, 2021
[โ€ฆ] Source link [โ€ฆ]

View Posts by Categories

All Posts 2399 posts
AI 7 posts
AI Agent 2 posts
AI-based hotel recommendation 1 posts
AIForGood 1 posts
Alumni 60 posts
Animated Maps 1 posts
APIs 41 posts
Artificial Intelligence 2 posts
Artificial Intelligence 2 posts
AWS 13 posts
Banking 1 posts
Big Data 50 posts
Branch Analysis 1 posts
Capstone 206 posts
Career Education 7 posts
CLIP 1 posts
Community 72 posts
Congestion Zone 1 posts
Content Recommendation 1 posts
Cosine SImilarity 1 posts
Data Analysis 5 posts
Data Engineering 1 posts
Data Engineering 3 posts
Data Science 7 posts
Data Science News and Sharing 73 posts
Data Visualization 324 posts
Events 5 posts
Featured 37 posts
Function calling 1 posts
FutureTech 1 posts
Generative AI 5 posts
Hadoop 13 posts
Image Classification 1 posts
Innovation 2 posts
Kmeans Cluster 1 posts
LLM 6 posts
Machine Learning 364 posts
Marketing 1 posts
Meetup 144 posts
MLOPs 1 posts
Model Deployment 1 posts
Nagamas69 1 posts
NLP 1 posts
OpenAI 5 posts
OpenNYC Data 1 posts
pySpark 1 posts
Python 16 posts
Python 458 posts
Python data analysis 4 posts
Python Shiny 2 posts
R 404 posts
R Data Analysis 1 posts
R Shiny 560 posts
R Visualization 445 posts
RAG 1 posts
RoBERTa 1 posts
semantic rearch 2 posts
Spark 17 posts
SQL 1 posts
Streamlit 2 posts
Student Works 1687 posts
Tableau 12 posts
TensorFlow 3 posts
Traffic 1 posts
User Preference Modeling 1 posts
Vector database 2 posts
Web Scraping 483 posts
wukong138 1 posts

Our Recent Popular Posts

AI 4 AI: ChatGPT Unifies My Blog Posts
by Vinod Chugani
Dec 18, 2022
Meet Your Machine Learning Mentors: Kyle Gallatin
by Vivian Zhang
Nov 4, 2020
NICU Admissions and CCHD: Predicting Based on Data Analysis
by Paul Lee, Aron Berke, Bee Kim, Bettina Meier and Ira Villar
Jan 7, 2020

View Posts by Tags

#python #trainwithnycdsa 2019 2020 Revenue 3-points agriculture air quality airbnb airline alcohol Alex Baransky algorithm alumni Alumni Interview Alumni Reviews Alumni Spotlight alumni story Alumnus ames dataset ames housing dataset apartment rent API Application artist aws bank loans beautiful soup Best Bootcamp Best Data Science 2019 Best Data Science Bootcamp Best Data Science Bootcamp 2020 Best Ranked Big Data Book Launch Book-Signing bootcamp Bootcamp Alumni Bootcamp Prep boston safety Bundles cake recipe California Cancer Research capstone car price Career Career Day ChatGPT citibike classic cars classpass clustering Coding Course Demo Course Report covid 19 credit credit card crime frequency crops D3.js data data analysis Data Analyst data analytics data for tripadvisor reviews data science Data Science Academy Data Science Bootcamp Data science jobs Data Science Reviews Data Scientist Data Scientist Jobs data visualization database Deep Learning Demo Day Discount disney dplyr drug data e-commerce economy employee employee burnout employer networking environment feature engineering Finance Financial Data Science fitness studio Flask flight delay football gbm Get Hired ggplot2 googleVis H20 Hadoop hallmark holiday movie happiness healthcare frauds higgs boson Hiring hiring partner events Hiring Partners hotels housing housing data housing predictions housing price hy-vee Income industry Industry Experts Injuries Instructor Blog Instructor Interview insurance italki Job Job Placement Jobs Jon Krohn JP Morgan Chase Kaggle Kickstarter las vegas airport lasso regression Lead Data Scienctist Lead Data Scientist leaflet league linear regression Logistic Regression machine learning Maps market matplotlib Medical Research Meet the team meetup methal health miami beach movie music Napoli NBA netflix Networking neural network Neural networks New Courses NHL nlp NYC NYC Data Science nyc data science academy NYC Open Data nyc property NYCDSA NYCDSA Alumni Online Online Bootcamp Online Training Open Data painter pandas Part-time performance phoenix pollutants Portfolio Development precision measurement prediction Prework Programming public safety PwC python Python Data Analysis python machine learning python scrapy python web scraping python webscraping Python Workshop R R Data Analysis R language R Programming R Shiny r studio R Visualization R Workshop R-bloggers random forest Ranking recommendation recommendation system regression Remote remote data science bootcamp Scrapy scrapy visualization seaborn seafood type Selenium sentiment analysis sentiment classification Shiny Shiny Dashboard Spark Special Special Summer Sports statistics streaming Student Interview Student Showcase SVM Switchup Tableau teachers team team performance TensorFlow Testimonial tf-idf Top Data Science Bootcamp Top manufacturing companies Transfers tweets twitter videos visualization wallstreet wallstreetbets web scraping Weekend Course What to expect whiskey whiskeyadvocate wildfire word cloud word2vec XGBoost yelp youtube trending ZORI

NYC Data Science Academy

NYC Data Science Academy teaches data science, trains companies and their employees to better profit from data, excels at big data project consulting, and connects trained Data Scientists to our industry.

NYC Data Science Academy is licensed by New York State Education Department.

Get detailed curriculum information about our
amazing bootcamp!

Please enter a valid email address
Sign up completed. Thank you!

Offerings

  • HOME
  • DATA SCIENCE BOOTCAMP
  • ONLINE DATA SCIENCE BOOTCAMP
  • Professional Development Courses
  • CORPORATE OFFERINGS
  • HIRING PARTNERS
  • About

  • About Us
  • Alumni
  • Blog
  • FAQ
  • Contact Us
  • Refund Policy
  • Join Us
  • SOCIAL MEDIA

    ยฉ 2025 NYC Data Science Academy
    All rights reserved. | Site Map
    Privacy Policy | Terms of Service
    Bootcamp Application