Member:

XIAO YUE(22110867) Data cleaning

TU RUI(22093962) Data Analysis(EDA)

VAISHNAVI A/P YUDEYELJODI(22121712) Modelling and Evaluation

JIANG JIAYAN(22098312) Modelling and Evaluation

WANG PENGXIANG(22105619) EDA and Video Presentation

Dataset

Link: healthcare-dataset-stroke-data.csv

Title: Predicting stroke using machine learning

Year: 2023

Purpose of dataset: To predict stroke based on other attributes

Objectives:

-Objective 1: To identify which factors have the most influence on stroke prediction

-Objective 2: To predict whether a patient is likely to experience a stroke based on various health parameters and attributes

-Objective 3: To evaluate different machine learning models and select the most accurate and reliable model for stroke prediction

#install.packages(" ")
library(data.table)
library(visdat)
library(ggplot2)
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.3     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ lubridate 1.9.3     ✔ tibble    3.2.1
## ✔ purrr     1.0.2     ✔ tidyr     1.3.0
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::between()     masks data.table::between()
## ✖ dplyr::filter()      masks stats::filter()
## ✖ dplyr::first()       masks data.table::first()
## ✖ lubridate::hour()    masks data.table::hour()
## ✖ lubridate::isoweek() masks data.table::isoweek()
## ✖ dplyr::lag()         masks stats::lag()
## ✖ dplyr::last()        masks data.table::last()
## ✖ lubridate::mday()    masks data.table::mday()
## ✖ lubridate::minute()  masks data.table::minute()
## ✖ lubridate::month()   masks data.table::month()
## ✖ lubridate::quarter() masks data.table::quarter()
## ✖ lubridate::second()  masks data.table::second()
## ✖ purrr::transpose()   masks data.table::transpose()
## ✖ lubridate::wday()    masks data.table::wday()
## ✖ lubridate::week()    masks data.table::week()
## ✖ lubridate::yday()    masks data.table::yday()
## ✖ lubridate::year()    masks data.table::year()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(moments)
# reading the dataset

data <- fread("D:/wpxdata/Thur04/healthcare-dataset-stroke-data.csv")

# about the dataset
dim(data) # dimension
## [1] 5110   12
head(data) # content
##       id gender age hypertension heart_disease ever_married     work_type
## 1:  9046   Male  67            0             1          Yes       Private
## 2: 51676 Female  61            0             0          Yes Self-employed
## 3: 31112   Male  80            0             1          Yes       Private
## 4: 60182 Female  49            0             0          Yes       Private
## 5:  1665 Female  79            1             0          Yes Self-employed
## 6: 56669   Male  81            0             0          Yes       Private
##    Residence_type avg_glucose_level  bmi  smoking_status stroke
## 1:          Urban            228.69 36.6 formerly smoked      1
## 2:          Rural            202.21  N/A    never smoked      1
## 3:          Rural            105.92 32.5    never smoked      1
## 4:          Urban            171.23 34.4          smokes      1
## 5:          Rural            174.12   24    never smoked      1
## 6:          Urban            186.21   29 formerly smoked      1
str(data) # structure
## Classes 'data.table' and 'data.frame':   5110 obs. of  12 variables:
##  $ id               : int  9046 51676 31112 60182 1665 56669 53882 10434 27419 60491 ...
##  $ gender           : chr  "Male" "Female" "Male" "Female" ...
##  $ age              : num  67 61 80 49 79 81 74 69 59 78 ...
##  $ hypertension     : int  0 0 0 0 1 0 1 0 0 0 ...
##  $ heart_disease    : int  1 0 1 0 0 0 1 0 0 0 ...
##  $ ever_married     : chr  "Yes" "Yes" "Yes" "Yes" ...
##  $ work_type        : chr  "Private" "Self-employed" "Private" "Private" ...
##  $ Residence_type   : chr  "Urban" "Rural" "Rural" "Urban" ...
##  $ avg_glucose_level: num  229 202 106 171 174 ...
##  $ bmi              : chr  "36.6" "N/A" "32.5" "34.4" ...
##  $ smoking_status   : chr  "formerly smoked" "never smoked" "never smoked" "smokes" ...
##  $ stroke           : int  1 1 1 1 1 1 1 1 1 1 ...
##  - attr(*, ".internal.selfref")=<externalptr>
summary(data) # summary
##        id           gender               age         hypertension    
##  Min.   :   67   Length:5110        Min.   : 0.08   Min.   :0.00000  
##  1st Qu.:17741   Class :character   1st Qu.:25.00   1st Qu.:0.00000  
##  Median :36932   Mode  :character   Median :45.00   Median :0.00000  
##  Mean   :36518                      Mean   :43.23   Mean   :0.09746  
##  3rd Qu.:54682                      3rd Qu.:61.00   3rd Qu.:0.00000  
##  Max.   :72940                      Max.   :82.00   Max.   :1.00000  
##  heart_disease     ever_married        work_type         Residence_type    
##  Min.   :0.00000   Length:5110        Length:5110        Length:5110       
##  1st Qu.:0.00000   Class :character   Class :character   Class :character  
##  Median :0.00000   Mode  :character   Mode  :character   Mode  :character  
##  Mean   :0.05401                                                           
##  3rd Qu.:0.00000                                                           
##  Max.   :1.00000                                                           
##  avg_glucose_level     bmi            smoking_status         stroke       
##  Min.   : 55.12    Length:5110        Length:5110        Min.   :0.00000  
##  1st Qu.: 77.25    Class :character   Class :character   1st Qu.:0.00000  
##  Median : 91.89    Mode  :character   Mode  :character   Median :0.00000  
##  Mean   :106.15                                          Mean   :0.04873  
##  3rd Qu.:114.09                                          3rd Qu.:0.00000  
##  Max.   :271.74                                          Max.   :1.00000

Data Cleaning

library(data.table)
library(visdat)
library(ggplot2)
library(tidyverse)
library(moments)
#Step 1 to deal with missing values
# Counting Missing Values
missing_summary <- as.data.frame(sapply(data, function(x) sum(is.na(x)) / length(x)))

# Print all missing values
print(missing_summary)
##                   sapply(data, function(x) sum(is.na(x))/length(x))
## id                                                                0
## gender                                                            0
## age                                                               0
## hypertension                                                      0
## heart_disease                                                     0
## ever_married                                                      0
## work_type                                                         0
## Residence_type                                                    0
## avg_glucose_level                                                 0
## bmi                                                               0
## smoking_status                                                    0
## stroke                                                            0
# Plotting the missing value matrix using vis_dat()
vis_dat(data)

# Deletion of missing values in behavioural units
data <- data[complete.cases(data), ]
#Step 2 Processing of duplicate values
# Detecting Repeat Values
duplicate_rows <- data[duplicated(data$id), ]

print(duplicate_rows)
## Empty data.table (0 rows and 12 cols): id,gender,age,hypertension,heart_disease,ever_married...
# Remove Duplicate Values
data <- unique(data)
#Step 3 deals with the type of value
# Converting col_name columns to characters
data[,gender:= as.character(gender)]

data[,ever_married:= as.character(ever_married)]

data[,work_type:= as.character(work_type)]

data[,Residence_type:= as.character(Residence_type)]

data[,smoking_status:= as.character(smoking_status)]


# Converting col_name columns to numeric values
data[, id:= as.numeric(id)]

data[, age := as.numeric(age)]

data[,hypertension := as.numeric(hypertension)]

data[, heart_disease := as.numeric(heart_disease)]

data[,avg_glucose_level := as.numeric(avg_glucose_level)]

data[, bmi := as.numeric(bmi)]
## Warning in eval(jsub, SDenv, parent.frame()): 强制改变过程中产生了NA
data[,stroke := as.numeric(stroke)]
#Step 4 Handling Discrete Values
# Remove outliers based on the Z-score of the col_name column (the score is human determined)
z_scores <- (data$bmi - mean(data$bmi)) / sd(data$bmi)
threshold <- 3  # Set the threshold value, values above the threshold are outliers
# data <- data[abs(z_scores) <= threshold, ] 
# I commented out the code above because it makes the "data" empty
# and does not generate any plots after this code



z_scores <- (data$age - mean(data$age)) / sd(data$age)
threshold <- 3  
data <- data[abs(z_scores) <= threshold, ]



z_scores <- ((data$avg_glucose_level - mean(data$avg_glucose_level)) / sd(data$avg_glucose_level))
threshold <- 3  
data <- data[abs(z_scores) <= threshold, ]
#Step 5 Check that the data conforms to a normal distribution (one of three choices)
# Select the columns to be processed
column <- data$avg_glucose_level
# Histograms specify the dataset and the columns to be used
histogram <- ggplot(data, aes(x = avg_glucose_level))
# Add a histogram layer, set bar widths and colours
histogram <- histogram + geom_histogram(binwidth = 0.6, fill = "#fffbf1", color = "#3498db")
# Add title and axis labels
histogram <- histogram + labs(title = "Histogram_avg_glucose_level", x = "Values", y = "Frequency") 

print(histogram)

column <- data$bmi
# Histograms specify the dataset and the columns to be used
histogram1 <- ggplot(data, aes(x = bmi))
# Add a histogram layer, set bar widths and colours
histogram1 <- histogram1 + geom_histogram(binwidth = 1, fill = "#fffbf1", color = "#5232db")
# Add title and axis labels
histogram1 <- histogram1 + labs(title = "Histogram_bmi", x = "Values", y = "Frequency") 

print(histogram1)
## Warning: Removed 198 rows containing non-finite values (`stat_bin()`).

# Select the columns to be processed
column <- data$agel
# Density map specifies the dataset and the columns to be used
density_plot <- ggplot(data, aes(x = age))
# Add a density map layer, set the fill colour and border colour
density_plot <- density_plot + geom_density(fill = "steelblue", color = "white") 
# Add title and axis labels
density_plot <- density_plot + labs(title = "Density Plot_age", x = "Values", y = "Density") 

print(density_plot)

write.csv(data, "cleaned-stroke-dataset.csv", row.names = FALSE)

Data Analysis: Exploratory Data Analysis (EDA)

Objective 1: To identify which factors have the most influence on stroke prediction

# library(data.table)
# library(ggplot2)
library(dplyr)
#Reading the cleaned dataset
data <- fread("cleaned-stroke-dataset.csv")

#Visualisation of all diagrams
# data %>%
#   gather(key = "variable", value = "value") %>%
#   ggplot(aes(x = value)) +
#   geom_bar() +
#   facet_wrap(~ variable, scales = "free") +
#   labs(title = "Barplot of Multiple Columns", x = "Values", y = "Count") +
#   theme_minimal()

#Drawing and analysing correlations
#Relationship between age and stroke
ggplot(data, aes(x = data$age, y = data$stroke)) + 
  geom_point() + 
  labs(title = "Scatter plot of age and stroke", x = "age", y = "stroke")

#Relationship between gender and stroke
df_filtered <- data %>% filter(stroke == 1)  

ggplot(df_filtered, aes(x = gender, fill = gender)) +
  geom_bar() +
  labs(title = "Distribution of Gender for stroke", x = "Gender", y = "Count") +
  scale_fill_manual(values = c("male" = "skyblue", "female" = "pink"))

#Relationship between hypertension and stroke

ggplot(df_filtered, aes(x = hypertension, fill = hypertension)) +
  geom_bar() +
  labs(title = "Distribution of hypertension for stroke", x = "hypertension", y = "Count") +
  scale_fill_manual(values = c("0" = "skyblue", "1" = "pink"))
## Warning: The following aesthetics were dropped during statistical transformation: fill
## ℹ This can happen when ggplot fails to infer the correct grouping structure in
##   the data.
## ℹ Did you forget to specify a `group` aesthetic or to convert a numerical
##   variable into a factor?

#Relationship between heart_disease and stroke

ggplot(df_filtered, aes(x = heart_disease, fill = heart_disease)) +
  geom_bar() +
  labs(title = "Distribution of heart_disease for stroke", x = "heart_disease", y = "Count") +
  scale_fill_manual(values = c("0" = "skyblue", "1" = "pink"))
## Warning: The following aesthetics were dropped during statistical transformation: fill
## ℹ This can happen when ggplot fails to infer the correct grouping structure in
##   the data.
## ℹ Did you forget to specify a `group` aesthetic or to convert a numerical
##   variable into a factor?

#Relationship between work_type and stroke

ggplot(df_filtered, aes(x = work_type, fill = work_type)) +
  geom_bar() +
  labs(title = "Distribution of work_type for stroke", x = "work_type", y = "Count") +
  scale_fill_manual(values = c("0" = "skyblue", "1" = "pink"))

#Relationship between Residence_type and stroke
ggplot(df_filtered, aes(x = Residence_type, fill = Residence_type)) +
  geom_bar() +
  labs(title = "Distribution of Residence_type for stroke", x = "Residence_type", y = "Count") +
  scale_fill_manual(values = c("0" = "skyblue", "1" = "pink"))

#Relationship between avg_glucose_level and stroke
ggplot(data, aes(x = data$avg_glucose_level, y = data$stroke)) + 
  geom_point() + 
  labs(title = "Scatter plot of avg_glucose_level and stroke", x = "avg_glucose_level", y = "stroke")

#Relationship between bmi and stroke
ggplot(data, aes(x = data$bmi, y = data$stroke)) + 
  geom_point() + 
  labs(title = "Scatter plot of bmi and stroke", x = "bmi", y = "stroke")
## Warning: Removed 198 rows containing missing values (`geom_point()`).

#Relationship between smoking_status and stroke

ggplot(df_filtered, aes(x = smoking_status, fill = smoking_status)) +
  geom_bar() +
  labs(title = "Distribution of smoking_status for stroke", x = "smoking_status", y = "Count") +
  scale_fill_manual(values = c("0" = "skyblue", "1" = "pink"))

# Analysing the effects of hypertension and heart_disease on stroke

  sum_ab = data$hypertension+data$heart_disease


# Scatterplotting
ggplot(data, aes(x = sum_ab, y = stroke)) +
  geom_point() + 
  geom_smooth(method = "lm", se = FALSE) +
  labs(title = "Scatter plot of (hypertension+heart_disease) vs stroke with correlation line",
       x = "attributes", y = "stroke")
## `geom_smooth()` using formula = 'y ~ x'

# Calculating relevance
correlation <- cor(sum_ab, data$stroke)
print(paste("Correlation coefficient:", correlation))
## [1] "Correlation coefficient: 0.161733987337129"
# Analysing the effects of hypertension, heart_disease and avg_glucose_level on stroke

sum_ab = data$hypertension+data$heart_disease+data$avg_glucose_level


# Scatterplotting
ggplot(data, aes(x = sum_ab, y = stroke)) +
  geom_point() + 
  geom_smooth(method = "lm", se = FALSE) +
  labs(title = "Scatter plot of (hypertension+heart_disease+heart_disease) vs stroke with correlation line",
       x = "attributes", y = "stroke")
## `geom_smooth()` using formula = 'y ~ x'

# Calculating relevance
correlation <- cor(sum_ab, data$stroke)
print(paste("Correlation coefficient:", correlation))
## [1] "Correlation coefficient: 0.121539955245848"
# Analysing the effects of hypertension, heart_disease, avg_glucose_level and bmi on stroke

sum_ab = data$hypertension+data$heart_disease+data$avg_glucose_level+data$bmi


# Scatterplotting
ggplot(data, aes(x = sum_ab, y = stroke)) +
  geom_point() + 
  geom_smooth(method = "lm", se = FALSE) +
  labs(title = "Scatter plot of (hypertension+heart_disease+heart_disease+bmi) vs stroke with correlation line",
       x = "attributes", y = "stroke")
## `geom_smooth()` using formula = 'y ~ x'
## Warning: Removed 198 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 198 rows containing missing values (`geom_point()`).

# Calculating relevance
correlation <- cor(sum_ab, data$stroke)
print(paste("Correlation coefficient:", correlation))
## [1] "Correlation coefficient: NA"

Data Modeling and Model Evaluation

Objective 2: To predict whether a patient is likely to experience a stroke based on various health parameters and attributes

Objective 3: To evaluate different machine learning models and selecting the most accurate and reliable model for stroke prediction

# data pre-processing
# to read cleaned data
df <- read.csv("D:/wpxdata/Thur04/cleaned.csv", header = T)

# to view loaded data
head(df)
##      id gender age hypertension heart_disease ever_married     work_type
## 1  9046   Male  67            0             1          Yes       Private
## 2 31112   Male  80            0             1          Yes       Private
## 3 60182 Female  49            0             0          Yes       Private
## 4  1665 Female  79            1             0          Yes Self-employed
## 5 56669   Male  81            0             0          Yes       Private
## 6 53882   Male  74            1             1          Yes       Private
##   Residence_type avg_glucose_level  bmi  smoking_status stroke
## 1          Urban            228.69 36.6 formerly smoked      1
## 2          Rural            105.92 32.5    never smoked      1
## 3          Urban            171.23 34.4          smokes      1
## 4          Rural            174.12 24.0    never smoked      1
## 5          Urban            186.21 29.0 formerly smoked      1
## 6          Rural             70.09 27.4    never smoked      1
glimpse(df)
## Rows: 4,790
## Columns: 12
## $ id                <int> 9046, 31112, 60182, 1665, 56669, 53882, 10434, 60491…
## $ gender            <chr> "Male", "Male", "Female", "Female", "Male", "Male", …
## $ age               <dbl> 67, 80, 49, 79, 81, 74, 69, 78, 81, 61, 54, 79, 50, …
## $ hypertension      <int> 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1…
## $ heart_disease     <int> 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0…
## $ ever_married      <chr> "Yes", "Yes", "Yes", "Yes", "Yes", "Yes", "No", "Yes…
## $ work_type         <chr> "Private", "Private", "Private", "Self-employed", "P…
## $ Residence_type    <chr> "Urban", "Rural", "Urban", "Rural", "Urban", "Rural"…
## $ avg_glucose_level <dbl> 228.69, 105.92, 171.23, 174.12, 186.21, 70.09, 94.39…
## $ bmi               <dbl> 36.6, 32.5, 34.4, 24.0, 29.0, 27.4, 22.8, 24.2, 29.7…
## $ smoking_status    <chr> "formerly smoked", "never smoked", "smokes", "never …
## $ stroke            <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1…
library(randomForest)
## randomForest 4.7-1.1
## Type rfNews() to see new features/changes/bug fixes.
## 
## 载入程辑包:'randomForest'
## The following object is masked from 'package:dplyr':
## 
##     combine
## The following object is masked from 'package:ggplot2':
## 
##     margin
model <- randomForest(stroke~., data = df)
## Warning in randomForest.default(m, y, ...): The response has five or fewer
## unique values.  Are you sure you want to do regression?
# feature importance analysis
importance <- randomForest::importance(model)
varImpPlot(model)

# convert importance matrix to a data frame for visualization
importance_df <- as.data.frame(importance)
importance_df$Variable <- row.names(importance_df)
# install and load required packages
# to use 'glimpse'
# install.packages("dplyr")
# library(dplyr)

# to use create 'createDataPartition', 'train', 'confusionMatrix'
# install.packages("caret")
library(caret)
## 载入需要的程辑包:lattice
## 
## 载入程辑包:'caret'
## The following object is masked from 'package:purrr':
## 
##     lift
# to use 'randomForest'
#install.packages("randomForest")
library(randomForest)
# data pre-processing

# remove id column
df <- subset(df, select = -id)
glimpse(df)
## Rows: 4,790
## Columns: 11
## $ gender            <chr> "Male", "Male", "Female", "Female", "Male", "Male", …
## $ age               <dbl> 67, 80, 49, 79, 81, 74, 69, 78, 81, 61, 54, 79, 50, …
## $ hypertension      <int> 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1…
## $ heart_disease     <int> 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0…
## $ ever_married      <chr> "Yes", "Yes", "Yes", "Yes", "Yes", "Yes", "No", "Yes…
## $ work_type         <chr> "Private", "Private", "Private", "Self-employed", "P…
## $ Residence_type    <chr> "Urban", "Rural", "Urban", "Rural", "Urban", "Rural"…
## $ avg_glucose_level <dbl> 228.69, 105.92, 171.23, 174.12, 186.21, 70.09, 94.39…
## $ bmi               <dbl> 36.6, 32.5, 34.4, 24.0, 29.0, 27.4, 22.8, 24.2, 29.7…
## $ smoking_status    <chr> "formerly smoked", "never smoked", "smokes", "never …
## $ stroke            <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1…
# check column with NA values
col_sums <- colSums(is.na(df)); col_sums # no NA values
##            gender               age      hypertension     heart_disease 
##                 0                 0                 0                 0 
##      ever_married         work_type    Residence_type avg_glucose_level 
##                 0                 0                 0                 0 
##               bmi    smoking_status            stroke 
##                 0                 0                 0
# convert categorical values into numerical values
cols <- c('gender', 'ever_married', 'work_type', 'Residence_type', 'smoking_status')
for (col in cols) {
  df[[col]] <- as.numeric(factor(df[[col]], levels = unique(df[[col]])))
}
glimpse(df)
## Rows: 4,790
## Columns: 11
## $ gender            <dbl> 1, 1, 2, 2, 1, 1, 2, 2, 2, 2, 2, 2, 2, 1, 1, 2, 2, 2…
## $ age               <dbl> 67, 80, 49, 79, 81, 74, 69, 78, 81, 61, 54, 79, 50, …
## $ hypertension      <int> 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1…
## $ heart_disease     <int> 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0…
## $ ever_married      <dbl> 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1…
## $ work_type         <dbl> 1, 1, 1, 2, 1, 1, 1, 1, 1, 3, 1, 1, 2, 1, 1, 1, 3, 2…
## $ Residence_type    <dbl> 1, 2, 1, 2, 1, 2, 1, 1, 2, 2, 1, 1, 2, 1, 1, 1, 2, 1…
## $ avg_glucose_level <dbl> 228.69, 105.92, 171.23, 174.12, 186.21, 70.09, 94.39…
## $ bmi               <dbl> 36.6, 32.5, 34.4, 24.0, 29.0, 27.4, 22.8, 24.2, 29.7…
## $ smoking_status    <dbl> 1, 2, 3, 2, 1, 2, 2, 4, 2, 3, 3, 2, 2, 3, 3, 2, 3, 2…
## $ stroke            <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1…
# convert int to factor of the predictor
df$stroke <- factor(df$stroke)
class(df$stroke)
## [1] "factor"
# to check the pre-processed data
head(df)
##   gender age hypertension heart_disease ever_married work_type Residence_type
## 1      1  67            0             1            1         1              1
## 2      1  80            0             1            1         1              2
## 3      2  49            0             0            1         1              1
## 4      2  79            1             0            1         2              2
## 5      1  81            0             0            1         1              1
## 6      1  74            1             1            1         1              2
##   avg_glucose_level  bmi smoking_status stroke
## 1            228.69 36.6              1      1
## 2            105.92 32.5              2      1
## 3            171.23 34.4              3      1
## 4            174.12 24.0              2      1
## 5            186.21 29.0              1      1
## 6             70.09 27.4              2      1
glimpse(df)
## Rows: 4,790
## Columns: 11
## $ gender            <dbl> 1, 1, 2, 2, 1, 1, 2, 2, 2, 2, 2, 2, 2, 1, 1, 2, 2, 2…
## $ age               <dbl> 67, 80, 49, 79, 81, 74, 69, 78, 81, 61, 54, 79, 50, …
## $ hypertension      <int> 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1…
## $ heart_disease     <int> 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0…
## $ ever_married      <dbl> 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1…
## $ work_type         <dbl> 1, 1, 1, 2, 1, 1, 1, 1, 1, 3, 1, 1, 2, 1, 1, 1, 3, 2…
## $ Residence_type    <dbl> 1, 2, 1, 2, 1, 2, 1, 1, 2, 2, 1, 1, 2, 1, 1, 1, 2, 1…
## $ avg_glucose_level <dbl> 228.69, 105.92, 171.23, 174.12, 186.21, 70.09, 94.39…
## $ bmi               <dbl> 36.6, 32.5, 34.4, 24.0, 29.0, 27.4, 22.8, 24.2, 29.7…
## $ smoking_status    <dbl> 1, 2, 3, 2, 1, 2, 2, 4, 2, 3, 3, 2, 2, 3, 3, 2, 3, 2…
## $ stroke            <fct> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1…

Random Forest

# prediction using random forest
RF <- function(s, df, col) {
  
  # split data to train and test data
  trainIndex <- createDataPartition(col, p = s, list = F)
  data_train <- df[trainIndex,]
  data_test <- df[-trainIndex,]
  
  # create the random forest model
  model <- randomForest(stroke~., data = data_train)
  
  # make predictions
  x_test <- data_test[,1:10]
  y_test <- data_test[,11]
  predictions <- predict(model, x_test)
  cm <- confusionMatrix(predictions, y_test)
  
  return(cm)
  
}

# splitting data into train (80%) and test (20%)
split <- 0.80
rfresult <- RF(split, df, df$stroke); rfresult
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction   0   1
##          0 918  39
##          1   0   0
##                                           
##                Accuracy : 0.9592          
##                  95% CI : (0.9447, 0.9709)
##     No Information Rate : 0.9592          
##     P-Value [Acc > NIR] : 0.5425          
##                                           
##                   Kappa : 0               
##                                           
##  Mcnemar's Test P-Value : 1.166e-09       
##                                           
##             Sensitivity : 1.0000          
##             Specificity : 0.0000          
##          Pos Pred Value : 0.9592          
##          Neg Pred Value :    NaN          
##              Prevalence : 0.9592          
##          Detection Rate : 0.9592          
##    Detection Prevalence : 1.0000          
##       Balanced Accuracy : 0.5000          
##                                           
##        'Positive' Class : 0               
## 
# confusion matrix visualization - random forest
rfplt <- as.data.frame(rfresult$table)
rfplt$Prediction <- factor(rfplt$Prediction, levels=rev(levels(rfplt$Prediction)))

ggplot(rfplt, aes(Prediction,Reference, fill = Freq)) +
  geom_tile() + geom_text(aes(label = Freq)) +
  scale_fill_gradient(low = "#F7E6F7", high = "#9735A6") +
  labs(title = "Confusion Matrix for Prediction using Random Forest", x = "Prediction",y = "Reference") +
  scale_x_discrete(labels = c("1","0")) +
  scale_y_discrete(labels = c("0","1"))

# evaluating the model using cross-validation
train_control <- trainControl(method = "cv", number = 10)
model_eval <- train(stroke~., data = df, trControl = train_control); model_eval
## Random Forest 
## 
## 4790 samples
##   10 predictor
##    2 classes: '0', '1' 
## 
## No pre-processing
## Resampling: Cross-Validated (10 fold) 
## Summary of sample sizes: 4310, 4311, 4312, 4312, 4311, 4311, ... 
## Resampling results across tuning parameters:
## 
##   mtry  Accuracy   Kappa        
##    2    0.9590822   0.0000000000
##    6    0.9586647  -0.0007984829
##   10    0.9576204  -0.0027264859
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was mtry = 2.
# making predictions
x_test <- df[,1:10]
y_test <- df[,11]
predict <- predict(model_eval, x_test)
rfcm <- confusionMatrix(predict, y_test); rfcm
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction    0    1
##          0 4594  161
##          1    0   35
##                                           
##                Accuracy : 0.9664          
##                  95% CI : (0.9609, 0.9713)
##     No Information Rate : 0.9591          
##     P-Value [Acc > NIR] : 0.004922        
##                                           
##                   Kappa : 0.2943          
##                                           
##  Mcnemar's Test P-Value : < 2.2e-16       
##                                           
##             Sensitivity : 1.0000          
##             Specificity : 0.1786          
##          Pos Pred Value : 0.9661          
##          Neg Pred Value : 1.0000          
##              Prevalence : 0.9591          
##          Detection Rate : 0.9591          
##    Detection Prevalence : 0.9927          
##       Balanced Accuracy : 0.5893          
##                                           
##        'Positive' Class : 0               
## 
# confusion matrix visualization - cv + rf
cvrfplt <- as.data.frame(rfcm$table)
cvrfplt$Prediction <- factor(cvrfplt$Prediction, levels=rev(levels(cvrfplt$Prediction)))

# plotting the confusion matrix for cv + rf
ggplot(cvrfplt, aes(Prediction,Reference, fill = Freq)) +
  geom_tile() + geom_text(aes(label = Freq)) +
  scale_fill_gradient(low = "#F7E6EF", high = "#AB3578") +
  labs(title = "Confusion Matrix for Prediction using Random Forest after Cross-Validation", x = "Prediction",y = "Reference") +
  scale_x_discrete(labels = c("1","0")) +
  scale_y_discrete(labels = c("0","1"))

K-Nearest Neighbors

# prediction using K-Nearest Neighbors
KNN <- function(s, df, col) {
  
  # split data to train and test data
  trainIndex <- createDataPartition(col, p = s, list = F)
  data_train <- df[trainIndex,]
  data_test <- df[-trainIndex,]    
  
  # create the knn model
  model <- train(stroke~., data = data_train, method = "knn")
  
  # make predictions
  x_test <- data_test[,1:10]
  y_test <- data_test[,11]
  predictions <- predict(model, x_test)
  cm <- confusionMatrix(predictions, y_test)
  
  return(list(model, cm))
  
}

# splitting data into train (80%) and test (20%)
split <- 0.80
knnresult <- KNN(split, df, df$stroke); knnresult
## [[1]]
## k-Nearest Neighbors 
## 
## 3833 samples
##   10 predictor
##    2 classes: '0', '1' 
## 
## No pre-processing
## Resampling: Bootstrapped (25 reps) 
## Summary of sample sizes: 3833, 3833, 3833, 3833, 3833, 3833, ... 
## Resampling results across tuning parameters:
## 
##   k  Accuracy   Kappa     
##   5  0.9441211  0.05110653
##   7  0.9496877  0.03612195
##   9  0.9536971  0.03071057
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was k = 9.
## 
## [[2]]
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction   0   1
##          0 916  39
##          1   2   0
##                                           
##                Accuracy : 0.9572          
##                  95% CI : (0.9423, 0.9691)
##     No Information Rate : 0.9592          
##     P-Value [Acc > NIR] : 0.6662          
##                                           
##                   Kappa : -0.004          
##                                           
##  Mcnemar's Test P-Value : 1.885e-08       
##                                           
##             Sensitivity : 0.9978          
##             Specificity : 0.0000          
##          Pos Pred Value : 0.9592          
##          Neg Pred Value : 0.0000          
##              Prevalence : 0.9592          
##          Detection Rate : 0.9572          
##    Detection Prevalence : 0.9979          
##       Balanced Accuracy : 0.4989          
##                                           
##        'Positive' Class : 0               
## 
# confusion matrix visualization - knn
knnplt <- as.data.frame(knnresult[[2]]$table)
knnplt$Prediction <- factor(knnplt$Prediction, levels=rev(levels(knnplt$Prediction)))

ggplot(knnplt, aes(Prediction,Reference, fill = Freq)) +
  geom_tile() + geom_text(aes(label = Freq)) +
  scale_fill_gradient(low = "#E7E6F7", high = "#5135A6") +
  labs(title = "Confusion Matrix for Prediction using KNN", x = "Prediction",y = "Reference") +
  scale_x_discrete(labels = c("1","0")) +
  scale_y_discrete(labels = c("0","1"))

# evaluating the model using cross-validation
train_control <- trainControl(method = "cv", number = 10)
model_eval <- train(stroke~., data = df, trControl = train_control, 
                    method = 'knn'); model_eval
## k-Nearest Neighbors 
## 
## 4790 samples
##   10 predictor
##    2 classes: '0', '1' 
## 
## No pre-processing
## Resampling: Cross-Validated (10 fold) 
## Summary of sample sizes: 4311, 4311, 4311, 4311, 4311, 4311, ... 
## Resampling results across tuning parameters:
## 
##   k  Accuracy   Kappa       
##   5  0.9546968   0.007920763
##   7  0.9578292  -0.002327410
##   9  0.9584555  -0.001160536
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was k = 9.
# making predictions
x_test <- df[,1:10]
y_test <- df[,11]
predict <- predict(model_eval, x_test)
knncm <- confusionMatrix(predict, y_test); knncm
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction    0    1
##          0 4594  196
##          1    0    0
##                                           
##                Accuracy : 0.9591          
##                  95% CI : (0.9531, 0.9645)
##     No Information Rate : 0.9591          
##     P-Value [Acc > NIR] : 0.519           
##                                           
##                   Kappa : 0               
##                                           
##  Mcnemar's Test P-Value : <2e-16          
##                                           
##             Sensitivity : 1.0000          
##             Specificity : 0.0000          
##          Pos Pred Value : 0.9591          
##          Neg Pred Value :    NaN          
##              Prevalence : 0.9591          
##          Detection Rate : 0.9591          
##    Detection Prevalence : 1.0000          
##       Balanced Accuracy : 0.5000          
##                                           
##        'Positive' Class : 0               
## 
# confusion matrix visualization - cv + knn
cvknnplt <- as.data.frame(knncm$table)
cvknnplt$Prediction <- factor(cvknnplt$Prediction, levels=rev(levels(cvknnplt$Prediction)))

# plotting the confusion matrix for cv + knn
ggplot(cvknnplt, aes(Prediction,Reference, fill = Freq)) +
  geom_tile() + geom_text(aes(label = Freq)) +
  scale_fill_gradient(low = "#E6F7EE", high = "#35AB6C") +
  labs(title = "Confusion Matrix for Prediction using KNN after Cross-Validation", x = "Prediction",y = "Reference") +
  scale_x_discrete(labels = c("1","0")) +
  scale_y_discrete(labels = c("0","1"))

Logistic Regression

# load necessary libraries
library(readr)
library(caret)
library(pROC)
## Type 'citation("pROC")' for a citation.
## 
## 载入程辑包:'pROC'
## The following objects are masked from 'package:stats':
## 
##     cov, smooth, var
library(ROSE)
## Loaded ROSE 0.0-4
data <- read_csv("D:/wpxdata/Thur04/cleaned.csv")
## Rows: 4790 Columns: 12
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (5): gender, ever_married, work_type, Residence_type, smoking_status
## dbl (7): id, age, hypertension, heart_disease, avg_glucose_level, bmi, stroke
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# convert categorical variables to factors
data$gender <- as.factor(data$gender)
data$ever_married <- as.factor(data$ever_married)
data$work_type <- as.factor(data$work_type)
data$Residence_type <- as.factor(data$Residence_type)
data$smoking_status <- as.factor(data$smoking_status)

# define and apply levels for categorical variables
categorical_cols <- c("gender", "ever_married", "work_type", "Residence_type", "smoking_status")
for(col in categorical_cols) {
  data[[col]] <- factor(data[[col]], levels = unique(data[[col]]))
}

# normalize numerical variables
numerical_cols <- c("age", "avg_glucose_level", "bmi")
preProcess_range_model <- preProcess(data[, numerical_cols], method = c("center", "scale"))
data[, numerical_cols] <- predict(preProcess_range_model, data[, numerical_cols])

# split the data into training and testing sets
set.seed(123)
trainIndex <- createDataPartition(data$stroke, p = .8, list = FALSE, times = 1)
trainData <- data[trainIndex, ]
testData <- data[-trainIndex, ]

# address class imbalance using ROSE's ovun.sample
balanced_data <- ovun.sample(stroke ~ ., data = trainData, method = "both", N = nrow(trainData), seed = 123)$data

# train a logistic regression model on the balanced dataset
model_lr_balanced <- glm(stroke ~ ., data = balanced_data, family = "binomial")

# Make predictions and evaluate the model
predictions_balanced <- predict(model_lr_balanced, testData, type = "response")

# ROC curve and find the optimal threshold
roc_curve_balanced <- roc(testData$stroke, predictions_balanced)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
# calculate the optimal threshold
optimal_idx <- which.max(roc_curve_balanced$sensitivities + roc_curve_balanced$specificities - 1)
optimal_threshold <- roc_curve_balanced$thresholds[optimal_idx]

prediction_class_balanced <- ifelse(predictions_balanced > optimal_threshold, 1, 0)

# confusion matrix
conf_matrix <- confusionMatrix(as.factor(prediction_class_balanced), as.factor(testData$stroke))
print(conf_matrix)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction   0   1
##          0 587   2
##          1 332  37
##                                           
##                Accuracy : 0.6514          
##                  95% CI : (0.6202, 0.6816)
##     No Information Rate : 0.9593          
##     P-Value [Acc > NIR] : 1               
##                                           
##                   Kappa : 0.1163          
##                                           
##  Mcnemar's Test P-Value : <2e-16          
##                                           
##             Sensitivity : 0.6387          
##             Specificity : 0.9487          
##          Pos Pred Value : 0.9966          
##          Neg Pred Value : 0.1003          
##              Prevalence : 0.9593          
##          Detection Rate : 0.6127          
##    Detection Prevalence : 0.6148          
##       Balanced Accuracy : 0.7937          
##                                           
##        'Positive' Class : 0               
## 
# ROC and AUC
roc_curve_balanced <- roc(testData$stroke, predictions_balanced)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
plot(roc_curve_balanced)

auc_value <- auc(roc_curve_balanced)
cat("Area under the curve:", auc_value, "\n")
## Area under the curve: 0.8340448
precision <- posPredValue(as.factor(prediction_class_balanced), as.factor(testData$stroke))
recall <- sensitivity(as.factor(prediction_class_balanced), as.factor(testData$stroke))
F1_score <- (2 * precision * recall) / (precision + recall)

cat("Precision:", precision, "\n")
## Precision: 0.9966044
cat("Recall:", recall, "\n")
## Recall: 0.6387378
cat("F1 Score:", F1_score, "\n")
## F1 Score: 0.7785146