We are presented with blood data results from https://data.mendeley.com/datasets/7bmfgkkm3z/3 where we have variables such as lymphocytes, red blood cell count, platelets, etc. There is also a column with whether the patient had COVID or not. Using our blood test variables, we will be predicting whether someone has COVID or not.

## Loading required package: ggplot2
## Loading required package: lattice
## Loading required package: grid
## Loading required package: mvtnorm
## Loading required package: modeltools
## Loading required package: stats4
## Loading required package: strucchange
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## Loading required package: sandwich
## randomForest 4.7-1.1
## Type rfNews() to see new features/changes/bug fixes.
## 
## Attaching package: 'randomForest'
## The following object is masked from 'package:ggplot2':
## 
##     margin

Splitting into Training and Testing

df <- read.csv("C:/Users/patel/Documents/CBCovid19EC.csv")
df <- df[-c(1,4,5)]
df$pcr <- ifelse(df$pcr == "negative", 0, 1)
df$sex <- ifelse(df$sex == "male ", 0, 1)
df$pcr <- factor(df$pcr)
set.seed(2)   
split <- sample.split(df$pcr, SplitRatio = 0.80)
train_data <- subset(df, split == TRUE)
test_data <- subset(df, split == FALSE)

Logarithmic Model

log_model <- glm(pcr~., data = train_data, family = "binomial")
summary(log_model)
## 
## Call:
## glm(formula = pcr ~ ., family = "binomial", data = train_data)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.3499  -0.6236  -0.2986   0.5458   2.6870  
## 
## Coefficients:
##                 Estimate Std. Error z value Pr(>|z|)   
## (Intercept)    1.079e+01  9.555e+00   1.130  0.25862   
## sex            4.261e-01  5.398e-01   0.789  0.42985   
## age           -1.738e-03  1.307e-02  -0.133  0.89420   
## leukocytes    -3.590e-04  2.042e-04  -1.758  0.07877 . 
## neutrophilsP  -4.433e-02  6.800e-02  -0.652  0.51447   
## lymphocytesP  -9.362e-02  7.444e-02  -1.258  0.20853   
## monocytesP     7.583e-02  1.246e-01   0.609  0.54266   
## eosinophilsP  -7.960e-01  2.478e-01  -3.213  0.00132 **
## basophilsP    -2.290e+00  1.389e+00  -1.649  0.09924 . 
## neutrophils    5.309e-06  1.198e-04   0.044  0.96465   
## lymphocytes   -6.836e-04  5.130e-04  -1.333  0.18269   
## monocytes     -3.051e-04  1.995e-03  -0.153  0.87846   
## eosinophils    6.951e-04  3.320e-03   0.209  0.83415   
## basophils      1.692e-02  2.421e-02   0.699  0.48452   
## redbloodcells  9.829e-04  9.435e-04   1.042  0.29750   
## mcv           -5.938e-02  4.317e-02  -1.376  0.16895   
## mch            5.297e-02  1.589e-01   0.333  0.73882   
## mchc          -8.736e-02  1.091e-01  -0.801  0.42315   
## rdwP           1.501e-01  1.383e-01   1.085  0.27773   
## hemoglobin    -1.129e-01  3.098e-01  -0.364  0.71550   
## hematocritP    1.337e-02  4.005e-02   0.334  0.73853   
## platelets     -7.279e-03  3.261e-03  -2.232  0.02562 * 
## mpv            1.623e-01  2.004e-01   0.810  0.41815   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 384.92  on 301  degrees of freedom
## Residual deviance: 247.69  on 279  degrees of freedom
## AIC: 293.69
## 
## Number of Fisher Scoring iterations: 6

As we can see, more than half the variables are not important, so we will reduce to get the most important variables and store in xvar. We will also need less variables so that we can fit things on our web app we make using this data.

After much trial and error, came to a conclusion on which variables are important using lower Pr(|z|) values, decision tree map, coefficients of svm model and model accuracies.

Code you will see will all be done using xvar, but initially ran code with all variables to find the most important ones.

xvar <- pcr ~ leukocytes+eosinophilsP+basophilsP+lymphocytes+basophils+mcv+mchc+platelets
log_model <- glm(xvar, data = train_data, family = "binomial")
summary(log_model)
## 
## Call:
## glm(formula = xvar, family = "binomial", data = train_data)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.2300  -0.6912  -0.3584   0.6367   2.9860  
## 
## Coefficients:
##                Estimate Std. Error z value Pr(>|z|)    
## (Intercept)   1.548e+01  3.709e+00   4.173 3.01e-05 ***
## leukocytes   -9.557e-05  1.076e-04  -0.888 0.374628    
## eosinophilsP -6.467e-01  1.641e-01  -3.940 8.13e-05 ***
## basophilsP   -2.207e+00  1.254e+00  -1.760 0.078490 .  
## lymphocytes  -1.306e-03  2.671e-04  -4.890 1.01e-06 ***
## basophils     2.534e-02  2.057e-02   1.232 0.217968    
## mcv          -6.973e-02  2.396e-02  -2.910 0.003614 ** 
## mchc         -8.175e-02  4.645e-02  -1.760 0.078433 .  
## platelets    -9.183e-03  2.534e-03  -3.624 0.000291 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 384.92  on 301  degrees of freedom
## Residual deviance: 263.32  on 293  degrees of freedom
## AIC: 281.32
## 
## Number of Fisher Scoring iterations: 5
predictions.log <- predict(log_model, newdata = test_data[-23])
predictions.log <- ifelse(predictions.log > 0.5, 1, 0)
table(predictions.log, test_data[[23]])
##                
## predictions.log  0  1
##               0 45  9
##               1  5 16
paste0('Accuracy: ', sum(diag(table(predictions.log, test_data[[23]])) / sum(table(predictions.log, test_data[[23]]))))
## [1] "Accuracy: 0.813333333333333"

Decision Tree Model

dtree <- ctree(xvar, data = train_data)
table(predict(dtree, newdata = test_data), test_data$pcr)
##    
##      0  1
##   0 42  8
##   1  8 17
paste0('Accuracy: ', sum(diag(table(predict(dtree, newdata = test_data), test_data$pcr)) / sum(table(predict(dtree, newdata = test_data), test_data$pcr))))
## [1] "Accuracy: 0.786666666666667"
plot(dtree)

From the decision tree, we can see that lymphocytes, eosinophilsP (percentage of eosinophils) and platelets are the main deciding variables.

Random Forest Model

rf.model <- randomForest(xvar, data = df, ntree = 500)
set.seed(2) 
split <- sample.split(df$pcr, SplitRatio = 0.80)
train_data <- subset(df, split == TRUE)
test_data <- subset(df, split == FALSE)
rf.model <- randomForest(x = train_data[-23], y = train_data$pcr, xtest = test_data[-23],
                         ytest = test_data$pcr, ntree = 500, mtry = 4)
rf.model
## 
## Call:
##  randomForest(x = train_data[-23], y = train_data$pcr, xtest = test_data[-23],      ytest = test_data$pcr, ntree = 500, mtry = 4) 
##                Type of random forest: classification
##                      Number of trees: 500
## No. of variables tried at each split: 4
## 
##         OOB estimate of  error rate: 20.86%
## Confusion matrix:
##     0  1 class.error
## 0 179 22   0.1094527
## 1  41 60   0.4059406
##                 Test set error rate: 12%
## Confusion matrix:
##    0  1 class.error
## 0 46  4        0.08
## 1  5 20        0.20
tunedrf <- tuneRF(df[-23], as.factor(df[[23]]), mtryStart = 4, stepFactor = 3, improve = 0.03)
## mtry = 4  OOB error = 21.49% 
## Searching left ...
## mtry = 2     OOB error = 21.75% 
## -0.01234568 0.03 
## Searching right ...
## mtry = 12    OOB error = 22.28% 
## -0.03703704 0.03

tunedrf
##        mtry  OOBError
## 2.OOB     2 0.2175066
## 4.OOB     4 0.2148541
## 12.OOB   12 0.2228117

After trial and error and tuning our Random Forest model, mtry = 4 and ntrees = 500 resulted in the most optimal model.

Support Vector Machine Classification

set.seed(2)
split <- sample.split(df$pcr, SplitRatio = 0.80)
train_data <- subset(df, split == TRUE)
test_data <- subset(df, split == FALSE)
svm.model <- svm(xvar, data = train_data, kernel = 'linear', cost = 0.01)
sv.pred <- predict(svm.model, test_data)
table(sv.pred, test_data$pcr)
##        
## sv.pred  0  1
##       0 45  8
##       1  5 17
paste0('Accuracy: ', sum(diag(table(sv.pred, test_data$pcr)) / sum(table(sv.pred, test_data$pcr))))
## [1] "Accuracy: 0.826666666666667"
coefficients <- coef(svm.model)
coefficients
##  (Intercept)   leukocytes eosinophilsP   basophilsP  lymphocytes    basophils 
##   0.74437113   0.08162228   0.26544141   0.18505203   0.44687309   0.02495099 
##          mcv         mchc    platelets 
##   0.11312522   0.01644444   0.31537834

We can see here that lymphocytes, platelets and eosinophilsP are the most important variables.

Training and Tuning SVM Models with 20 Fold Cross Validation (20 gave best results)

ctrl <- trainControl(method = "cv", number = 20)
svm.lin <- train(xvar, data = train_data, method = "svmLinear", trControl = ctrl)
svm.lin
## Support Vector Machines with Linear Kernel 
## 
## 302 samples
##   8 predictor
##   2 classes: '0', '1' 
## 
## No pre-processing
## Resampling: Cross-Validated (20 fold) 
## Summary of sample sizes: 287, 287, 286, 287, 287, 287, ... 
## Resampling results:
## 
##   Accuracy  Kappa    
##   0.81125   0.5481518
## 
## Tuning parameter 'C' was held constant at a value of 1
lin.values = list(20)
for (i in 1:20){
  j <- train(xvar, data = train_data, method = "svmLinear", trControl = ctrl)
  lin.values[i] <- max(j$results$Accuracy) 
}
paste0('Average Highest Accuracy for Linear Model: ', mean(unlist(lin.values)))
## [1] "Average Highest Accuracy for Linear Model: 0.81177512254902"

Radial Method

svm.rad <- train(xvar, data = train_data, method = "svmRadial", trControl = ctrl)
svm.rad
## Support Vector Machines with Radial Basis Function Kernel 
## 
## 302 samples
##   8 predictor
##   2 classes: '0', '1' 
## 
## No pre-processing
## Resampling: Cross-Validated (20 fold) 
## Summary of sample sizes: 287, 287, 287, 287, 287, 286, ... 
## Resampling results across tuning parameters:
## 
##   C     Accuracy   Kappa    
##   0.25  0.8047917  0.5183111
##   0.50  0.8145833  0.5507797
##   1.00  0.8179167  0.5610429
## 
## Tuning parameter 'sigma' was held constant at a value of 0.1766809
## Accuracy was used to select the optimal model using the largest value.
## The final values used for the model were sigma = 0.1766809 and C = 1.
rad.values = list(20)
for (i in 1:20){
  j <- train(xvar, data = train_data, method = "svmRadial", trControl = ctrl)
  rad.values[i] <- max(j$results$Accuracy) 
}
paste0('Average Highest Accuracy for Radial Model: ', mean(unlist(rad.values)))
## [1] "Average Highest Accuracy for Radial Model: 0.816125"

Polynomial Method

svm.pol <- train(xvar, data = train_data, method = "svmPoly", trControl = ctrl)
svm.pol
## Support Vector Machines with Polynomial Kernel 
## 
## 302 samples
##   8 predictor
##   2 classes: '0', '1' 
## 
## No pre-processing
## Resampling: Cross-Validated (20 fold) 
## Summary of sample sizes: 287, 286, 287, 287, 287, 287, ... 
## Resampling results across tuning parameters:
## 
##   degree  scale  C     Accuracy   Kappa    
##   1       0.001  0.25  0.6656250  0.0000000
##   1       0.001  0.50  0.6656250  0.0000000
##   1       0.001  1.00  0.6656250  0.0000000
##   1       0.010  0.25  0.6656250  0.0000000
##   1       0.010  0.50  0.6687500  0.0100000
##   1       0.010  1.00  0.7787500  0.4313655
##   1       0.100  0.25  0.8083333  0.5286971
##   1       0.100  0.50  0.8085417  0.5371718
##   1       0.100  1.00  0.8185417  0.5704239
##   2       0.001  0.25  0.6656250  0.0000000
##   2       0.001  0.50  0.6656250  0.0000000
##   2       0.001  1.00  0.6656250  0.0000000
##   2       0.010  0.25  0.6787500  0.0475000
##   2       0.010  0.50  0.7854167  0.4480322
##   2       0.010  1.00  0.8050000  0.5185217
##   2       0.100  0.25  0.8218750  0.5690547
##   2       0.100  0.50  0.8216667  0.5691179
##   2       0.100  1.00  0.8145833  0.5575845
##   3       0.001  0.25  0.6656250  0.0000000
##   3       0.001  0.50  0.6656250  0.0000000
##   3       0.001  1.00  0.6656250  0.0000000
##   3       0.010  0.25  0.7618750  0.3522231
##   3       0.010  0.50  0.7983333  0.4973142
##   3       0.010  1.00  0.8016667  0.5129076
##   3       0.100  0.25  0.8214583  0.5679895
##   3       0.100  0.50  0.8181250  0.5628686
##   3       0.100  1.00  0.8016667  0.5342987
## 
## Accuracy was used to select the optimal model using the largest value.
## The final values used for the model were degree = 2, scale = 0.1 and C = 0.25.
pol.values = list(20)
for (i in 1:20){
  j <- train(xvar, data = train_data, method = "svmPoly", trControl = ctrl)
  pol.values[i] <- max(j$results$Accuracy) 
}
paste0('Average Highest Accuracy for Poly Model: ', mean(unlist(pol.values)))
## [1] "Average Highest Accuracy for Poly Model: 0.823947916666667"

Radial Sigma Method

svm.sig <- train(xvar, data = train_data, method = "svmRadialSigma", trControl = ctrl)
svm.sig
## Support Vector Machines with Radial Basis Function Kernel 
## 
## 302 samples
##   8 predictor
##   2 classes: '0', '1' 
## 
## No pre-processing
## Resampling: Cross-Validated (20 fold) 
## Summary of sample sizes: 287, 287, 286, 287, 287, 287, ... 
## Resampling results across tuning parameters:
## 
##   sigma       C     Accuracy   Kappa    
##   0.03454424  0.25  0.8147917  0.5338015
##   0.03454424  0.50  0.8214583  0.5541587
##   0.03454424  1.00  0.8247917  0.5737158
##   0.14354836  0.25  0.8150000  0.5429192
##   0.14354836  0.50  0.8085417  0.5321259
##   0.14354836  1.00  0.8085417  0.5343816
##   0.25255249  0.25  0.7950000  0.4827380
##   0.25255249  0.50  0.8085417  0.5330179
##   0.25255249  1.00  0.7985417  0.5144726
## 
## Accuracy was used to select the optimal model using the largest value.
## The final values used for the model were sigma = 0.03454424 and C = 1.
rads.values = list(20)
for (i in 1:20){
  j <- train(xvar, data = train_data, method = "svmRadialSigma", trControl = ctrl)
  rads.values[i] <- max(j$results$Accuracy) 
}
paste0('Average Highest Accuracy for Radial Sigma Model: ', mean(unlist(rads.values)))
## [1] "Average Highest Accuracy for Radial Sigma Model: 0.823088848039216"

Radial Cost Method

svm.radc <- train(xvar, data = train_data, method = "svmRadialCost", trControl = ctrl)
svm.radc
## Support Vector Machines with Radial Basis Function Kernel 
## 
## 302 samples
##   8 predictor
##   2 classes: '0', '1' 
## 
## No pre-processing
## Resampling: Cross-Validated (20 fold) 
## Summary of sample sizes: 287, 287, 287, 287, 287, 287, ... 
## Resampling results across tuning parameters:
## 
##   C     Accuracy   Kappa    
##   0.25  0.8145098  0.5459776
##   0.50  0.8111765  0.5445239
##   1.00  0.8178431  0.5687845
## 
## Accuracy was used to select the optimal model using the largest value.
## The final value used for the model was C = 1.
radc.values = list(20)
for (i in 1:20){
  j <- train(xvar, data = train_data, method = "svmRadialCost", trControl = ctrl)
  radc.values[i] <- max(j$results$Accuracy) 
}
paste0('Average Highest Accuracy for Radial Cost Model: ', mean(unlist(radc.values)))
## [1] "Average Highest Accuracy for Radial Cost Model: 0.816833946078431"

Using Best Model on Testing Data

pred <- predict(svm.sig, newdata = test_data[-23])
table(pred, test_data$pcr)
##     
## pred  0  1
##    0 44  8
##    1  6 17
sum(diag(table(pred, test_data$pcr)) / sum(table(pred, test_data$pcr)))
## [1] 0.8133333

From our results we can see that best model is with the Polynomial method. The best training accuracy was about 82% and the testing accuracy was about 81%. A slight drop in testing accuracy is expected, but this shows that our model wasn’t overfit or there wasn’t any data leakage. We will be using this model in our web application created in shiny.