# load required packages
library(adabag)
## Loading required package: rpart
## Loading required package: caret
## Loading required package: ggplot2
## Loading required package: lattice
## Loading required package: foreach
## Loading required package: doParallel
## Loading required package: iterators
## Loading required package: parallel
library(nnet)
library(car)
## Loading required package: carData
library(ResourceSelection)
## ResourceSelection 0.3-6   2023-06-27
library(bestglm)
## Loading required package: leaps
library(caTools)
library(LiblineaR)
library(e1071)
## Warning: package 'e1071' was built under R version 4.2.3
library(pROC)
## Type 'citation("pROC")' for a citation.
## 
## Attaching package: 'pROC'
## The following objects are masked from 'package:stats':
## 
##     cov, smooth, var
library(rpart)
library(rpart.plot)
library(ipred)
## 
## Attaching package: 'ipred'
## The following object is masked from 'package:adabag':
## 
##     bagging
library(randomForest)
## 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

Helper Functions

# encodes all categorical columns into integer types
# usage: encode_to_numeric(df), where df is a dataframe
# returns a dataframe with all categorical variables converted to integer, if any
encode_to_numeric <- function(Z) {
  col_types = sapply(Z, class)
  categorical_var_indices <- which(col_types == 'character')
  
  for (idx in categorical_var_indices){
    if (colnames(Z)[idx] == 'ChestPainType') {
      Z[which(Z[, idx] == 'ASY'), idx] = 0
      Z[which(Z[, idx] == 'NAP'), idx] = 1
      Z[which(Z[, idx] == 'ATA'), idx] = 2
      Z[which(Z[, idx] == 'TA'), idx] = 3
    }
    Z[, idx] <- unclass(as.factor(Z[, idx])) - 1
    Z[, idx] <- as.integer(Z[, idx])
  }

  return(Z)  
}


## Selection Methods
best_subset_aic <- function(X, y) {
  # Best Subset Selection
  model <- bestglm (cbind(X, y), IC = 'AIC', family = binomial)$BestModel
  return(model)
}

best_subset_bic <- function(X, y) {
  model <- bestglm(cbind(X, y), IC = 'BIC', family = binomial)$BestModel
  return(model)
}

forward_aic <- function(X, y) {
  biggest <- formula(glm(y~., data = cbind(X,  y), family = binomial))
  
  fit0 = glm(y~1, data = cbind(X, y), family = 'binomial')
  fitfwd = step(fit0, direction = 'forward', scope = biggest)
  
  return(fitfwd)
}

backward_aic <- function(X, y) {
  fit_full <- glm(y~., data = cbind(X, y), family = binomial)
  fitB <- step(fit_full, direction = 'backward')
  
  return(fitB)
}

stepwise_aic <- function(X, y) {
  biggest <- formula(glm(y~., data = cbind(X, y), family = binomial))
  
  fit0 = glm(y~1, data = cbind(X, y), family = 'binomial')
  fitstep = step(fit0, direction = 'both', scope = biggest) 
  return(fitstep)
}
############################################################################################################

# Takes a design matrix X and a response label vector y
# returns:
# train_X: Training Data (X) (df)
# train_y: Training labels (y) (df)
# test_X: Test Data (X) (df)
# test_y: Test Labels (y) (df)
split_data <- function(X, y, split_ratio = 3/4) {
  
  # creates a mask of boolean values, where observations with true values representing train data and false values representing test data
  mask <- sample.split(c(y[, 1]), SplitRatio = split_ratio)
  
  train_X <- subset(X, mask == T)
  train_y <- subset(y, mask == T)
  
  test_X <- subset(X, mask == F)
  test_y <- subset(y, mask == F)
  
  
  test_X <- scale(test_X, center = colMeans(train_X), scale = apply(train_X, 2, sd))
  train_X <- scale(train_X)
  
  return(list('train_X'=train_X, 'train_y'=train_y, 'test_X'=test_X, 'test_y'=test_y))
}

lr_fit <- function(lr_model) {
  residual_dev <- summary(lr_model)$deviance
  null_dev <- summary(lr_model)$null.deviance
  # check overall fit 
  r.squared <- 1 - residual_dev / null_dev
  print(r.squared)
  print("R squared:")
  print(r.squared)
  
  # Test overall fit
  g_stat <- null_dev - residual_dev
  p.value <- pchisq(g_stat, df = ncol(lr_model$data), lower.tail = FALSE)
  print("p-value for overall fit:")
  print(p.value)
  
  # HL Test
  hoslem.test(lr_model$y, fitted(lr_model))
}

get_probs <- function(model, test_X) {
  # get the probs
  if (class(model)[1] == 'glm'){
    probs <- predict(model, as.data.frame(test_X), type = 'response')
  }
  else if (class(model)[1] == 'LiblineaR') {
    probs <- predict(model, as.matrix(test_X), proba = T)$probabilities[, 1]
  }
  else if (class(model)[1] %in% c('rpart', 'classbagg', 'randomForest.formula')) {
    probs <- predict(model, data.frame(test_X), type = 'prob')[, 2]
  }
  else if (class(model)[1] == 'boosting') {
    probs <- predict(model, data.frame(test_X))$prob[, 2]
  }
  else {
    stop('model type not supported')
  }
  
  return(probs)
}

get_preds <- function(model, test_X, threshold = 0.5) {
  # svm models don't have probabilities
  if (class(model)[1] == 'LiblineaR' && model$Type == 2) {
    return(predict(model, as.matrix(test_X), proba = F)$predictions)
  }
  if (class(model)[1] == 'svm.formula') {
    return(predict(model, as.matrix(test_X), proba = F))
  }
  
  # get probabilities for other models
  probs <- get_probs(model, test_X)
  
  preds <- probs > threshold
  return(preds)
}

# Evaluation
# evaluate model by creating confusion matrix on testing data
# model: model object (glm or LibllineaR) type
# test_X: Test Data (X)
# test_y: Test Data (y)
# threshold: threshold value for prediction (default = 0.5)
cfmat_eval <- function(test_X, test_y, predict_y) {
  cfmat <- table(actual = test_y[, 1], predicted = predict_y)
  
  tp <- cfmat[2, 2]
  tn <- cfmat[1, 1]
  fn <- cfmat[2, 1]
  fp <- cfmat[1, 2]
  
  accuracy <- (tp + tn)/sum(cfmat)
  precision <- tp/(tp+fp)
  recall <- tp/(tp + fn)
  f1_measure <- 1/mean(c(1/precision, 1/recall))
  
  sensitivity <- tp/(tp + fn)
  specificity <- tn/(fp + tn)
  
  return(list('cfmat' = cfmat, 'accuracy' = accuracy, 'precision' = precision, 'recall' = recall, 'f1_measure' = f1_measure, 'sensitivity' = sensitivity, 'specificity' = specificity))
}

roc_eval <- function(model, test_X, test_y, print_plot = TRUE) {
  roc_obj <- roc(response = as.numeric(test_y[, 1]), predictor = get_probs(model, test_X))
  best_threshold <- coords(roc_obj, 'best', ret = c('threshold'), best.method = 'closest.topleft')
  print('best threshold')
  print(best_threshold)
  if (print_plot){
    plot(roc_obj)
  }
  auc_value <- auc(roc_obj)
  print('auc:')
  print(auc_value)
  
  # print(coords(roc_obj, 'best', ret = c('threshold', 'tp'), transpose = FALSE))
  
  return(list('auc_value' = auc_value, 'best_threshold' = best_threshold[1, 1]))
}

# create ada boost
bestK_adaB <- function(train_X, train_y, test_X, test_y, kmin, kmax) {
  accuracy_rate <- c()
  for (i in kmin: kmax) {
    set.seed(23)
    data_adaBoost <- cbind(train_y, train_X)
    data_adaBoost$y <- factor(data_adaBoost$y)
    
    adaB <- boosting(y~., data = data_adaBoost, mfinal = i)
    
    cfmat <- table(actual = test_y[, 1], predicted = predict(adaB, data.frame(test_X))$class)
    tp <- cfmat[2, 2]
    tn <- cfmat[1, 1]
    fn <- cfmat[2, 1]
    fp <- cfmat[1, 2]
    
    accuracy <- (tp + tn)/sum(tp + tn + fn + fp)
    accuracy_rate <- c(accuracy_rate, accuracy)
    
    cat("Processing the case with ", i , "trees. \n")
  }
  
  acc = data.frame(k=kmin:kmax, accuracy_rate = accuracy_rate)
  return(acc)
}

Load data and preprocess

Z <- read.csv('data/classification/heart.csv')
Z <- na.omit(Z)
Z <- encode_to_numeric(Z)

# remove some variables
# variable_names <- c('X', 'id', 'Gender', 'Online.boarding', 'Departure.Arrival.time.convenient', 'On.board.service', 'Gate.location', 'Customer.Type', 'Age', 'Type.of.Travel')
# 
# variable_names <- c('X', 'id')
# 
# Z <- Z[, !(colnames(Z) %in% variable_names)]

y_name <- 'HeartDisease'
y_idx <- which(colnames(Z) == y_name)
colnames(Z)[which(colnames(Z) == y_name)] <- 'y'

# drop = F for preserving data frame type
y <- Z[, y_idx, drop = F]
X <- Z[, -y_idx]

# fix seed value for reproducibility 
set.seed(300)
# split data into training and test set 
dat <- split_data(X, y)
train_X <- dat$train_X
train_y <- dat$train_y
test_X <- dat$test_X
test_y <- dat$test_y

Logistic Regresssion

log_model <- glm(y~., family = binomial, data = cbind(train_X, train_y))
summary(log_model)
## 
## Call:
## glm(formula = y ~ ., family = binomial, data = cbind(train_X, 
##     train_y))
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.8809  -0.4798   0.1731   0.4853   2.4655  
## 
## Coefficients:
##                Estimate Std. Error z value Pr(>|z|)    
## (Intercept)     0.44092    0.11850   3.721 0.000199 ***
## Age             0.18942    0.13038   1.453 0.146275    
## Sex             0.57222    0.12057   4.746 2.07e-06 ***
## ChestPainType  -0.46900    0.11918  -3.935 8.32e-05 ***
## RestingBP       0.11440    0.11899   0.961 0.336338    
## Cholesterol    -0.42822    0.13226  -3.238 0.001205 ** 
## FastingBS       0.48548    0.12797   3.794 0.000148 ***
## RestingECG     -0.07621    0.12362  -0.616 0.537583    
## MaxHR          -0.23033    0.13831  -1.665 0.095841 .  
## ExerciseAngina  0.50069    0.13138   3.811 0.000138 ***
## Oldpeak         0.42642    0.13775   3.096 0.001964 ** 
## ST_Slope       -1.08357    0.14555  -7.445 9.70e-14 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 947.41  on 688  degrees of freedom
## Residual deviance: 491.96  on 677  degrees of freedom
## AIC: 515.96
## 
## Number of Fisher Scoring iterations: 5

Perform Model Selection

selected_log <- best_subset_aic(train_X, train_y)
## Morgan-Tatar search since family is non-gaussian.
best_subset_bic(train_X, train_y)
## Morgan-Tatar search since family is non-gaussian.
## 
## Call:  glm(formula = y ~ ., family = family, data = Xi, weights = weights)
## 
## Coefficients:
##    (Intercept)             Sex   ChestPainType     Cholesterol       FastingBS  
##         0.4414          0.5622         -0.4942         -0.4614          0.5151  
## ExerciseAngina         Oldpeak        ST_Slope  
##         0.5720          0.4391         -1.1525  
## 
## Degrees of Freedom: 688 Total (i.e. Null);  681 Residual
## Null Deviance:       947.4 
## Residual Deviance: 501.3     AIC: 517.3
forward_aic(train_X, train_y)
## Start:  AIC=949.41
## y ~ 1
## 
##                  Df Deviance    AIC
## + ST_Slope        1   683.15 687.15
## + ExerciseAngina  1   780.56 784.56
## + Oldpeak         1   809.47 813.47
## + ChestPainType   1   812.26 816.26
## + MaxHR           1   828.83 832.83
## + Sex             1   876.40 880.40
## + Age             1   880.14 884.14
## + FastingBS       1   887.47 891.47
## + Cholesterol     1   902.56 906.56
## + RestingBP       1   938.95 942.95
## + RestingECG      1   943.85 947.85
## <none>                947.41 949.41
## 
## Step:  AIC=687.15
## y ~ ST_Slope
## 
##                  Df Deviance    AIC
## + ExerciseAngina  1   625.91 631.91
## + Sex             1   628.52 634.52
## + ChestPainType   1   629.70 635.70
## + Cholesterol     1   640.50 646.50
## + FastingBS       1   643.25 649.25
## + MaxHR           1   644.40 650.40
## + Oldpeak         1   656.61 662.61
## + Age             1   660.40 666.40
## + RestingECG      1   678.31 684.31
## + RestingBP       1   679.42 685.42
## <none>                683.15 687.15
## 
## Step:  AIC=631.91
## y ~ ST_Slope + ExerciseAngina
## 
##                 Df Deviance    AIC
## + Cholesterol    1   579.91 587.91
## + Sex            1   580.35 588.35
## + FastingBS      1   584.42 592.42
## + ChestPainType  1   597.44 605.44
## + MaxHR          1   604.85 612.85
## + Age            1   611.31 619.31
## + Oldpeak        1   614.93 622.93
## + RestingECG     1   622.78 630.78
## <none>               625.91 631.91
## + RestingBP      1   624.66 632.66
## 
## Step:  AIC=587.91
## y ~ ST_Slope + ExerciseAngina + Cholesterol
## 
##                 Df Deviance    AIC
## + Sex            1   551.69 561.69
## + FastingBS      1   556.92 566.92
## + ChestPainType  1   558.67 568.67
## + Oldpeak        1   566.18 576.18
## + MaxHR          1   570.04 580.04
## + Age            1   571.02 581.02
## + RestingBP      1   576.65 586.65
## <none>               579.91 587.91
## + RestingECG     1   579.88 589.88
## 
## Step:  AIC=561.69
## y ~ ST_Slope + ExerciseAngina + Cholesterol + Sex
## 
##                 Df Deviance    AIC
## + ChestPainType  1   531.18 543.18
## + FastingBS      1   531.95 543.95
## + Oldpeak        1   538.03 550.03
## + Age            1   540.48 552.48
## + MaxHR          1   543.73 555.73
## + RestingBP      1   548.16 560.16
## <none>               551.69 561.69
## + RestingECG     1   551.67 563.67
## 
## Step:  AIC=543.18
## y ~ ST_Slope + ExerciseAngina + Cholesterol + Sex + ChestPainType
## 
##              Df Deviance    AIC
## + FastingBS   1   512.29 526.29
## + Oldpeak     1   518.95 532.95
## + Age         1   520.68 534.68
## + RestingBP   1   526.77 540.77
## + MaxHR       1   527.27 541.27
## <none>            531.18 543.18
## + RestingECG  1   531.10 545.10
## 
## Step:  AIC=526.29
## y ~ ST_Slope + ExerciseAngina + Cholesterol + Sex + ChestPainType + 
##     FastingBS
## 
##              Df Deviance    AIC
## + Oldpeak     1   501.31 517.31
## + Age         1   504.77 520.77
## + MaxHR       1   508.45 524.45
## + RestingBP   1   509.47 525.47
## <none>            512.29 526.29
## + RestingECG  1   512.14 528.14
## 
## Step:  AIC=517.31
## y ~ ST_Slope + ExerciseAngina + Cholesterol + Sex + ChestPainType + 
##     FastingBS + Oldpeak
## 
##              Df Deviance    AIC
## + Age         1   495.83 513.83
## + MaxHR       1   496.10 514.10
## + RestingBP   1   499.20 517.20
## <none>            501.31 517.31
## + RestingECG  1   501.24 519.24
## 
## Step:  AIC=513.83
## y ~ ST_Slope + ExerciseAngina + Cholesterol + Sex + ChestPainType + 
##     FastingBS + Oldpeak + Age
## 
##              Df Deviance    AIC
## + MaxHR       1   493.14 513.14
## <none>            495.83 513.83
## + RestingBP   1   494.82 514.82
## + RestingECG  1   495.80 515.80
## 
## Step:  AIC=513.14
## y ~ ST_Slope + ExerciseAngina + Cholesterol + Sex + ChestPainType + 
##     FastingBS + Oldpeak + Age + MaxHR
## 
##              Df Deviance    AIC
## <none>            493.14 513.14
## + RestingBP   1   492.34 514.34
## + RestingECG  1   492.87 514.87
## 
## Call:  glm(formula = y ~ ST_Slope + ExerciseAngina + Cholesterol + Sex + 
##     ChestPainType + FastingBS + Oldpeak + Age + MaxHR, family = "binomial", 
##     data = cbind(X, y))
## 
## Coefficients:
##    (Intercept)        ST_Slope  ExerciseAngina     Cholesterol             Sex  
##         0.4400         -1.0844          0.5019         -0.3952          0.5652  
##  ChestPainType       FastingBS         Oldpeak             Age           MaxHR  
##        -0.4610          0.4919          0.4322          0.2186         -0.2217  
## 
## Degrees of Freedom: 688 Total (i.e. Null);  679 Residual
## Null Deviance:       947.4 
## Residual Deviance: 493.1     AIC: 513.1
backward_aic(train_X, train_y)
## Start:  AIC=515.96
## y ~ Age + Sex + ChestPainType + RestingBP + Cholesterol + FastingBS + 
##     RestingECG + MaxHR + ExerciseAngina + Oldpeak + ST_Slope
## 
##                  Df Deviance    AIC
## - RestingECG      1   492.34 514.34
## - RestingBP       1   492.87 514.87
## <none>                491.96 515.96
## - Age             1   494.08 516.08
## - MaxHR           1   494.73 516.73
## - Oldpeak         1   501.79 523.79
## - Cholesterol     1   502.98 524.98
## - ExerciseAngina  1   506.49 528.49
## - FastingBS       1   507.19 529.19
## - ChestPainType   1   507.76 529.76
## - Sex             1   516.14 538.14
## - ST_Slope        1   553.68 575.68
## 
## Step:  AIC=514.34
## y ~ Age + Sex + ChestPainType + RestingBP + Cholesterol + FastingBS + 
##     MaxHR + ExerciseAngina + Oldpeak + ST_Slope
## 
##                  Df Deviance    AIC
## - RestingBP       1   493.14 513.14
## <none>                492.34 514.34
## - Age             1   494.70 514.70
## - MaxHR           1   494.82 514.82
## - Oldpeak         1   502.18 522.18
## - Cholesterol     1   502.98 522.98
## - ExerciseAngina  1   506.58 526.58
## - FastingBS       1   507.50 527.50
## - ChestPainType   1   508.09 528.09
## - Sex             1   516.23 536.23
## - ST_Slope        1   555.39 575.39
## 
## Step:  AIC=513.14
## y ~ Age + Sex + ChestPainType + Cholesterol + FastingBS + MaxHR + 
##     ExerciseAngina + Oldpeak + ST_Slope
## 
##                  Df Deviance    AIC
## <none>                493.14 513.14
## - MaxHR           1   495.83 513.83
## - Age             1   496.10 514.10
## - Cholesterol     1   503.14 521.14
## - Oldpeak         1   503.31 521.31
## - ExerciseAngina  1   508.00 526.00
## - ChestPainType   1   508.48 526.48
## - FastingBS       1   508.86 526.86
## - Sex             1   516.94 534.94
## - ST_Slope        1   555.62 573.62
## 
## Call:  glm(formula = y ~ Age + Sex + ChestPainType + Cholesterol + FastingBS + 
##     MaxHR + ExerciseAngina + Oldpeak + ST_Slope, family = binomial, 
##     data = cbind(X, y))
## 
## Coefficients:
##    (Intercept)             Age             Sex   ChestPainType     Cholesterol  
##         0.4400          0.2186          0.5652         -0.4610         -0.3952  
##      FastingBS           MaxHR  ExerciseAngina         Oldpeak        ST_Slope  
##         0.4919         -0.2217          0.5019          0.4322         -1.0844  
## 
## Degrees of Freedom: 688 Total (i.e. Null);  679 Residual
## Null Deviance:       947.4 
## Residual Deviance: 493.1     AIC: 513.1
stepwise_aic(train_X, train_y)
## Start:  AIC=949.41
## y ~ 1
## 
##                  Df Deviance    AIC
## + ST_Slope        1   683.15 687.15
## + ExerciseAngina  1   780.56 784.56
## + Oldpeak         1   809.47 813.47
## + ChestPainType   1   812.26 816.26
## + MaxHR           1   828.83 832.83
## + Sex             1   876.40 880.40
## + Age             1   880.14 884.14
## + FastingBS       1   887.47 891.47
## + Cholesterol     1   902.56 906.56
## + RestingBP       1   938.95 942.95
## + RestingECG      1   943.85 947.85
## <none>                947.41 949.41
## 
## Step:  AIC=687.15
## y ~ ST_Slope
## 
##                  Df Deviance    AIC
## + ExerciseAngina  1   625.91 631.91
## + Sex             1   628.52 634.52
## + ChestPainType   1   629.70 635.70
## + Cholesterol     1   640.50 646.50
## + FastingBS       1   643.25 649.25
## + MaxHR           1   644.40 650.40
## + Oldpeak         1   656.61 662.61
## + Age             1   660.40 666.40
## + RestingECG      1   678.31 684.31
## + RestingBP       1   679.42 685.42
## <none>                683.15 687.15
## - ST_Slope        1   947.41 949.41
## 
## Step:  AIC=631.91
## y ~ ST_Slope + ExerciseAngina
## 
##                  Df Deviance    AIC
## + Cholesterol     1   579.91 587.91
## + Sex             1   580.35 588.35
## + FastingBS       1   584.42 592.42
## + ChestPainType   1   597.44 605.44
## + MaxHR           1   604.85 612.85
## + Age             1   611.31 619.31
## + Oldpeak         1   614.93 622.93
## + RestingECG      1   622.78 630.78
## <none>                625.91 631.91
## + RestingBP       1   624.66 632.66
## - ExerciseAngina  1   683.15 687.15
## - ST_Slope        1   780.56 784.56
## 
## Step:  AIC=587.91
## y ~ ST_Slope + ExerciseAngina + Cholesterol
## 
##                  Df Deviance    AIC
## + Sex             1   551.69 561.69
## + FastingBS       1   556.92 566.92
## + ChestPainType   1   558.67 568.67
## + Oldpeak         1   566.18 576.18
## + MaxHR           1   570.04 580.04
## + Age             1   571.02 581.02
## + RestingBP       1   576.65 586.65
## <none>                579.91 587.91
## + RestingECG      1   579.88 589.88
## - Cholesterol     1   625.91 631.91
## - ExerciseAngina  1   640.50 646.50
## - ST_Slope        1   725.63 731.63
## 
## Step:  AIC=561.69
## y ~ ST_Slope + ExerciseAngina + Cholesterol + Sex
## 
##                  Df Deviance    AIC
## + ChestPainType   1   531.18 543.18
## + FastingBS       1   531.95 543.95
## + Oldpeak         1   538.03 550.03
## + Age             1   540.48 552.48
## + MaxHR           1   543.73 555.73
## + RestingBP       1   548.16 560.16
## <none>                551.69 561.69
## + RestingECG      1   551.67 563.67
## - Sex             1   579.91 587.91
## - Cholesterol     1   580.35 588.35
## - ExerciseAngina  1   603.28 611.28
## - ST_Slope        1   694.58 702.58
## 
## Step:  AIC=543.18
## y ~ ST_Slope + ExerciseAngina + Cholesterol + Sex + ChestPainType
## 
##                  Df Deviance    AIC
## + FastingBS       1   512.29 526.29
## + Oldpeak         1   518.95 532.95
## + Age             1   520.68 534.68
## + RestingBP       1   526.77 540.77
## + MaxHR           1   527.27 541.27
## <none>                531.18 543.18
## + RestingECG      1   531.10 545.10
## - ChestPainType   1   551.69 561.69
## - Cholesterol     1   554.50 564.50
## - Sex             1   558.67 568.67
## - ExerciseAngina  1   559.95 569.95
## - ST_Slope        1   653.50 663.50
## 
## Step:  AIC=526.29
## y ~ ST_Slope + ExerciseAngina + Cholesterol + Sex + ChestPainType + 
##     FastingBS
## 
##                  Df Deviance    AIC
## + Oldpeak         1   501.31 517.31
## + Age             1   504.77 520.77
## + MaxHR           1   508.45 524.45
## + RestingBP       1   509.47 525.47
## <none>                512.29 526.29
## + RestingECG      1   512.14 528.14
## - Cholesterol     1   525.54 537.54
## - FastingBS       1   531.18 543.18
## - ChestPainType   1   531.95 543.95
## - Sex             1   536.56 548.56
## - ExerciseAngina  1   541.21 553.21
## - ST_Slope        1   624.27 636.27
## 
## Step:  AIC=517.31
## y ~ ST_Slope + ExerciseAngina + Cholesterol + Sex + ChestPainType + 
##     FastingBS + Oldpeak
## 
##                  Df Deviance    AIC
## + Age             1   495.83 513.83
## + MaxHR           1   496.10 514.10
## + RestingBP       1   499.20 517.20
## <none>                501.31 517.31
## + RestingECG      1   501.24 519.24
## - Oldpeak         1   512.29 526.29
## - Cholesterol     1   515.89 529.89
## - FastingBS       1   518.95 532.95
## - ChestPainType   1   519.63 533.63
## - ExerciseAngina  1   521.97 535.97
## - Sex             1   525.05 539.05
## - ST_Slope        1   574.92 588.92
## 
## Step:  AIC=513.83
## y ~ ST_Slope + ExerciseAngina + Cholesterol + Sex + ChestPainType + 
##     FastingBS + Oldpeak + Age
## 
##                  Df Deviance    AIC
## + MaxHR           1   493.14 513.14
## <none>                495.83 513.83
## + RestingBP       1   494.82 514.82
## + RestingECG      1   495.80 515.80
## - Age             1   501.31 517.31
## - Oldpeak         1   504.77 520.77
## - Cholesterol     1   508.25 524.25
## - FastingBS       1   511.28 527.28
## - ExerciseAngina  1   513.77 529.77
## - ChestPainType   1   514.15 530.15
## - Sex             1   521.06 537.06
## - ST_Slope        1   565.52 581.52
## 
## Step:  AIC=513.14
## y ~ ST_Slope + ExerciseAngina + Cholesterol + Sex + ChestPainType + 
##     FastingBS + Oldpeak + Age + MaxHR
## 
##                  Df Deviance    AIC
## <none>                493.14 513.14
## - MaxHR           1   495.83 513.83
## - Age             1   496.10 514.10
## + RestingBP       1   492.34 514.34
## + RestingECG      1   492.87 514.87
## - Cholesterol     1   503.14 521.14
## - Oldpeak         1   503.31 521.31
## - ExerciseAngina  1   508.00 526.00
## - ChestPainType   1   508.48 526.48
## - FastingBS       1   508.86 526.86
## - Sex             1   516.94 534.94
## - ST_Slope        1   555.62 573.62
## 
## Call:  glm(formula = y ~ ST_Slope + ExerciseAngina + Cholesterol + Sex + 
##     ChestPainType + FastingBS + Oldpeak + Age + MaxHR, family = "binomial", 
##     data = cbind(X, y))
## 
## Coefficients:
##    (Intercept)        ST_Slope  ExerciseAngina     Cholesterol             Sex  
##         0.4400         -1.0844          0.5019         -0.3952          0.5652  
##  ChestPainType       FastingBS         Oldpeak             Age           MaxHR  
##        -0.4610          0.4919          0.4322          0.2186         -0.2217  
## 
## Degrees of Freedom: 688 Total (i.e. Null);  679 Residual
## Null Deviance:       947.4 
## Residual Deviance: 493.1     AIC: 513.1

Check fit of Logistic Regression - HL Test

lr_fit(selected_log)
## [1] 0.479482
## [1] "R squared:"
## [1] 0.479482
## [1] "p-value for overall fit:"
## [1] 3.51281e-92
## 
##  Hosmer and Lemeshow goodness of fit (GOF) test
## 
## data:  lr_model$y, fitted(lr_model)
## X-squared = 6.2977, df = 8, p-value = 0.6139

Evaluate Logistic Regression Model with Confusion Matrix and roc curve

lr_eval <- roc_eval(selected_log, test_X, test_y)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
## [1] "best threshold"
##   threshold
## 1 0.5365748

## [1] "auc:"
## Area under the curve: 0.9034
cfmat_eval(test_X, test_y, get_preds(selected_log, test_X, lr_eval$best_threshold))
## $cfmat
##       predicted
## actual FALSE TRUE
##      0    87   15
##      1    15  112
## 
## $accuracy
## [1] 0.8689956
## 
## $precision
## [1] 0.8818898
## 
## $recall
## [1] 0.8818898
## 
## $f1_measure
## [1] 0.8818898
## 
## $sensitivity
## [1] 0.8818898
## 
## $specificity
## [1] 0.8529412

Regularized Logistic Regression

lr1 <- LiblineaR(train_X, train_y, type = 6)
lr2 <- LiblineaR(train_X, train_y, type = 7)

Regularized Logistic Regression Evaluation

lr1_eval <- roc_eval(lr1, test_X, test_y)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
## [1] "best threshold"
##   threshold
## 1 0.5624144

## [1] "auc:"
## Area under the curve: 0.9036
cfmat_eval(test_X, test_y, get_preds(lr1, test_X, lr1_eval$best_threshold))
## $cfmat
##       predicted
## actual FALSE TRUE
##      0    88   14
##      1    18  109
## 
## $accuracy
## [1] 0.860262
## 
## $precision
## [1] 0.8861789
## 
## $recall
## [1] 0.8582677
## 
## $f1_measure
## [1] 0.872
## 
## $sensitivity
## [1] 0.8582677
## 
## $specificity
## [1] 0.8627451
lr2_eval <- roc_eval(lr2, test_X, test_y)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
## [1] "best threshold"
##   threshold
## 1 0.5727877

## [1] "auc:"
## Area under the curve: 0.9031
cfmat_eval(test_X, test_y, get_preds(lr2, test_X, lr2_eval$best_threshold))
## $cfmat
##       predicted
## actual FALSE TRUE
##      0    88   14
##      1    18  109
## 
## $accuracy
## [1] 0.860262
## 
## $precision
## [1] 0.8861789
## 
## $recall
## [1] 0.8582677
## 
## $f1_measure
## [1] 0.872
## 
## $sensitivity
## [1] 0.8582677
## 
## $specificity
## [1] 0.8627451

SVM

lr_svm <- LiblineaR(train_X, train_y, type = 2)
e1071_svm <- svm(factor(y)~., data = cbind(train_X, train_y), kernel = 'linear', type = 'C-classification')

SVM Evaluation

cfmat_eval(test_X, test_y, get_preds(lr_svm, test_X))
## $cfmat
##       predicted
## actual   0   1
##      0  84  18
##      1  14 113
## 
## $accuracy
## [1] 0.860262
## 
## $precision
## [1] 0.8625954
## 
## $recall
## [1] 0.8897638
## 
## $f1_measure
## [1] 0.875969
## 
## $sensitivity
## [1] 0.8897638
## 
## $specificity
## [1] 0.8235294
cfmat_eval(test_X, test_y, get_preds(e1071_svm, test_X))
## $cfmat
##       predicted
## actual   0   1
##      0  86  16
##      1  15 112
## 
## $accuracy
## [1] 0.8646288
## 
## $precision
## [1] 0.875
## 
## $recall
## [1] 0.8818898
## 
## $f1_measure
## [1] 0.8784314
## 
## $sensitivity
## [1] 0.8818898
## 
## $specificity
## [1] 0.8431373

Decision Tree

dtree <- rpart(factor(y)~., data = cbind(train_X, train_y), method = 'class')
rpart.plot(dtree)

dtree_eval <- roc_eval(dtree, test_X, test_y)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
## [1] "best threshold"
##   threshold
## 1 0.4157895

## [1] "auc:"
## Area under the curve: 0.8932
cfmat_eval(test_X, test_y, get_preds(dtree, test_X, dtree_eval$best_threshold))
## $cfmat
##       predicted
## actual FALSE TRUE
##      0    81   21
##      1     7  120
## 
## $accuracy
## [1] 0.8777293
## 
## $precision
## [1] 0.8510638
## 
## $recall
## [1] 0.9448819
## 
## $f1_measure
## [1] 0.8955224
## 
## $sensitivity
## [1] 0.9448819
## 
## $specificity
## [1] 0.7941176

Bagging

bg <- bagging(factor(y)~., data = cbind(train_X, train_y))
bg_eval <- roc_eval(bg, test_X, test_y)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
## [1] "best threshold"
##   threshold
## 1      0.62

## [1] "auc:"
## Area under the curve: 0.9093
cfmat_eval(test_X, test_y, get_preds(bg, test_X, bg_eval$best_threshold))
## $cfmat
##       predicted
## actual FALSE TRUE
##      0    85   17
##      1    17  110
## 
## $accuracy
## [1] 0.8515284
## 
## $precision
## [1] 0.8661417
## 
## $recall
## [1] 0.8661417
## 
## $f1_measure
## [1] 0.8661417
## 
## $sensitivity
## [1] 0.8661417
## 
## $specificity
## [1] 0.8333333

Random Forest

rforest <- randomForest(factor(y)~., data = cbind(train_X, train_y))
rforest_eval <- roc_eval(rforest, test_X, test_y)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
## [1] "best threshold"
##   threshold
## 1     0.593

## [1] "auc:"
## Area under the curve: 0.9308
cfmat_eval(test_X, test_y, get_preds(rforest, test_X, rforest_eval$best_threshold))
## $cfmat
##       predicted
## actual FALSE TRUE
##      0    89   13
##      1    14  113
## 
## $accuracy
## [1] 0.8820961
## 
## $precision
## [1] 0.8968254
## 
## $recall
## [1] 0.8897638
## 
## $f1_measure
## [1] 0.8932806
## 
## $sensitivity
## [1] 0.8897638
## 
## $specificity
## [1] 0.872549

Ada Boost

acc_adaB <- bestK_adaB(train_X, train_y, test_X, test_y, 1, 30)
## Processing the case with  1 trees. 
## Processing the case with  2 trees. 
## Processing the case with  3 trees. 
## Processing the case with  4 trees. 
## Processing the case with  5 trees. 
## Processing the case with  6 trees. 
## Processing the case with  7 trees. 
## Processing the case with  8 trees. 
## Processing the case with  9 trees. 
## Processing the case with  10 trees. 
## Processing the case with  11 trees. 
## Processing the case with  12 trees. 
## Processing the case with  13 trees. 
## Processing the case with  14 trees. 
## Processing the case with  15 trees. 
## Processing the case with  16 trees. 
## Processing the case with  17 trees. 
## Processing the case with  18 trees. 
## Processing the case with  19 trees. 
## Processing the case with  20 trees. 
## Processing the case with  21 trees. 
## Processing the case with  22 trees. 
## Processing the case with  23 trees. 
## Processing the case with  24 trees. 
## Processing the case with  25 trees. 
## Processing the case with  26 trees. 
## Processing the case with  27 trees. 
## Processing the case with  28 trees. 
## Processing the case with  29 trees. 
## Processing the case with  30 trees.
best_k <- acc_adaB$k[which.max(acc_adaB$accuracy_rate)]
data_adaboost <- cbind(train_X, train_y)
data_adaboost$y <- factor(data_adaboost$y)
adaB <- boosting(y~., data = data_adaboost, mfinal = best_k)
adaB_eval <- roc_eval(adaB, test_X, test_y)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
## [1] "best threshold"
##   threshold
## 1 0.5433347

## [1] "auc:"
## Area under the curve: 0.9051
cfmat_eval(test_X, test_y, get_preds(adaB, test_X, adaB_eval$best_threshold))
## $cfmat
##       predicted
## actual FALSE TRUE
##      0    84   18
##      1    14  113
## 
## $accuracy
## [1] 0.860262
## 
## $precision
## [1] 0.8625954
## 
## $recall
## [1] 0.8897638
## 
## $f1_measure
## [1] 0.875969
## 
## $sensitivity
## [1] 0.8897638
## 
## $specificity
## [1] 0.8235294

Aggregate Voting

# Regularized Logistic Model, SVM, Random Forest, Boosting
pred_rf <- get_preds(rforest, test_X, rforest_eval$best_threshold)
pred_rlr <- get_preds(lr2, test_X, lr2_eval$best_threshold)
pred_svm <- get_preds(lr_svm, test_X)
pred_adaB <- get_preds(adaB, test_X, adaB_eval$best_threshold)
pred_dtree <- get_preds(dtree, test_X, dtree_eval$best_threshold)
pred_aggregate <- cbind(pred_rf, pred_rlr, pred_svm, pred_adaB, pred_dtree)

prob_rf <- get_probs(rforest, test_X)
prob_rlr <- get_probs(lr2, test_X)
prob_adaB <- get_probs(adaB, test_X)
prob_dtree <- get_probs(dtree, test_X)
prob_aggregate <- cbind(prob_rf, prob_rlr, prob_adaB, prob_dtree)

# Hard Voting (Majority Wins)
get_majority <- function(row) {
  one_voters <- length(which(row == 1))
  if (one_voters > length(row) / 2) {
    return(1)
  }
  return(0)
}
pred_majority <- apply(pred_aggregate, 1, get_majority)
cfmat_eval(test_X, test_y, pred_majority)
## $cfmat
##       predicted
## actual   0   1
##      0  85  17
##      1  13 114
## 
## $accuracy
## [1] 0.8689956
## 
## $precision
## [1] 0.870229
## 
## $recall
## [1] 0.8976378
## 
## $f1_measure
## [1] 0.8837209
## 
## $sensitivity
## [1] 0.8976378
## 
## $specificity
## [1] 0.8333333
# Average Probabilities
avg_probs <- apply(prob_aggregate, 1, mean)
preds_avg <- avg_probs > 0.5
cfmat_eval(test_X, test_y, preds_avg)
## $cfmat
##       predicted
## actual FALSE TRUE
##      0    83   19
##      1     7  120
## 
## $accuracy
## [1] 0.8864629
## 
## $precision
## [1] 0.8633094
## 
## $recall
## [1] 0.9448819
## 
## $f1_measure
## [1] 0.9022556
## 
## $sensitivity
## [1] 0.9448819
## 
## $specificity
## [1] 0.8137255
# Weighted Probabilities
weights <- c(0.5, 0.2, 0.3, 0)
get_weighted_pred <- function(row) {
  weighted_avg <- sum(row * weights)
  return(weighted_avg > 0.5)
}
preds_weighted <- apply(prob_aggregate, 1, get_weighted_pred)
cfmat_eval(test_X, test_y, preds_weighted)
## $cfmat
##       predicted
## actual FALSE TRUE
##      0    84   18
##      1    10  117
## 
## $accuracy
## [1] 0.8777293
## 
## $precision
## [1] 0.8666667
## 
## $recall
## [1] 0.9212598
## 
## $f1_measure
## [1] 0.8931298
## 
## $sensitivity
## [1] 0.9212598
## 
## $specificity
## [1] 0.8235294
B = 1000
set.seed(300)

model_names <- c('L2-Logistic Model', 'SVM', 'Decision Tree', 'Bagging', 'Random Forest', 'AdaBoost')
metrics <- data.frame(matrix(0, B, length(model_names)))
colnames(metrics) <- model_names


# for (i in 1:B) {
#   dat <- split_data(X, y)
#   train_X <- dat$train_X
#   train_y <- dat$train_y
#   test_X <- dat$test_X
#   test_y <- dat$test_y
#   
#   # L2-Logistic Model
#   lr1 <- LiblineaR(train_X, train_y, type = 6)
#   lr1_eval <- roc_eval(lr2, test_X, test_y, print_plot = F)
#   rlr_cfmat <- cfmat_eval(test_X, test_y, get_preds(lr1, test_X, lr1_eval$best_threshold))
#   metrics[i, 1] <- rlr_cfmat$accuracy 
#   
#   # svm
#   lr_svm <- LiblineaR(train_X, train_y, type = 2)
#   e1071_svm <- svm(factor(y)~., data = cbind(train_X, train_y), kernel = 'linear', type = 'C-classification')
#   cfmat_eval(test_X, test_y, get_preds(lr_svm, test_X))
#   svm_cfmat <- cfmat_eval(test_X, test_y, get_preds(e1071_svm, test_X))
#   metrics[i, 2] <- svm_cfmat$accuracy
#   
#   # Decision Tree
#   dtree <- rpart(factor(y)~., data = cbind(train_X, train_y), method = 'class')
#   dtree_eval <- roc_eval(dtree, test_X, test_y, print_plot = F)
#   dtree_cfmat <- cfmat_eval(test_X, test_y, get_preds(dtree, test_X, dtree_eval$best_threshold))
#   metrics[i, 3] <- dtree_cfmat$accuracy
#   
#   # bagging
#   bg <- bagging(factor(y)~., data = cbind(train_X, train_y))
#   bg_eval <- roc_eval(bg, test_X, test_y, print_plot = F)
#   bg_cfmat <- cfmat_eval(test_X, test_y, get_preds(bg, test_X, bg_eval$best_threshold))
#   metrics[i, 4] <- bg_cfmat$accuracy
#   
#   # Random Forest
#   rforest <- randomForest(factor(y)~., data = cbind(train_X, train_y))
#   rforest_eval <- roc_eval(rforest, test_X, test_y, print_plot = F)
#   rforest_cfmat <- cfmat_eval(test_X, test_y, get_preds(rforest, test_X, rforest_eval$best_threshold))
#   metrics[i, 5] <- rforest_cfmat$accuracy
#   
#   # Ada boost
#   # acc_adaB <- bestK_adaB(train_X, train_y, test_X, test_y, 1, 30)
#   # best_k <- acc_adaB$k[which.max(acc_adaB$accuracy_rate)]
#   
#   data_adaboost <- cbind(train_X, train_y)
#   data_adaboost$y <- factor(data_adaboost$y)
#   adaB <- boosting(y~., data = data_adaboost, mfinal = 30)
#   adaB_eval <- roc_eval(adaB, test_X, test_y, print_plot = F)
#   adaB_cfmat <- cfmat_eval(test_X, test_y, get_preds(adaB, test_X, adaB_eval$best_threshold))
#   metrics[i, 6] <- adaB_cfmat$accuracy
#   
#   cat('Finished iteration: ', i)
# }
# 
# average_metrics <- apply(metrics, 2, mean)
# average_metrics