Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
9 changes: 9 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -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.

## Partial dependence curves

* `sdmApp_response()` gains `type = "partial"`: partial dependence curves
Expand Down
88 changes: 88 additions & 0 deletions R/sdmApp_model.R
Original file line number Diff line number Diff line change
Expand Up @@ -1341,3 +1341,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
}
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions _pkgdown.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ reference:
- sdmApp_tune
- sdmApp_tuning_grid
- sdmApp_null
- sdmApp_compare
- sdmApp_ensemble
- sdmApp_project
- sdmApp_importance
Expand Down
1 change: 1 addition & 0 deletions inst/shiny/sdmApp/controllers/ui_code.R
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
40 changes: 40 additions & 0 deletions inst/shiny/sdmApp/controllers/ui_ensemble.R
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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),
Expand Down
65 changes: 65 additions & 0 deletions inst/shiny/sdmApp/helpers.R
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -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")
}
Expand Down Expand Up @@ -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)
)
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion inst/shiny/sdmApp/server.R
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
48 changes: 48 additions & 0 deletions man/sdmApp_compare.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions tests/testthat/test-app-server.R
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,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"
Expand Down
Loading
Loading