Heart Failure Prediction using Bagging Algorithm in R

This code demonstrates how to implement a bagging algorithm in R to predict heart failure events based on clinical data. The data used is a CSV file called 'heart_failure_clinical_records_dataset.csv' containing information about patients with heart failure.

1. Load the Data

data <- read.csv('heart_failure_clinical_records_dataset.csv')

2. Split the Data into Training and Testing Sets

train_index <- sample(1:nrow(data), 0.8 * nrow(data))
train_data <- data[train_index, ]
test_data <- data[-train_index, ]

3. Define the Bagging Function

bagging <- function(train_data, test_data, num_models) {
  # Initialize model list and prediction matrix
  models <- list()
predictions <- matrix(0, nrow = nrow(test_data), ncol = num_models)
  
  # Train models and make predictions
  for (i in 1:num_models) {
    # Randomly sample with replacement
    sample_index <- sample(1:nrow(train_data), replace = TRUE)
    sample_data <- train_data[sample_index, ]
    
    # Train decision tree model
    model <- rpart(DEATH_EVENT ~ ., data = sample_data)
    # Add model to model list
    models[[i]] <- model
    
    # Make predictions on test data
    predictions[, i] <- predict(model, test_data, type = 'class')
  }
  
  # Majority vote for final prediction
  final_predictions <- apply(predictions, 1, function(x) {
    ifelse(sum(x == 1) > sum(x == 0), 1, 0)
  })
  
  # Return final predictions
  return(final_predictions)
}

4. Run the Bagging Algorithm and Calculate Accuracy

predictions <- bagging(train_data, test_data, 10)
accuracy <- sum(predictions == test_data$DEATH_EVENT) / length(predictions)
print(paste('Bagging accuracy:', round(accuracy, 2)))

This code first loads the data, then splits it into training and testing sets. The bagging function takes the training and testing data, as well as the number of models to create, as arguments. It then loops through the specified number of models, randomly sampling with replacement from the training data to create a new training set for each model. A decision tree model is trained on each of these new training sets, and predictions are made on the test data. Finally, the majority vote of all the models is used to generate the final predictions. The accuracy is then calculated as the proportion of correctly predicted heart failure events in the test data.

This example demonstrates a basic implementation of bagging in R for heart failure prediction. You can modify the code to explore other models, different sampling strategies, and various parameter tunings to improve the performance of the bagging algorithm.

Heart Failure Prediction using Bagging Algorithm in R