WQD7004 Group Project

Group Member:

  1. Muhammad Imran Haiqal bin Azmi (17113547)
  2. Tasslim Bin Mansoor Ali (23056322)
  3. Muhammad Adib Bin Mohd Akbar (17119253)
  4. Muhammad Aiman bin Zolkifli (22080779)
  5. Nur Qistina binti Roslan (22089573)

Title

Risk of Diabetes Prediction

Introduction

Diabetes is a chronic disease associated with individuals inability to effectively regulate the glucose level in the blood, leading to diminished quality of life and reduced longevity. Individuals that are diagnosed with diabetes often suffer many health complications including heart disease, chronic kidney disease, nerve damage and mental health issues. The challenge is that diabetes patients are frequently diagnosed in the later stages of the disease when significant complications have already developed. Therefore, there is a need for a highly accurate model that can establish strong relationships between individuals’ background factors and risk of diabetes.

Objective

  1. To identify and quantify how certain individuals background (smoking habit, blood pressure, cholesterol levels) contribute to the progression of diabetes.
  2. To classify individuals based on their risk of developing diabetes, considering their background.
  3. To predict the severity level of health complication in individuals using key health indicators (BMI, smoker, physical activity, fruit and vegetable intake, heavy alcohol consumption, healthcare coverage, general health, doctor visitation, mental health, physical health, difficulty in walking, sex, age)

Libraries

library(tidyverse)
library(ggplot2)
library(caret)
library(dplyr)
library(Metrics)
library(e1071)
library(rpart)
library(pROC)
library(corrplot)
library(randomForest)
library(klaR)
library(pander)
library(reshape2)
## Warning: package 'reshape2' was built under R version 4.2.3
## 
## Attaching package: 'reshape2'
## The following object is masked from 'package:tidyr':
## 
##     smiths

Load our Dataset

data<-read_csv("diabetes.csv")
## Rows: 253680 Columns: 22
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## dbl (22): Diabetes_012, HighBP, HighChol, CholCheck, BMI, Smoker, Stroke, He...
## 
## ℹ 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.

Data Understanding

# Summary of dataset
glimpse(data)
## Rows: 253,680
## Columns: 22
## $ Diabetes_012         <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, 2, 0, 0, 0…
## $ HighBP               <dbl> 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1…
## $ HighChol             <dbl> 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1…
## $ CholCheck            <dbl> 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1…
## $ BMI                  <dbl> 40, 25, 28, 27, 24, 25, 30, 25, 30, 24, 25, 34, 2…
## $ Smoker               <dbl> 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0…
## $ Stroke               <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0…
## $ HeartDiseaseorAttack <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0…
## $ PhysActivity         <dbl> 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1…
## $ Fruits               <dbl> 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1…
## $ Veggies              <dbl> 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1…
## $ HvyAlcoholConsump    <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0…
## $ AnyHealthcare        <dbl> 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1…
## $ NoDocbcCost          <dbl> 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0…
## $ GenHlth              <dbl> 5, 3, 5, 2, 2, 2, 3, 3, 5, 2, 3, 3, 3, 4, 4, 2, 3…
## $ MentHlth             <dbl> 18, 0, 30, 0, 3, 0, 0, 0, 30, 0, 0, 0, 0, 0, 30, …
## $ PhysHlth             <dbl> 15, 0, 30, 0, 0, 2, 14, 0, 30, 0, 0, 30, 15, 0, 2…
## $ DiffWalk             <dbl> 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0…
## $ Sex                  <dbl> 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0…
## $ Age                  <dbl> 9, 7, 9, 11, 11, 10, 9, 11, 9, 8, 13, 10, 7, 11, …
## $ Education            <dbl> 4, 6, 4, 3, 5, 6, 6, 4, 5, 4, 6, 5, 5, 4, 6, 6, 4…
## $ Income               <dbl> 3, 1, 8, 6, 4, 8, 7, 4, 1, 3, 8, 1, 7, 6, 2, 8, 3…
# Structure of dataset
str(data)
## spc_tbl_ [253,680 × 22] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
##  $ Diabetes_012        : num [1:253680] 0 0 0 0 0 0 0 0 2 0 ...
##  $ HighBP              : num [1:253680] 1 0 1 1 1 1 1 1 1 0 ...
##  $ HighChol            : num [1:253680] 1 0 1 0 1 1 0 1 1 0 ...
##  $ CholCheck           : num [1:253680] 1 0 1 1 1 1 1 1 1 1 ...
##  $ BMI                 : num [1:253680] 40 25 28 27 24 25 30 25 30 24 ...
##  $ Smoker              : num [1:253680] 1 1 0 0 0 1 1 1 1 0 ...
##  $ Stroke              : num [1:253680] 0 0 0 0 0 0 0 0 0 0 ...
##  $ HeartDiseaseorAttack: num [1:253680] 0 0 0 0 0 0 0 0 1 0 ...
##  $ PhysActivity        : num [1:253680] 0 1 0 1 1 1 0 1 0 0 ...
##  $ Fruits              : num [1:253680] 0 0 1 1 1 1 0 0 1 0 ...
##  $ Veggies             : num [1:253680] 1 0 0 1 1 1 0 1 1 1 ...
##  $ HvyAlcoholConsump   : num [1:253680] 0 0 0 0 0 0 0 0 0 0 ...
##  $ AnyHealthcare       : num [1:253680] 1 0 1 1 1 1 1 1 1 1 ...
##  $ NoDocbcCost         : num [1:253680] 0 1 1 0 0 0 0 0 0 0 ...
##  $ GenHlth             : num [1:253680] 5 3 5 2 2 2 3 3 5 2 ...
##  $ MentHlth            : num [1:253680] 18 0 30 0 3 0 0 0 30 0 ...
##  $ PhysHlth            : num [1:253680] 15 0 30 0 0 2 14 0 30 0 ...
##  $ DiffWalk            : num [1:253680] 1 0 1 0 0 0 0 1 1 0 ...
##  $ Sex                 : num [1:253680] 0 0 0 0 0 1 0 0 0 1 ...
##  $ Age                 : num [1:253680] 9 7 9 11 11 10 9 11 9 8 ...
##  $ Education           : num [1:253680] 4 6 4 3 5 6 6 4 5 4 ...
##  $ Income              : num [1:253680] 3 1 8 6 4 8 7 4 1 3 ...
##  - attr(*, "spec")=
##   .. cols(
##   ..   Diabetes_012 = col_double(),
##   ..   HighBP = col_double(),
##   ..   HighChol = col_double(),
##   ..   CholCheck = col_double(),
##   ..   BMI = col_double(),
##   ..   Smoker = col_double(),
##   ..   Stroke = col_double(),
##   ..   HeartDiseaseorAttack = col_double(),
##   ..   PhysActivity = col_double(),
##   ..   Fruits = col_double(),
##   ..   Veggies = col_double(),
##   ..   HvyAlcoholConsump = col_double(),
##   ..   AnyHealthcare = col_double(),
##   ..   NoDocbcCost = col_double(),
##   ..   GenHlth = col_double(),
##   ..   MentHlth = col_double(),
##   ..   PhysHlth = col_double(),
##   ..   DiffWalk = col_double(),
##   ..   Sex = col_double(),
##   ..   Age = col_double(),
##   ..   Education = col_double(),
##   ..   Income = col_double()
##   .. )
##  - attr(*, "problems")=<externalptr>
# Check if there is any NA value
colSums(is.na(data))
##         Diabetes_012               HighBP             HighChol 
##                    0                    0                    0 
##            CholCheck                  BMI               Smoker 
##                    0                    0                    0 
##               Stroke HeartDiseaseorAttack         PhysActivity 
##                    0                    0                    0 
##               Fruits              Veggies    HvyAlcoholConsump 
##                    0                    0                    0 
##        AnyHealthcare          NoDocbcCost              GenHlth 
##                    0                    0                    0 
##             MentHlth             PhysHlth             DiffWalk 
##                    0                    0                    0 
##                  Sex                  Age            Education 
##                    0                    0                    0 
##               Income 
##                    0
# Check if there is any empty string value
colSums(data=="")
##         Diabetes_012               HighBP             HighChol 
##                    0                    0                    0 
##            CholCheck                  BMI               Smoker 
##                    0                    0                    0 
##               Stroke HeartDiseaseorAttack         PhysActivity 
##                    0                    0                    0 
##               Fruits              Veggies    HvyAlcoholConsump 
##                    0                    0                    0 
##        AnyHealthcare          NoDocbcCost              GenHlth 
##                    0                    0                    0 
##             MentHlth             PhysHlth             DiffWalk 
##                    0                    0                    0 
##                  Sex                  Age            Education 
##                    0                    0                    0 
##               Income 
##                    0
# Checking duplicated values 
anyDuplicated(data)
## [1] 1243
# Remove the duplicated row 
duplicate_rows <- duplicated(data) 
data <- data[!duplicate_rows, ]
# Checking duplicated values 
anyDuplicated(data)
## [1] 0

Exploratory Data Analysis (EDA)

# Load the corrplot package
library(corrplot)

# Generate a random dataset for demonstration purposes
set.seed(123)

# Compute the correlation matrix
cor_matrix <- cor(data)

# Create a correlation heatmap
corrplot(cor_matrix, method = "color", type = "upper", order = "hclust", tl.cex = 0.7)

# New Column to determine the diabetes
data$diabetes_binary <- ifelse(data$Diabetes_012 > 0, "Diabetic", "Non-Diabetic")
data$diabetes_binary <- factor(data$diabetes_binary)

# Count the values of 
category_count <- table(data$diabetes_binary)
print(category_count)
## 
##     Diabetic Non-Diabetic 
##        39726       190055
# Plot the bar chart
barplot(category_count, main = "Bar Chart of Diabetes", xlab = "Categories", ylab = "Frequency", col = "skyblue")

# Relation of Diabetes with Blood Pressure
contingency_table <- table(data$diabetes_binary, data$HighBP)
df_contingency <- as.data.frame.matrix(contingency_table)
barplot(as.matrix(df_contingency), beside = TRUE, legend.text = TRUE, col = c("red", "blue"),
        main = "Relationship between Diabetes and BP Levels",
        xlab = "Diabetes Status", ylab = "Count")

# Relation of High Cholestrol with Diabetes
cholesterol_counts <- table(data$HighChol)
print(cholesterol_counts)
## 
##      0      1 
## 128273 101508
pie(cholesterol_counts, main = "Pie Chart: Cholesterol Levels",
    labels = c("Normal Cholesterol", "High Cholesterol"),
    col = c("red", "lightblue"))

# Relation of High BP with Diabetes
contingency_table1 <- table(data$diabetes_binary, data$HighChol)
df_contingency1 <- as.data.frame.matrix(contingency_table1)
barplot(as.matrix(df_contingency1), beside = TRUE, legend.text = TRUE, col = c("red", "blue"),
        main = "Relationship between Diabetes and Cholesterol",
        xlab = "Diabetes Status", ylab = "Count")

#Smoker vs diabetes
smoker_counts <- table(data$Smoker)
print(smoker_counts)
## 
##      0      1 
## 122781 107000
pie(smoker_counts,  main = "Smoking pie chart",col = rainbow(length(smoker_counts)))
legend("topright", c("Non-Smoker","Smoker"), cex = 0.8,
       fill = rainbow(length(smoker_counts)))

contingency_table2 <- table(data$diabetes_binary, data$Smoker)
df_contingency2 <- as.data.frame.matrix(contingency_table2)
df_contingency2
##                   0     1
## Diabetic      19222 20504
## Non-Diabetic 103559 86496
barplot(as.matrix(df_contingency2), beside = TRUE, legend.text = TRUE, col = c("red", "blue"),
        main = "Relationship between Diabetes and Smoking",
        xlab = "Diabetes Status", ylab = "Count")

# According to this data, smoking has minor effect on diabetes

#Heavy Alcohol Consumption vs Diabetes
alcohol_counts <- table(data$HvyAlcoholConsump)
print(alcohol_counts)
## 
##      0      1 
## 215831  13950
pie(alcohol_counts,  main = "alcohol pie chart",col = rainbow(length(alcohol_counts)))
legend("topright", c("Non HvyAlcoholConsumption","HvyAlcoholConsumption"), cex = 0.8,
       fill = rainbow(length(alcohol_counts)))

contingency_table3 <- table(data$diabetes_binary, data$HvyAlcoholConsump)
df_contingency3 <- as.data.frame.matrix(contingency_table3)
df_contingency3
##                   0     1
## Diabetic      38686  1040
## Non-Diabetic 177145 12910
barplot(as.matrix(df_contingency3), beside = TRUE, legend.text = TRUE, col = c("red", "blue"),
        main = "Relationship between Diabetes and Heavy Alcohol Consumption",
        xlab = "Diabetes Status", ylab = "Frequency")

#According to this data, there is insufficient data to prove that heavy alcohol effects diabetes.

#Gender and diabetes
ggplot(data, aes(x = Sex, fill = diabetes_binary)) +
  geom_bar(position = "dodge", color = "black") +
  labs(title = 'Diabetes Disease Frequency for Sex',
       x = 'Sex (0 = Female, 1 = Male)',
       y = 'Frequency') +
  scale_fill_manual(values = c('#AA1111', '#1CA53B'),
                    name = "Diabetes Status",
                    labels = c("Have Diabetic", "Healthy")) +
  theme_minimal()

#Relationship between bmi and diabetes
ggplot(data, aes(x = BMI, fill = diabetes_binary)) +
  geom_bar(position = "dodge", color = "black") +
  labs(title = 'Diabetes Disease Frequency for BMI',
       x = 'BMI',
       y = 'Frequency') +
  scale_fill_manual(values = c('#AA1111', '#1CA53B'),
                    name = "Diabetes Status",
                    labels = c("Have Diabetic", "Healthy")) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 0, hjust = 1))

#People range between 24-33 are more prone to have diabetes

#relationship between income and diabetes
ggplot(data, aes(x = Income, fill = diabetes_binary)) +
  geom_bar(position = "dodge", color = "black") +
  labs(title = 'Diabetes Disease Frequency for Income',
       x = 'Income',
       y = 'Frequency') +
  scale_fill_manual(values = c('#AA1111', '#1CA53B'),
                    name = "Diabetes Status",
                    labels = c("Have Diabetic", "Healthy")) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 0, hjust = 1))

#We can say that people with higher income are more diabetic


#Lifestyle
#physactivity
contingency_table4 <- table(data$diabetes_binary, data$PhysActivity)
df_contingency4 <- as.data.frame.matrix(contingency_table4)
df_contingency4
##                  0      1
## Diabetic     14527  25199
## Non-Diabetic 46743 143312
barplot(as.matrix(df_contingency4), beside = TRUE, legend.text = TRUE, col = c("red", "blue"),
        main = "Relationship between Diabetes and PhysActivity",
        xlab = "Diabetes Status", ylab = "Count")

#Lifestyle
#fruits
contingency_table5 <- table(data$diabetes_binary, data$Fruits)
df_contingency5 <- as.data.frame.matrix(contingency_table5)
df_contingency5
##                  0      1
## Diabetic     16432  23294
## Non-Diabetic 72501 117554
barplot(as.matrix(df_contingency5), beside = TRUE, legend.text = TRUE, col = c("red", "blue"),
        main = "Relationship between Diabetes and Fruits",
        xlab = "Diabetes Status", ylab = "Count")

#Lifestyle
#Veggies
contingency_table6 <- table(data$diabetes_binary, data$Veggies)
df_contingency6 <- as.data.frame.matrix(contingency_table6)
df_contingency6
##                  0      1
## Diabetic      9672  30054
## Non-Diabetic 37476 152579
barplot(as.matrix(df_contingency4), beside = TRUE, legend.text = TRUE, col = c("red", "blue"),
        main = "Relationship between Diabetes and Veggies",
        xlab = "Diabetes Status", ylab = "Count")

#Lifestyle practises such as physical activity and consumption of fruits and veggies reduces the risk of diabetes

# Binning
bins <- c(0, 18.5, 25, 30, 35, 40, Inf)
# Create a new variable "BMI_category" based on the bins
data$BMI_category <- cut(data$BMI, bins, labels = c("Underweight", "Normal", "Overweight", "Obese I", "Obese II", "Obese III"))


# Exploratory Data Analysis
# BMI vs General Health
ggplot(data, aes(x = GenHlth, fill = BMI_category)) +
  geom_bar(position = "dodge", stat = "count") +
  labs(title = "Bar Plot of BMI Categories vs. General Health",
       x = "BMI Category",
       y = "Count") +
  theme_minimal()


Modelling and evaluation

Regression Methods

Train-test Preparation

# possible number of health complication (0-4)
#Linear Regression of Health Complication with Diabetes
# Filtering the dataset to non-diabetes and pre-diabetes patients
data <- data %>% filter(data$Diabetes_012==0 | data$Diabetes_012==1 )

# Mutate new column that combine all health complications
data <- mutate(data, "Health_Complication" = HighChol + HighBP + Stroke + HeartDiseaseorAttack)

set.seed(123)  # Set a random seed for reproducibility
train_index <- createDataPartition(data$Health_Complication, p = 0.6, list = FALSE)
train_data <- data[train_index, ]
temp_data <- data[-train_index, ]

# Create validation and test sets
validation_index <- createDataPartition(temp_data$Health_Complication, p = 0.5, list = FALSE)
validation_data <- temp_data[validation_index, ]
test_data <- temp_data[-validation_index, ]

Multiple Linear Regression Modelling (RMSE = 0.8055)

# Define the model formula
model_comp <- Health_Complication ~ BMI + Smoker + PhysActivity + Fruits + Veggies + HvyAlcoholConsump + AnyHealthcare + GenHlth + NoDocbcCost + MentHlth + PhysHlth + DiffWalk + Sex + Age
model_formula <- model_comp

# Train the linear regression model
linear_model <- lm(model_formula, data = train_data)

# Summarize the model 
summary(linear_model)
## 
## Call:
## lm(formula = model_formula, data = train_data)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -2.3383 -0.5827 -0.0830  0.5420  3.7822 
## 
## Coefficients:
##                     Estimate Std. Error t value Pr(>|t|)    
## (Intercept)       -0.9691362  0.0183208 -52.898  < 2e-16 ***
## BMI                0.0137978  0.0003744  36.851  < 2e-16 ***
## Smoker             0.0572757  0.0048780  11.742  < 2e-16 ***
## PhysActivity       0.0094954  0.0057241   1.659   0.0972 .  
## Fruits            -0.0314192  0.0050764  -6.189 6.06e-10 ***
## Veggies           -0.0260755  0.0061689  -4.227 2.37e-05 ***
## HvyAlcoholConsump  0.0387549  0.0095197   4.071 4.68e-05 ***
## AnyHealthcare      0.1038907  0.0106160   9.786  < 2e-16 ***
## GenHlth            0.1767620  0.0028258  62.553  < 2e-16 ***
## NoDocbcCost        0.0535185  0.0087242   6.135 8.57e-10 ***
## MentHlth           0.0026645  0.0003461   7.700 1.38e-14 ***
## PhysHlth           0.0006481  0.0003452   1.877   0.0605 .  
## DiffWalk           0.1472531  0.0077908  18.901  < 2e-16 ***
## Sex                0.1528348  0.0048505  31.509  < 2e-16 ***
## Age                0.1101461  0.0007983 137.975  < 2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.805 on 116797 degrees of freedom
## Multiple R-squared:  0.2462, Adjusted R-squared:  0.2461 
## F-statistic:  2725 on 14 and 116797 DF,  p-value: < 2.2e-16
#analysis of variance
anova(linear_model)
## Analysis of Variance Table
## 
## Response: Health_Complication
##                       Df Sum Sq Mean Sq    F value    Pr(>F)    
## BMI                    1   1343  1342.8  2072.1896 < 2.2e-16 ***
## Smoker                 1   1358  1358.1  2095.8258 < 2.2e-16 ***
## PhysActivity           1    577   577.4   890.9971 < 2.2e-16 ***
## Fruits                 1      1     0.6     1.0025    0.3167    
## Veggies                1     95    95.4   147.2485 < 2.2e-16 ***
## HvyAlcoholConsump      1     22    21.8    33.5988 6.791e-09 ***
## AnyHealthcare          1    521   520.8   803.6626 < 2.2e-16 ***
## GenHlth                1   6683  6683.2 10313.5196 < 2.2e-16 ***
## NoDocbcCost            1     70    70.0   107.9846 < 2.2e-16 ***
## MentHlth               1     85    85.2   131.5439 < 2.2e-16 ***
## PhysHlth               1    142   142.3   219.6279 < 2.2e-16 ***
## DiffWalk               1   1075  1075.0  1659.0064 < 2.2e-16 ***
## Sex                    1    411   410.8   633.9904 < 2.2e-16 ***
## Age                    1  12336 12336.0 19037.0499 < 2.2e-16 ***
## Residuals         116797  75685     0.6                         
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
# Make predictions on the test set
predictions <- predict(linear_model, newdata = test_data)

# Evaluate the model performance
mse <- mean((predictions - test_data$Health_Complication)^2)
rmse <- sqrt(mse)
print(paste("Mean Squared Error:", mse))
## [1] "Mean Squared Error: 0.648982183022197"
print(paste("Root Mean Squared Error:", rmse))
## [1] "Root Mean Squared Error: 0.805594304238925"

Decision Tree Regression (RMSE = 0.8362)

#Decision Tree Regression
tree_model <- rpart(model_comp , data = train_data, method = "anova")
tree_prediction <- predict(tree_model, newdata = test_data)
mse <- mean((tree_prediction - test_data$Health_Complication)^2)
rmse <- sqrt(mse)
print(paste("Mean Squared Error:", mse))
## [1] "Mean Squared Error: 0.699301204668268"
print(paste("Root Mean Squared Error:", rmse))
## [1] "Root Mean Squared Error: 0.836242312172894"

Classification method

Train/test split data, Modelling, Predictions, Confusion Matrix

# Split the data for modelling
diabetes <-read.csv("diabetes.csv")  
#check for duplicated rows
anyDuplicated(diabetes)
## [1] 1243
#collect duplicated rows
duplicate_rows <- duplicated(diabetes)
#drop duplicated rows
diabetes <- diabetes[!duplicate_rows,]
glimpse(diabetes)
## Rows: 229,781
## Columns: 22
## $ Diabetes_012         <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, 2, 0, 0, 0…
## $ HighBP               <dbl> 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1…
## $ HighChol             <dbl> 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1…
## $ CholCheck            <dbl> 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1…
## $ BMI                  <dbl> 40, 25, 28, 27, 24, 25, 30, 25, 30, 24, 25, 34, 2…
## $ Smoker               <dbl> 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0…
## $ Stroke               <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0…
## $ HeartDiseaseorAttack <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0…
## $ PhysActivity         <dbl> 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1…
## $ Fruits               <dbl> 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1…
## $ Veggies              <dbl> 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1…
## $ HvyAlcoholConsump    <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0…
## $ AnyHealthcare        <dbl> 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1…
## $ NoDocbcCost          <dbl> 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0…
## $ GenHlth              <dbl> 5, 3, 5, 2, 2, 2, 3, 3, 5, 2, 3, 3, 3, 4, 4, 2, 3…
## $ MentHlth             <dbl> 18, 0, 30, 0, 3, 0, 0, 0, 30, 0, 0, 0, 0, 0, 30, …
## $ PhysHlth             <dbl> 15, 0, 30, 0, 0, 2, 14, 0, 30, 0, 0, 30, 15, 0, 2…
## $ DiffWalk             <dbl> 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0…
## $ Sex                  <dbl> 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0…
## $ Age                  <dbl> 9, 7, 9, 11, 11, 10, 9, 11, 9, 8, 13, 10, 7, 11, …
## $ Education            <dbl> 4, 6, 4, 3, 5, 6, 6, 4, 5, 4, 6, 5, 5, 4, 6, 6, 4…
## $ Income               <dbl> 3, 1, 8, 6, 4, 8, 7, 4, 1, 3, 8, 1, 7, 6, 2, 8, 3…
#re check the duplicated rows
anyDuplicated(diabetes)
## [1] 0
#convert data to factor
diabetes$Diabetes_012 <- as.factor(diabetes$Diabetes_012)
glimpse(diabetes)
## Rows: 229,781
## Columns: 22
## $ Diabetes_012         <fct> 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0, 2, 0, 0, 0…
## $ HighBP               <dbl> 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1…
## $ HighChol             <dbl> 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1…
## $ CholCheck            <dbl> 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1…
## $ BMI                  <dbl> 40, 25, 28, 27, 24, 25, 30, 25, 30, 24, 25, 34, 2…
## $ Smoker               <dbl> 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0…
## $ Stroke               <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0…
## $ HeartDiseaseorAttack <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0…
## $ PhysActivity         <dbl> 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1…
## $ Fruits               <dbl> 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1…
## $ Veggies              <dbl> 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1…
## $ HvyAlcoholConsump    <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0…
## $ AnyHealthcare        <dbl> 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1…
## $ NoDocbcCost          <dbl> 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0…
## $ GenHlth              <dbl> 5, 3, 5, 2, 2, 2, 3, 3, 5, 2, 3, 3, 3, 4, 4, 2, 3…
## $ MentHlth             <dbl> 18, 0, 30, 0, 3, 0, 0, 0, 30, 0, 0, 0, 0, 0, 30, …
## $ PhysHlth             <dbl> 15, 0, 30, 0, 0, 2, 14, 0, 30, 0, 0, 30, 15, 0, 2…
## $ DiffWalk             <dbl> 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0…
## $ Sex                  <dbl> 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0…
## $ Age                  <dbl> 9, 7, 9, 11, 11, 10, 9, 11, 9, 8, 13, 10, 7, 11, …
## $ Education            <dbl> 4, 6, 4, 3, 5, 6, 6, 4, 5, 4, 6, 5, 5, 4, 6, 6, 4…
## $ Income               <dbl> 3, 1, 8, 6, 4, 8, 7, 4, 1, 3, 8, 1, 7, 6, 2, 8, 3…
set.seed(123)
#split data 60% train, 40% test
trainIndex<-createDataPartition(diabetes$Diabetes_012, p=0.6, list=F)
data_train<-diabetes[trainIndex,]
data_test<-diabetes[-trainIndex,]  
x_test <- data_test[,2:22]
y_test <- data_test[,1]

Random Forest (Accuracy = 0.8334)

#RANDOM FOREST
# modelling random forest 
modelRF <- randomForest(Diabetes_012~., data=data_train)
#make predictions using random forest
predictionsRF <- predict(modelRF, x_test)
#Confusion matrix using random forest
cmRF<-confusionMatrix(predictionsRF, y_test)
cmRF
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction     0     1     2
##          0 74354  1697 11794
##          1     0     0     0
##          2  1668   154  2244
## 
## Overall Statistics
##                                          
##                Accuracy : 0.8334         
##                  95% CI : (0.831, 0.8358)
##     No Information Rate : 0.8271         
##     P-Value [Acc > NIR] : 2.285e-07      
##                                          
##                   Kappa : 0.1781         
##                                          
##  Mcnemar's Test P-Value : < 2.2e-16      
## 
## Statistics by Class:
## 
##                      Class: 0 Class: 1 Class: 2
## Sensitivity            0.9781  0.00000  0.15985
## Specificity            0.1509  1.00000  0.97660
## Pos Pred Value         0.8464      NaN  0.55189
## Neg Pred Value         0.5898  0.97986  0.86574
## Prevalence             0.8271  0.02014  0.15273
## Detection Rate         0.8090  0.00000  0.02441
## Detection Prevalence   0.9558  0.00000  0.04424
## Balanced Accuracy      0.5645  0.50000  0.56823

Summary of Evaluation

# multiple linear regression
linear_model_summary <- summary(linear_model)
rmse_linear <- sqrt(linear_model_summary$sigma^2)

# decision tree regression
tree_prediction <- predict(tree_model, newdata = test_data)
mse_tree <- mean((tree_prediction - test_data$Health_Complication)^2)
rmse_tree <- sqrt(mse_tree)

# Random Forest
predictionsRF <- predict(modelRF, x_test)
cmRF <- confusionMatrix(predictionsRF, y_test)
accuracy_rf <- cmRF$overall['Accuracy']

# Summary table
model_evaluations <- data.frame(
  ModelType = c("Regression", "Regression", "Classification"),
  ModelDescription = c("Multiple Linear Regression", "Decision Tree Regression", "Random Forest"),
  EvaluationMetric = c("RMSE", "RMSE", "Accuracy"),
  Value = c(rmse_linear, rmse_tree, accuracy_rf)
)
# Render the table
pander(model_evaluations)
ModelType ModelDescription EvaluationMetric Value
Regression Multiple Linear Regression RMSE 0.805
Regression Decision Tree Regression RMSE 0.8362
Classification Random Forest Accuracy 0.8334
# Confusion Matrix
confusion_matrix_melted <- melt(as.matrix(cmRF$table))
names(confusion_matrix_melted) <- c("Var1", "Var2", "value")

# Plotting the confusion matrix
ggplot(confusion_matrix_melted, aes(Var1, Var2, fill = value)) +
  geom_tile() +
  geom_text(aes(label = value), vjust = 1) +
  scale_fill_gradient(low = "white", high = "steelblue") +
  labs(title = "Confusion Matrix for Random Forest Model",
       x = "Predicted Label",
       y = "Actual Label") +
  theme_minimal()

Conclusion

In conclusion, we have predict the severity level of health complication in individuals using key health indicators for our regression section. Based on our observation, the Linear Regression model is the best model to predict the severity level of health complication in individuals with the lowest MSE and RMSE value. We have performed classification method which is Random Forest to classify diabetes given the independent variables and it shows significant accuracy prediction. Future enhancement can be considered on using other classification model that suitable for large dataset approach and perform model evaluation for selecting right parameter to perform best modelling.