Importing the packages and calling it by library function
library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.3.2
library(reshape2)
## Warning: package 'reshape2' was built under R version 4.3.2
library(imputeTS) ##for mean imputation
## Warning: package 'imputeTS' was built under R version 4.3.2
## Registered S3 method overwritten by 'quantmod':
## method from
## as.zoo.data.frame zoo
library(caTools) ##package for train test split
library(dplyr)
## Warning: package 'dplyr' was built under R version 4.3.2
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(ROCR)
## Warning: package 'ROCR' was built under R version 4.3.2
library(caret)
## Warning: package 'caret' was built under R version 4.3.2
## Loading required package: lattice
library(verification)
## Warning: package 'verification' was built under R version 4.3.2
## Loading required package: fields
## Warning: package 'fields' was built under R version 4.3.2
## Loading required package: spam
## Warning: package 'spam' was built under R version 4.3.2
## Spam version 2.10-0 (2023-10-23) is loaded.
## Type 'help( Spam)' or 'demo( spam)' for a short introduction
## and overview of this package.
## Help for individual functions is also obtained by adding the
## suffix '.spam' to the function name, e.g. 'help( chol.spam)'.
##
## Attaching package: 'spam'
## The following objects are masked from 'package:base':
##
## backsolve, forwardsolve
## Loading required package: viridisLite
## Warning: package 'viridisLite' was built under R version 4.3.2
##
## Try help(fields) to get started.
## Loading required package: boot
##
## Attaching package: 'boot'
## The following object is masked from 'package:lattice':
##
## melanoma
## Loading required package: CircStats
## Warning: package 'CircStats' was built under R version 4.3.2
## Loading required package: MASS
##
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
##
## select
## Loading required package: dtw
## Warning: package 'dtw' was built under R version 4.3.2
## Loading required package: proxy
##
## Attaching package: 'proxy'
## The following object is masked from 'package:spam':
##
## as.matrix
## The following objects are masked from 'package:stats':
##
## as.dist, dist
## The following object is masked from 'package:base':
##
## as.matrix
## Loaded dtw v1.23-1. See ?dtw for help, citation("dtw") for use in publication.
## Registered S3 method overwritten by 'verification':
## method from
## lines.roc pROC
Loaded the dataset from local system
df=read.csv("F:/Desktop items/datasets/diabetes.csv")
head(df)
## Pregnancies Glucose BloodPressure SkinThickness Insulin BMI
## 1 6 148 72 35 0 33.6
## 2 1 85 66 29 0 26.6
## 3 8 183 64 0 0 23.3
## 4 1 89 66 23 94 28.1
## 5 0 137 40 35 168 43.1
## 6 5 116 74 0 0 25.6
## DiabetesPedigreeFunction Age Outcome
## 1 0.627 50 1
## 2 0.351 31 0
## 3 0.672 32 1
## 4 0.167 21 0
## 5 2.288 33 1
## 6 0.201 30 0
tail(df)
## Pregnancies Glucose BloodPressure SkinThickness Insulin BMI
## 763 9 89 62 0 0 22.5
## 764 10 101 76 48 180 32.9
## 765 2 122 70 27 0 36.8
## 766 5 121 72 23 112 26.2
## 767 1 126 60 0 0 30.1
## 768 1 93 70 31 0 30.4
## DiabetesPedigreeFunction Age Outcome
## 763 0.142 33 0
## 764 0.171 63 0
## 765 0.340 27 0
## 766 0.245 30 0
## 767 0.349 47 1
## 768 0.315 23 0
Checking data types for all variables
str(df)
## 'data.frame': 768 obs. of 9 variables:
## $ Pregnancies : int 6 1 8 1 0 5 3 10 2 8 ...
## $ Glucose : int 148 85 183 89 137 116 78 115 197 125 ...
## $ BloodPressure : int 72 66 64 66 40 74 50 0 70 96 ...
## $ SkinThickness : int 35 29 0 23 35 0 32 0 45 0 ...
## $ Insulin : int 0 0 0 94 168 0 88 0 543 0 ...
## $ BMI : num 33.6 26.6 23.3 28.1 43.1 25.6 31 35.3 30.5 0 ...
## $ DiabetesPedigreeFunction: num 0.627 0.351 0.672 0.167 2.288 ...
## $ Age : int 50 31 32 21 33 30 26 29 53 54 ...
## $ Outcome : int 1 0 1 0 1 0 1 0 1 1 ...
sum(is.na(df))
## [1] 0
No missing values
sum(duplicated(df))
## [1] 0
No duplicate values Checking for inappropriate or zero values in variables
for (col in names(df)) {
zero_values <- sum(df[[col]] <= 0)
cat(paste('Zero values in column', col, '=', zero_values, '\n'))
}
## Zero values in column Pregnancies = 111
## Zero values in column Glucose = 5
## Zero values in column BloodPressure = 35
## Zero values in column SkinThickness = 227
## Zero values in column Insulin = 374
## Zero values in column BMI = 11
## Zero values in column DiabetesPedigreeFunction = 0
## Zero values in column Age = 0
## Zero values in column Outcome = 500
The BMI, Insulin, Skin thickness, Blood pressure and Glucose cannot have zero values so imputing it with the median values
col_containing_zero <- c("Glucose", "BloodPressure", "SkinThickness", "Insulin", "BMI")
for (col in col_containing_zero) {
median_value <- median(df[[col]], na.rm = TRUE)
df[df[[col]] <= 0, col] <- median_value
}
Again checking zero values after imputation
for (col in names(df)) {
zero_values <- sum(df[[col]] <= 0)
cat(paste('Zero values in column', col, '=', zero_values, '\n'))
}
## Zero values in column Pregnancies = 111
## Zero values in column Glucose = 0
## Zero values in column BloodPressure = 0
## Zero values in column SkinThickness = 0
## Zero values in column Insulin = 0
## Zero values in column BMI = 0
## Zero values in column DiabetesPedigreeFunction = 0
## Zero values in column Age = 0
## Zero values in column Outcome = 500
EXPLORATORY DATA ANALYSIS Comparison of patients with and without diabetes through Bar charts
df %>%
group_by(Outcome)%>%
summarise(n=n())%>%
ggplot(aes(x=Outcome,y=n))+
geom_bar(stat = 'identity',fill='purple')+
geom_label(aes(label=n))+
theme_minimal()+
labs(title = "Count of Diabetic patients and Non-Diabetic patients")+
theme(panel.grid = element_blank())+
theme(plot.title = element_text(hjust = 0.5))
Comparing different variables with diabetic and non diabetic
patients
dist_columns <- c('Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness', 'Insulin', 'BMI', 'DiabetesPedigreeFunction', 'Age')
for (col in dist_columns) {
ggplot(df, aes(x = !!sym(col))) +
geom_histogram(binwidth = 1, fill = 'blue', color = 'black', alpha = 0.7) +
geom_density(color = 'red') +
labs(title = paste("Distribution of", col, "column")) +
theme_minimal() +
theme(plot.title = element_text(hjust = 0.5)) +
scale_fill_manual(values = 'blue') +
scale_color_manual(values = 'black') +
facet_wrap(~1, scales = 'free_y') +
NULL
}
Obtaining correlations matrix
cor(df) ##computed correlation matrix
## Pregnancies Glucose BloodPressure SkinThickness
## Pregnancies 1.00000000 0.1282130 0.208615412 0.03256830
## Glucose 0.12821296 1.0000000 0.218937186 0.17214324
## BloodPressure 0.20861541 0.2189372 1.000000000 0.14780938
## SkinThickness 0.03256830 0.1721432 0.147809385 1.00000000
## Insulin -0.05569740 0.3575729 -0.028721243 0.23818837
## BMI 0.02154624 0.2313996 0.281132428 0.54695138
## DiabetesPedigreeFunction -0.03352267 0.1373269 -0.002378336 0.14297708
## Age 0.54434123 0.2669092 0.324915391 0.05451384
## Outcome 0.22189815 0.4927824 0.165722913 0.18906542
## Insulin BMI DiabetesPedigreeFunction
## Pregnancies -0.05569740 0.02154624 -0.033522673
## Glucose 0.35757290 0.23139957 0.137326919
## BloodPressure -0.02872124 0.28113243 -0.002378336
## SkinThickness 0.23818837 0.54695138 0.142977079
## Insulin 1.00000000 0.18902241 0.178029351
## BMI 0.18902241 1.00000000 0.153506351
## DiabetesPedigreeFunction 0.17802935 0.15350635 1.000000000
## Age -0.01541273 0.02574447 0.033561312
## Outcome 0.14845724 0.31224903 0.173844066
## Age Outcome
## Pregnancies 0.54434123 0.2218982
## Glucose 0.26690916 0.4927824
## BloodPressure 0.32491539 0.1657229
## SkinThickness 0.05451384 0.1890654
## Insulin -0.01541273 0.1484572
## BMI 0.02574447 0.3122490
## DiabetesPedigreeFunction 0.03356131 0.1738441
## Age 1.00000000 0.2383560
## Outcome 0.23835598 1.0000000
corr_mat=round(cor(df),2) ##rounded to 2 decimel
melted_corr_mat <- melt(corr_mat) #reduce the size of correlation matrix
Plotting the correlation heatmap with annotations
ggplot(data = melted_corr_mat, aes(x=Var1, y=Var2,
fill=value)) +
geom_tile()+
geom_text(aes(Var2, Var1, label = value),
color = "black", size = 4)
looking for missing values
sum(is.na(df$Pregnancies))
## [1] 0
sum(is.na(df$Glucose))
## [1] 0
sum(is.na(df$BloodPressure))
## [1] 0
sum(is.na(df$SkinThickness))
## [1] 0
sum(is.na(df$Insulin))
## [1] 0
sum(is.na(df$BMI))
## [1] 0
sum(is.na(df$Age))
## [1] 0
sum(is.na(df$Outcome))
## [1] 0
#so the data has no missing values
checking outliers using scatterlot
plot(df$Glucose)
plot(df$BloodPressure)
plot(df$SkinThickness)
plot(df$Insulin)
plot(df$BMI)
plot(df$Age)
it is observed that the above features have many outliers and the
outliers are zero values ####
###check for summary of data frame
summary(df)
## Pregnancies Glucose BloodPressure SkinThickness
## Min. : 0.000 Min. : 44.00 Min. : 24.00 Min. : 7.00
## 1st Qu.: 1.000 1st Qu.: 99.75 1st Qu.: 64.00 1st Qu.:23.00
## Median : 3.000 Median :117.00 Median : 72.00 Median :23.00
## Mean : 3.845 Mean :121.66 Mean : 72.39 Mean :27.33
## 3rd Qu.: 6.000 3rd Qu.:140.25 3rd Qu.: 80.00 3rd Qu.:32.00
## Max. :17.000 Max. :199.00 Max. :122.00 Max. :99.00
## Insulin BMI DiabetesPedigreeFunction Age
## Min. : 14.00 Min. :18.20 Min. :0.0780 Min. :21.00
## 1st Qu.: 30.50 1st Qu.:27.50 1st Qu.:0.2437 1st Qu.:24.00
## Median : 31.25 Median :32.00 Median :0.3725 Median :29.00
## Mean : 94.65 Mean :32.45 Mean :0.4719 Mean :33.24
## 3rd Qu.:127.25 3rd Qu.:36.60 3rd Qu.:0.6262 3rd Qu.:41.00
## Max. :846.00 Max. :67.10 Max. :2.4200 Max. :81.00
## Outcome
## Min. :0.000
## 1st Qu.:0.000
## Median :0.000
## Mean :0.349
## 3rd Qu.:1.000
## Max. :1.000
colSums(df==0) ##checking the number of zeros in each features
## Pregnancies Glucose BloodPressure
## 111 0 0
## SkinThickness Insulin BMI
## 0 0 0
## DiabetesPedigreeFunction Age Outcome
## 0 0 500
#replacing the zeros by imputing mean in each of the important features
##converting the zero values to NA
df$Glucose[df$Glucose==0]<-NA
df$BloodPressure[df$BloodPressure==0]<-NA
df$SkinThickness[df$SkinThickness==0]<-NA
df$Insulin[df$Insulin==0]<-NA
df$BMI[df$BMI==0]<-NA
df$Glucose<-round(na_mean(df$Glucose, option = "mean", maxgap = Inf),0)##this is only for mean imputation
df$BloodPressure<-round(na_mean(df$BloodPressure, option = "mean", maxgap = Inf),0)##this is only for mean imputation
df$SkinThickness<-round(na_mean(df$SkinThickness, option = "mean", maxgap = Inf),0)##this is only for mean imputation
df$Insulin<-round(na_mean(df$Insulin, option = "mean", maxgap = Inf),0)##this is only for mean imputation
df$BMI<-round(na_mean(df$BMI, option = "mean", maxgap = Inf),1)##this is only for mean imputation
Logistic Regression Model
##split features and target
X=df[-8] ##features
y=df[8] ##target
Splitting Train Test Data
##splitting the data into trainning and test data
set.seed(1)
sample <- sample.split(df, SplitRatio = 0.8)
train_df <- subset(df, sample == TRUE)
test_df <- subset(df, sample == FALSE)
##spliting the data set into outcome and features
train_X=train_df[-8]
train_y=train_df[8]
test_X=test_df[-8]
test_y=test_df[8]
#checking the dimensions
dim(train_y)
## [1] 598 1
dim(test_y)
## [1] 170 1
dim(train_X)
## [1] 598 8
dim(test_X)
## [1] 170 8
head(train_X)
## Pregnancies Glucose BloodPressure SkinThickness Insulin BMI
## 1 6 148 72 35 30 33.6
## 2 1 85 66 29 30 26.6
## 3 8 183 64 23 30 23.3
## 5 0 137 40 35 168 43.1
## 6 5 116 74 23 30 25.6
## 8 10 115 72 23 30 35.3
## DiabetesPedigreeFunction Outcome
## 1 0.627 1
## 2 0.351 0
## 3 0.672 1
## 5 2.288 1
## 6 0.201 0
## 8 0.134 0
head(train_df)
## Pregnancies Glucose BloodPressure SkinThickness Insulin BMI
## 1 6 148 72 35 30 33.6
## 2 1 85 66 29 30 26.6
## 3 8 183 64 23 30 23.3
## 5 0 137 40 35 168 43.1
## 6 5 116 74 23 30 25.6
## 8 10 115 72 23 30 35.3
## DiabetesPedigreeFunction Age Outcome
## 1 0.627 50 1
## 2 0.351 31 0
## 3 0.672 32 1
## 5 2.288 33 1
## 6 0.201 30 0
## 8 0.134 29 0
###Model training
logit_model<- glm( Outcome ~ Age+BMI+ Insulin+SkinThickness+BloodPressure+Glucose+Pregnancies,
data = train_df,
family = "binomial")
summary(logit_model)
##
## Call:
## glm(formula = Outcome ~ Age + BMI + Insulin + SkinThickness +
## BloodPressure + Glucose + Pregnancies, family = "binomial",
## data = train_df)
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -8.944320 0.926884 -9.650 < 2e-16 ***
## Age 0.013093 0.011144 1.175 0.240045
## BMI 0.090012 0.020229 4.450 8.6e-06 ***
## Insulin -0.000803 0.001030 -0.780 0.435433
## SkinThickness 0.003405 0.014198 0.240 0.810481
## BloodPressure -0.008891 0.009613 -0.925 0.355032
## Glucose 0.039618 0.004456 8.892 < 2e-16 ***
## Pregnancies 0.132927 0.036438 3.648 0.000264 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 766.25 on 597 degrees of freedom
## Residual deviance: 554.27 on 590 degrees of freedom
## AIC: 570.27
##
## Number of Fisher Scoring iterations: 5
###model testing
predict_model <- predict(logit_model,
test_df, type = "response")
###model performance
test_class<-ifelse(predict_model<=0.5, 0, 1) ###assuming 0.5 as the optimal threshold probability
test_class
## 4 7 13 16 22 25 31 34 40 43 49 52 58 61 67 70 76 79 85 88
## 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0
## 94 97 103 106 112 115 121 124 130 133 139 142 148 151 157 160 166 169 175 178
## 0 0 0 0 1 1 1 0 0 1 0 0 0 0 0 1 0 0 0 1
## 184 187 193 196 202 205 211 214 220 223 229 232 238 241 247 250 256 259 265 268
## 0 1 1 1 0 0 0 1 0 0 1 1 1 0 1 0 0 1 0 0
## 274 277 283 286 292 295 301 304 310 313 319 322 328 331 337 340 346 349 355 358
## 0 0 0 0 0 0 1 1 0 0 0 0 1 0 0 1 1 0 0 1
## 364 367 373 376 382 385 391 394 400 403 409 412 418 421 427 430 436 439 445 448
## 1 0 0 1 0 0 0 0 1 1 1 0 1 0 0 0 1 0 0 0
## 454 457 463 466 472 475 481 484 490 493 499 502 508 511 517 520 526 529 535 538
## 0 0 0 0 0 0 1 0 1 0 1 0 0 0 1 0 0 0 0 0
## 544 547 553 556 562 565 571 574 580 583 589 592 598 601 607 610 616 619 625 628
## 0 1 0 0 1 0 0 0 1 0 1 0 0 0 1 0 0 0 0 0
## 634 637 643 646 652 655 661 664 670 673 679 682 688 691 697 700 706 709 715 718
## 0 0 1 1 0 0 1 1 1 0 0 1 0 0 1 1 0 1 0 0
## 724 727 733 736 742 745 751 754 760 763
## 0 0 1 0 0 1 0 1 1 0
#it is required to factor the outcomes in order to create a confusion matrix
test_class<-as.factor(test_class)
test_df$Outcome<-as.factor(test_df$Outcome)
confusionMatrix(test_df$Outcome,test_class)
## Confusion Matrix and Statistics
##
## Reference
## Prediction 0 1
## 0 93 12
## 1 24 41
##
## Accuracy : 0.7882
## 95% CI : (0.7191, 0.8471)
## No Information Rate : 0.6882
## P-Value [Acc > NIR] : 0.002434
##
## Kappa : 0.5353
##
## Mcnemar's Test P-Value : 0.066753
##
## Sensitivity : 0.7949
## Specificity : 0.7736
## Pos Pred Value : 0.8857
## Neg Pred Value : 0.6308
## Prevalence : 0.6882
## Detection Rate : 0.5471
## Detection Prevalence : 0.6176
## Balanced Accuracy : 0.7842
##
## 'Positive' Class : 0
##