## ----include = FALSE---------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 7, fig.height = 4 ) library(figsr) ## ----load--------------------------------------------------------------------- str(pima_diabetes) ## ----missingness-------------------------------------------------------------- predictors_with_gaps <- c("Glucose", "BloodPressure", "SkinThickness", "Insulin", "BMI") missing_rate <- vapply(pima_diabetes[predictors_with_gaps], function(x) mean(is.na(x)), numeric(1)) knitr::kable( data.frame(predictor = names(missing_rate), missing_pct = sprintf("%.1f%%", 100 * missing_rate)), row.names = FALSE ) ## ----fit---------------------------------------------------------------------- set.seed(42) train_idx <- sample(nrow(pima_diabetes), floor(0.75 * nrow(pima_diabetes))) train <- pima_diabetes[train_idx, ] test <- pima_diabetes[-train_idx, ] fit_omit <- figs(Outcome ~ ., data = train, max_splits = 10, mode = "classification") fit_mia <- figs(Outcome ~ ., data = train, max_splits = 10, mode = "classification", na_method = "mia") cat("training rows used, omit:", length(fit_omit$fitted_values), "of", nrow(train), "\n") cat("training rows used, mia :", length(fit_mia$fitted_values), "of", nrow(train), "\n") test_complete <- complete.cases(test[, predictors_with_gaps]) cat("test patients omit can score at all:", sum(test_complete), "of", nrow(test), "\n") cat("test patients mia can score :", nrow(test), "of", nrow(test), "\n") ## ----accuracy----------------------------------------------------------------- accuracy <- function(predicted, observed) mean(predicted == observed) pred_omit <- predict(fit_omit, test[test_complete, ], type = "class")$.pred_class pred_mia <- predict(fit_mia, test, type = "class")$.pred_class cat("accuracy, omit, on the", sum(test_complete), "patients it can score:", round(accuracy(pred_omit, test$Outcome[test_complete]), 3), "\n") cat("accuracy, mia, on those same", sum(test_complete), "patients :", round(accuracy(pred_mia[test_complete], test$Outcome[test_complete]), 3), "\n") cat("accuracy, mia, on all", nrow(test), "test patients :", round(accuracy(pred_mia, test$Outcome), 3), "\n") ## ----rules-------------------------------------------------------------------- summary(fit_mia) ## ----importance--------------------------------------------------------------- figsr_importance(fit_mia) ## ----plot, fig.width = 8, fig.height = 4.5, fig.alt = "Three trees of the Pima diabetes tree sum, rooted in Glucose, Age and BMI, with positive leaves in green and negative leaves in red."---- fit_plot <- figs(Outcome ~ ., data = train, max_splits = 4, mode = "classification", na_method = "mia") root_features <- vapply(fit_plot$trees, function(tr) tr[[1]]$feature, character(1)) plot(fit_plot, main = "Pima diabetes: tree sum under na_method = \"mia\"", tree_names = paste0("splits first on ", root_features)) .