From a817f0834be97a396369367e5d7c34c7e4d19da4 Mon Sep 17 00:00:00 2001 From: Aboubacar HEMA Date: Tue, 1 Dec 2026 08:55:48 +0000 Subject: [PATCH] Compare fitted models side by side - New sdmApp_compare(): one row per model with the mean and SD of its cross-validated AUC, TSS and Boyce index, its predictors, points, folds and settings, best first. - The Ensemble page has a "Compare models" tab with this table, box plots of the metrics of every fold and the suitability maps side by side (rescaled to 0-1); the R-Code tab records the comparison. Co-Authored-By: Claude Opus 5.5 --- NAMESPACE | 1 + NEWS.md | 9 +++ R/sdmApp_model.R | 88 +++++++++++++++++++++ README.md | 3 +- _pkgdown.yml | 1 + inst/shiny/sdmApp/controllers/ui_code.R | 1 + inst/shiny/sdmApp/controllers/ui_ensemble.R | 40 ++++++++++ inst/shiny/sdmApp/helpers.R | 65 +++++++++++++++ inst/shiny/sdmApp/server.R | 2 +- man/sdmApp_compare.Rd | 48 +++++++++++ tests/testthat/test-app-server.R | 5 ++ tests/testthat/test-sdmApp_compare.R | 42 ++++++++++ 12 files changed, 303 insertions(+), 2 deletions(-) create mode 100644 man/sdmApp_compare.Rd create mode 100644 tests/testthat/test-sdmApp_compare.R diff --git a/NAMESPACE b/NAMESPACE index a6adc40..d7928a8 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -14,6 +14,7 @@ export(sdmApp_background) export(sdmApp_boyce) export(sdmApp_broken_stick) export(sdmApp_cmip6) +export(sdmApp_compare) export(sdmApp_enfa) export(sdmApp_enfa_plot) export(sdmApp_ensemble) diff --git a/NEWS.md b/NEWS.md index 1b15a13..1ccd1a3 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,14 @@ # sdmApp (development version) +## Comparing models + +* New `sdmApp_compare()` tabulates fitted models: the mean and standard + deviation of their cross-validated AUC, TSS and Boyce index, their + number of predictors and points, folds and settings, best first. +* The Ensemble page has a "Compare models" tab with this table, box plots + of the metrics of every fold and the suitability maps side by side; the + R-Code tab records the comparison. + ## Documentation * New vignette "A complete modelling workflow in R" diff --git a/R/sdmApp_model.R b/R/sdmApp_model.R index ff5d80a..6275969 100644 --- a/R/sdmApp_model.R +++ b/R/sdmApp_model.R @@ -1304,3 +1304,91 @@ null_one <- function(shuffle, fit, params) { boyce = mean(m$boyce, na.rm = TRUE) ) } + +#' Compare fitted models +#' +#' A table comparing models fitted with [sdmApp_fit()]: the mean and +#' standard deviation of their cross-validated AUC, TSS and Boyce index, +#' their number of predictors, folds and settings. Models are compared +#' fairly only when they share the same occurrences and folds, which the +#' table shows. +#' +#' @param fits A list of `sdmApp_fit` objects (`NULL` elements are +#' dropped). Names, when given, label the models; otherwise their method +#' is used. +#' @param metric The metric ordering the models (highest mean first): +#' `"auc"`, `"tss"` or `"boyce"`. +#' +#' @return A data frame with one row per model. +#' @examples +#' \donttest{ +#' if (requireNamespace("dismo", quietly = TRUE)) { +#' env <- sdmApp_read_layers(system.file("extdata", +#' c("bio1.tif", "bio12.tif"), +#' package = "sdmApp" +#' )) +#' occ <- utils::read.csv2(system.file("extdata", "Niakhar.csv", +#' package = "sdmApp" +#' )) +#' occ <- sdmApp_occurrences(occ[1:500, ], "X_WGS84", "Y_WGS84", +#' "Faidherbia.albida", +#' crs = terra::crs(env) +#' ) +#' glm <- sdmApp_fit(env, occ, "Faidherbia.albida", method = "glm", k = 3) +#' bioclim <- sdmApp_fit(env, occ, "Faidherbia.albida", +#' method = "bioclim", k = 3 +#' ) +#' sdmApp_compare(list(glm, bioclim)) +#' } +#' } +#' @export +sdmApp_compare <- function(fits, metric = c("auc", "tss", "boyce")) { + metric <- match.arg(metric) + fits <- Filter(Negate(is.null), fits) + if (length(fits) == 0L) { + stop("'fits' contains no fitted model.", call. = FALSE) + } + if (!all(vapply(fits, inherits, logical(1), "sdmApp_fit"))) { + stop("'fits' must be a list of models fitted with sdmApp_fit().", + call. = FALSE + ) + } + labels <- names(fits) + if (is.null(labels)) { + labels <- rep("", length(fits)) + } + methods <- vapply(fits, function(f) sdm_method_label(f$method), "") + labels[!nzchar(labels)] <- methods[!nzchar(labels)] + rows <- lapply(fits, function(f) { + m <- f$fold_metrics + s <- f$settings + params <- s$params + data.frame( + auc = mean(m$auc), auc_sd = stats::sd(m$auc), + tss = mean(m$tss), tss_sd = stats::sd(m$tss), + boyce = mean(m$boyce, na.rm = TRUE), + boyce_sd = stats::sd(m$boyce, na.rm = TRUE), + predictors = length(f$predictors), + points = nrow(f$data), + folds = if (isTRUE(s$spatial)) { + paste(s$k, "blocks") + } else { + paste(s$k, "random") + }, + settings = if (length(params)) { + paste(names(params), vapply(params, format, ""), + sep = " = ", + collapse = ", " + ) + } else { + "defaults" + } + ) + }) + out <- cbind(model = labels, method = vapply(fits, `[[`, "", "method"), + do.call(rbind, rows) + ) + out <- out[order(-out[[metric]]), , drop = FALSE] + rownames(out) <- NULL + out +} diff --git a/README.md b/README.md index 21ab53e..4a558c2 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,8 @@ CRAN, install it from GitHub (see below). algorithms * Tune the settings of each method (regularization, complexity...) by cross-validation with `sdmApp_tune()` -* Combine the models into an ensemble weighted by their cross-validated AUC +* Compare the fitted models side by side (`sdmApp_compare()`), and + combine them into an ensemble weighted by their cross-validated AUC or TSS * Map the uncertainty of every model, ensemble and projection: the spread of the cross-validation fold models, and the disagreement between diff --git a/_pkgdown.yml b/_pkgdown.yml index 72c64e7..ae8eab3 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -39,6 +39,7 @@ reference: - sdmApp_tune - sdmApp_tuning_grid - sdmApp_null + - sdmApp_compare - sdmApp_ensemble - sdmApp_project - sdmApp_importance diff --git a/inst/shiny/sdmApp/controllers/ui_code.R b/inst/shiny/sdmApp/controllers/ui_code.R index 1d5148b..985754e 100644 --- a/inst/shiny/sdmApp/controllers/ui_code.R +++ b/inst/shiny/sdmApp/controllers/ui_code.R @@ -47,6 +47,7 @@ analysis_steps <- reactive({ f$settings ) }), + compare = code_state$compare, ensemble = if (!is.null(ens)) ens$settings, projections = intersect( code_state$projections, c(vapply(fits, `[[`, "", "method"), "ensemble") diff --git a/inst/shiny/sdmApp/controllers/ui_ensemble.R b/inst/shiny/sdmApp/controllers/ui_ensemble.R index f210d5f..7ccbf70 100644 --- a/inst/shiny/sdmApp/controllers/ui_ensemble.R +++ b/inst/shiny/sdmApp/controllers/ui_ensemble.R @@ -37,6 +37,31 @@ output$ensemble_available <- renderTable( digits = 3 ) +# Compare models ------------------------------------------------------------- + +comparison <- reactive({ + fits <- fitted_models() + validate(need(length(fits) > 0, "No model fitted yet.")) + metric <- if (is.null(input$compare_metric)) "auc" else input$compare_metric + code_state$compare <- metric + sdmApp::sdmApp_compare(fits, metric = metric) +}) + +output$compare_table <- renderTable( + { + out <- comparison() + out$method <- NULL + names(out) <- c( + "Model", "AUC", "SD", "TSS", "SD", "Boyce", "SD", "Predictors", + "Points", "Folds", "Settings" + ) + out + }, + digits = 3 +) +output$compare_metrics <- renderPlot(plot_fold_metrics(fitted_models())) +output$compare_maps <- renderPlot(plot_model_maps(fitted_models())) + ensemble <- eventReactive(input$ensemble_run, { withProgress(message = "Building the ensemble", { tryCatch( @@ -114,6 +139,21 @@ output$ui_ensemble <- renderUI({ ), mainPanel(width = 8, do.call(tabsetPanel, c( list(type = "tabs"), + list(tabPanel( + "Compare models", + p( + "The models fitted in the other pages, side by side. They are", + "compared fairly only when fitted on the same points and folds." + ), + selectInput("compare_metric", "Order by", + c("Mean AUC" = "auc", "Mean TSS" = "tss", "Mean Boyce" = "boyce") + ), + div(style = "overflow-x: auto;", tableOutput("compare_table")), + h4("Metrics of every cross-validation fold"), + plotOutput("compare_metrics"), + h4("Suitability maps (each rescaled to 0-1)"), + plotOutput("compare_maps", height = "500px") + )), list(tabPanel( "Map", selectInput("ensemble_map_type", NULL, ensemble_map_choices), diff --git a/inst/shiny/sdmApp/helpers.R b/inst/shiny/sdmApp/helpers.R index d2ac49e..736042b 100644 --- a/inst/shiny/sdmApp/helpers.R +++ b/inst/shiny/sdmApp/helpers.R @@ -13,6 +13,9 @@ # Bounding box of a raster in longitude/latitude (internal to the package). lonlat_extent <- utils::getFromNamespace("lonlat_extent", "sdmApp") +# Rescaling of a model's map to [0, 1] (internal to the package). +rescale_to_map <- utils::getFromNamespace("rescale_to_map", "sdmApp") + sdm_method_label <- function(method) { m <- sdmApp::sdmApp_methods() m$label[match(method, m$id)] @@ -294,6 +297,53 @@ plot_null <- function(x) { ggplot2::theme_bw() } +# Box plots of the fold metrics of several models. +plot_fold_metrics <- function(fits) { + rows <- lapply(fits, function(f) { + m <- f$fold_metrics + data.frame( + model = sdm_method_label(f$method), + metric = rep(c("AUC", "TSS", "Boyce index"), each = nrow(m)), + value = c(m$auc, m$tss, m$boyce) + ) + }) + d <- do.call(rbind, rows) + d <- d[is.finite(d$value), ] + d$metric <- factor(d$metric, c("AUC", "TSS", "Boyce index")) + ggplot2::ggplot(d, ggplot2::aes( + x = .data[["model"]], y = .data[["value"]] + )) + + ggplot2::geom_boxplot(fill = "grey90", outlier.shape = NA) + + ggplot2::geom_point(colour = "darkgreen", alpha = 0.7) + + ggplot2::facet_wrap(~metric, scales = "free_y") + + ggplot2::labs(x = NULL, y = NULL) + + ggplot2::theme_bw() + + ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 30, hjust = 1)) +} + +# Suitability maps of several models, each rescaled to [0, 1] so that +# models on different scales can be compared. +plot_model_maps <- function(fits) { + rows <- lapply(fits, function(f) { + r <- rescale_to_map(f$prediction, f) + d <- raster_df(r, "value") + d$model <- sdm_method_label(f$method) + d + }) + d <- do.call(rbind, rows) + ggplot2::ggplot(d) + + ggplot2::geom_raster(ggplot2::aes( + x = .data[["x"]], y = .data[["y"]], fill = .data[["value"]] + )) + + ggplot2::scale_fill_viridis_c(name = "Suitability", limits = c(0, 1)) + + ggplot2::scale_x_continuous(n.breaks = 3) + + ggplot2::facet_wrap(~model) + + ggplot2::coord_equal() + + ggplot2::labs(x = NULL, y = NULL) + + ggplot2::theme_bw() + + ggplot2::theme(panel.spacing.x = grid::unit(1.5, "lines")) +} + evaluation_types <- function() { c("ROC", "density", "boxplot", "kappa", "FPR", "prevalence") } @@ -530,6 +580,7 @@ analysis_script <- function(steps) { }, script_blocks(steps$blocks, species), script_models(steps$models, species, has_blocks = !is.null(steps$blocks)), + script_compare(steps$models, steps$compare), script_ensemble(steps$ensemble), if (!is.null(steps$future)) script_projections(steps$projections) ) @@ -757,6 +808,20 @@ script_models <- function(models, species, has_blocks) { c(r_section("Models"), utils::head(unlist(fits), -1)) } +script_compare <- function(models, metric) { + if (is.null(metric) || length(models) < 2L) { + return(NULL) + } + fits <- paste0("fit_", vapply(models, `[[`, "", "method")) + c( + r_section("Comparison of models"), + r_call("sdmApp_compare", list( + r_code(paste0("list(", paste(fits, collapse = ", "), ")")), + metric = metric + )) + ) +} + script_ensemble <- function(ens) { if (is.null(ens)) { return(NULL) diff --git a/inst/shiny/sdmApp/server.R b/inst/shiny/sdmApp/server.R index 6620e32..9e430e8 100644 --- a/inst/shiny/sdmApp/server.R +++ b/inst/shiny/sdmApp/server.R @@ -20,7 +20,7 @@ function(input, output, session) { # (models and ensembles are read from their own results). code_state <- reactiveValues( correlation = FALSE, vif = NULL, enfa = FALSE, projections = character(), - nulls = list() + nulls = list(), compare = NULL ) ui_state <- reactiveValues( preparation = "btn_preparation_1", diff --git a/man/sdmApp_compare.Rd b/man/sdmApp_compare.Rd new file mode 100644 index 0000000..e40a371 --- /dev/null +++ b/man/sdmApp_compare.Rd @@ -0,0 +1,48 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/sdmApp_model.R +\name{sdmApp_compare} +\alias{sdmApp_compare} +\title{Compare fitted models} +\usage{ +sdmApp_compare(fits, metric = c("auc", "tss", "boyce")) +} +\arguments{ +\item{fits}{A list of \code{sdmApp_fit} objects (\code{NULL} elements are +dropped). Names, when given, label the models; otherwise their method +is used.} + +\item{metric}{The metric ordering the models (highest mean first): +\code{"auc"}, \code{"tss"} or \code{"boyce"}.} +} +\value{ +A data frame with one row per model. +} +\description{ +A table comparing models fitted with \code{\link[=sdmApp_fit]{sdmApp_fit()}}: the mean and +standard deviation of their cross-validated AUC, TSS and Boyce index, +their number of predictors, folds and settings. Models are compared +fairly only when they share the same occurrences and folds, which the +table shows. +} +\examples{ +\donttest{ +if (requireNamespace("dismo", quietly = TRUE)) { + env <- sdmApp_read_layers(system.file("extdata", + c("bio1.tif", "bio12.tif"), + package = "sdmApp" + )) + occ <- utils::read.csv2(system.file("extdata", "Niakhar.csv", + package = "sdmApp" + )) + occ <- sdmApp_occurrences(occ[1:500, ], "X_WGS84", "Y_WGS84", + "Faidherbia.albida", + crs = terra::crs(env) + ) + glm <- sdmApp_fit(env, occ, "Faidherbia.albida", method = "glm", k = 3) + bioclim <- sdmApp_fit(env, occ, "Faidherbia.albida", + method = "bioclim", k = 3 + ) + sdmApp_compare(list(glm, bioclim)) +} +} +} diff --git a/tests/testthat/test-app-server.R b/tests/testthat/test-app-server.R index 93e8ac9..0e37c73 100644 --- a/tests/testthat/test-app-server.R +++ b/tests/testthat/test-app-server.R @@ -87,6 +87,11 @@ test_that("the shiny app runs a full analysis", { session$setInputs(`maxnet-run` = 1) expect_s3_class(model_fits$maxnet()$model, "maxnet") expect_length(fitted_models(), 3) + session$setInputs(compare_metric = "tss") + expect_type(output$compare_table, "character") + expect_false(is.unsorted(-comparison()$tss)) + expect_type(output$compare_maps$src, "character") + expect_true(any(grepl("sdmApp_compare(", current_code(), fixed = TRUE))) session$setInputs( ensemble_weight = "auc", ensemble_min_auc = 0, ensemble_map_type = "probability" diff --git a/tests/testthat/test-sdmApp_compare.R b/tests/testthat/test-sdmApp_compare.R new file mode 100644 index 0000000..1aeef80 --- /dev/null +++ b/tests/testthat/test-sdmApp_compare.R @@ -0,0 +1,42 @@ +test_that("sdmApp_compare tabulates and ranks fitted models", { + skip_if_not(app_deps_available(c("terra", "dismo"))) + h <- app_helpers() + env <- small_env(h) + occ <- small_occ(h, env) + glm <- sdmApp_fit(env, occ, "Faidherbia.albida", "glm", + k = 3, uncertainty = FALSE, params = list(quadratic = TRUE) + ) + bioclim <- sdmApp_fit(env, occ, "Faidherbia.albida", "bioclim", + k = 3, uncertainty = FALSE + ) + + out <- sdmApp_compare(list(glm, NULL, bioclim), metric = "tss") + expect_equal(nrow(out), 2) + expect_false(is.unsorted(-out$tss)) + row <- out[out$method == "glm", ] + expect_equal(row$auc, mean(glm$fold_metrics$auc)) + expect_equal(row$tss_sd, stats::sd(glm$fold_metrics$tss)) + expect_identical(row$model, "Generalized Linear Models") + expect_identical(row$settings, "quadratic = TRUE") + expect_identical(row$folds, "3 random") + expect_equal(row$predictors, 3) + expect_identical(out$settings[out$method == "bioclim"], "defaults") + + named <- sdmApp_compare(list(a = glm, b = bioclim)) + expect_setequal(named$model, c("a", "b")) + expect_false(is.unsorted(-named$auc)) + + expect_error(sdmApp_compare(list()), "no fitted model") + expect_error(sdmApp_compare(list(1)), "sdmApp_fit") + + expect_drawable(h$plot_fold_metrics(list(glm, bioclim))) + expect_drawable(h$plot_model_maps(list(glm, bioclim))) + code <- h$script_compare( + list(list(method = "glm"), list(method = "bioclim")), "auc" + ) + expect_true(any(grepl( + "sdmApp_compare(list(fit_glm, fit_bioclim), metric = \"auc\")", code, + fixed = TRUE + ))) + expect_null(h$script_compare(list(list(method = "glm")), "auc")) +})