From 3f754eda654fc7ff701e94e919bc62c51231fc10 Mon Sep 17 00:00:00 2001 From: Aboubacar HEMA Date: Tue, 1 Dec 2026 09:21:19 +0000 Subject: [PATCH] Measure the spatial sorting bias of cross-validation folds - New sdmApp_ssb(): for each fold, the mean distance from test presences to the nearest training presence divided by that of test absences (Hijmans 2012); well below 1, the AUC is inflated by distance alone. It agrees with dismo::ssb(). - Fits keep the coordinates of their points (cv$coords). - The per-fold evaluation table of the interface shows the sorting bias; the workflow vignette explains it. Co-Authored-By: Claude Opus 5.5 --- NAMESPACE | 1 + NEWS.md | 11 +++ R/sdmApp_model.R | 96 ++++++++++++++++++++++++++- _pkgdown.yml | 1 + inst/shiny/sdmApp/modules/sdm_model.R | 16 ++++- man/sdmApp_ssb.Rd | 60 +++++++++++++++++ tests/testthat/test-sdmApp_ssb.R | 56 ++++++++++++++++ vignettes/workflow.Rmd | 15 +++++ 8 files changed, 253 insertions(+), 3 deletions(-) create mode 100644 man/sdmApp_ssb.Rd create mode 100644 tests/testthat/test-sdmApp_ssb.R diff --git a/NAMESPACE b/NAMESPACE index d7928a8..e7c02fe 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -29,6 +29,7 @@ export(sdmApp_occurrences) export(sdmApp_project) export(sdmApp_read_layers) export(sdmApp_response) +export(sdmApp_ssb) export(sdmApp_thin) export(sdmApp_tss) export(sdmApp_tune) diff --git a/NEWS.md b/NEWS.md index 4e76de6..3a6f9ea 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,16 @@ # sdmApp (development version) +## Spatial sorting bias + +* New `sdmApp_ssb()` measures the spatial sorting bias of each + cross-validation fold (Hijmans 2012): the mean distance from test + presences to the nearest training presence, divided by that of test + absences. Well below 1, the AUC is inflated by distance alone. It agrees + with `dismo::ssb()`. +* Fits keep the coordinates of their points (`cv$coords`) for this + purpose, and the per-fold evaluation table of the interface shows the + sorting bias. + ## Comparing models * New `sdmApp_compare()` tabulates fitted models: the mean and standard diff --git a/R/sdmApp_model.R b/R/sdmApp_model.R index 3c5f738..41c2db3 100644 --- a/R/sdmApp_model.R +++ b/R/sdmApp_model.R @@ -394,7 +394,11 @@ sdmApp_fit <- function(env, occ, species, method = "glm", k = 5, evaluation = evaluation, threshold = threshold, # The folds and Boyce background, reused by sdmApp_null(). - cv = list(folds = setup$folds, background = setup$background), + cv = list( + folds = setup$folds, background = setup$background, + coords = sf::st_coordinates(occ)[dat$row, 1:2, drop = FALSE], + lonlat = isTRUE(sf::st_is_longlat(occ)) + ), settings = list( k = if (is.null(fold_ids)) k else length(unique(fold_ids)), spatial = !is.null(fold_ids), seed = seed, @@ -1429,3 +1433,93 @@ sdmApp_compare <- function(fits, metric = c("auc", "tss", "boyce")) { rownames(out) <- NULL out } + +#' Spatial sorting bias of cross-validation folds +#' +#' Measures, for each cross-validation fold of a model, whether the test +#' presences lie closer to the training presences than the test absences +#' do (Hijmans 2012). When they do, a model can score a high AUC merely by +#' telling places near known presences from places far from them, without +#' learning anything about the environment: the AUC is then inflated. +#' +#' For each fold, the distance from every test presence to the nearest +#' training presence, and from every test absence to the nearest training +#' presence, are computed (great-circle distances for geographic +#' coordinates). The spatial sorting bias is the ratio of their means: +#' close to 1, the evaluation is not biased by distance; well below 1 (for +#' example under 0.5), test presences are much closer to training data +#' than test absences, which is typical of random folds with clustered +#' presences. Spatial blocks or environmental folds reduce the bias. +#' +#' @param x An `sdmApp_fit` object. +#' +#' @return A data frame with one row per fold: the mean distance (in +#' metres for geographic coordinates, map units otherwise) from the test +#' presences (`presence_distance`) and test absences +#' (`absence_distance`) to the nearest training presence, and their ratio +#' `ssb`. +#' +#' @references Hijmans, R. J. (2012). Cross-validation of species +#' distribution models: removing spatial sorting bias and calibration +#' with a null model. *Ecology*, 93, 679--688. +#' \doi{10.1890/11-0826.1} +#' +#' @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) +#' ) +#' fit <- sdmApp_fit(env, occ, "Faidherbia.albida", method = "glm", k = 3) +#' sdmApp_ssb(fit) +#' } +#' } +#' @export +sdmApp_ssb <- function(x) { + if (!inherits(x, "sdmApp_fit")) { + stop("'x' must be a model fitted with sdmApp_fit().", call. = FALSE) + } + if (is.null(x$cv$coords)) { + stop("Refit the model with this version of sdmApp: it lacks the ", + "coordinates of its points.", + call. = FALSE + ) + } + xy <- x$cv$coords + pa <- x$data$pa + folds <- x$cv$folds + rows <- lapply(sort(unique(folds)), function(fold) { + test <- folds == fold + train_p <- xy[!test & pa == 1, , drop = FALSE] + test_p <- xy[test & pa == 1, , drop = FALSE] + test_a <- xy[test & pa == 0, , drop = FALSE] + if (nrow(train_p) == 0L || nrow(test_p) == 0L || nrow(test_a) == 0L) { + return(NULL) + } + nearest <- function(from) { + d <- terra::distance(from, train_p, lonlat = x$cv$lonlat) + apply(d, 1, min) + } + dp <- mean(nearest(test_p)) + da <- mean(nearest(test_a)) + data.frame( + fold = fold, presence_distance = dp, absence_distance = da, + ssb = if (da > 0) dp / da else NA_real_ + ) + }) + out <- do.call(rbind, rows) + if (is.null(out)) { + stop("No fold has training presences and test presences and absences.", + call. = FALSE + ) + } + out +} diff --git a/_pkgdown.yml b/_pkgdown.yml index ae8eab3..f0874f8 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -39,6 +39,7 @@ reference: - sdmApp_tune - sdmApp_tuning_grid - sdmApp_null + - sdmApp_ssb - sdmApp_compare - sdmApp_ensemble - sdmApp_project diff --git a/inst/shiny/sdmApp/modules/sdm_model.R b/inst/shiny/sdmApp/modules/sdm_model.R index 280d997..2e01311 100644 --- a/inst/shiny/sdmApp/modules/sdm_model.R +++ b/inst/shiny/sdmApp/modules/sdm_model.R @@ -100,6 +100,14 @@ sdm_model_ui <- function(id, method, layer_names) { "threshold maximising the TSS of the pooled out-of-fold predictions." ), shiny::tableOutput(ns("metrics_summary")), + shiny::p( + class = "text-muted", + "Sorting bias (Hijmans 2012): mean distance from the test presences", + "to the nearest training presence, divided by that of the test", + "absences. Well below 1, test presences lie much closer to the", + "training data than test absences and the AUC is inflated: use", + "spatial blocks or environmental folds." + ), shiny::tableOutput(ns("fold_metrics")), shiny::downloadButton(ns("download_metrics"), "Download metrics (csv)"), shiny::h4("Evaluation plots (pooled out-of-fold predictions)"), @@ -338,9 +346,13 @@ sdm_model_server <- function(id, method, env, occ, species, spatial_cv, ) output$fold_metrics <- shiny::renderTable( { - m <- ready_fit()$fold_metrics + f <- ready_fit() + m <- f$fold_metrics + ssb <- tryCatch(sdmApp::sdmApp_ssb(f), error = function(e) NULL) + m$ssb <- if (is.null(ssb)) NA else ssb$ssb[match(m$fold, ssb$fold)] names(m) <- c( - "Fold", "Test presences", "Test absences", "AUC", "TSS", "Boyce" + "Fold", "Test presences", "Test absences", "AUC", "TSS", "Boyce", + "Sorting bias" ) m }, diff --git a/man/sdmApp_ssb.Rd b/man/sdmApp_ssb.Rd new file mode 100644 index 0000000..33c274b --- /dev/null +++ b/man/sdmApp_ssb.Rd @@ -0,0 +1,60 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/sdmApp_model.R +\name{sdmApp_ssb} +\alias{sdmApp_ssb} +\title{Spatial sorting bias of cross-validation folds} +\usage{ +sdmApp_ssb(x) +} +\arguments{ +\item{x}{An \code{sdmApp_fit} object.} +} +\value{ +A data frame with one row per fold: the mean distance (in +metres for geographic coordinates, map units otherwise) from the test +presences (\code{presence_distance}) and test absences +(\code{absence_distance}) to the nearest training presence, and their ratio +\code{ssb}. +} +\description{ +Measures, for each cross-validation fold of a model, whether the test +presences lie closer to the training presences than the test absences +do (Hijmans 2012). When they do, a model can score a high AUC merely by +telling places near known presences from places far from them, without +learning anything about the environment: the AUC is then inflated. +} +\details{ +For each fold, the distance from every test presence to the nearest +training presence, and from every test absence to the nearest training +presence, are computed (great-circle distances for geographic +coordinates). The spatial sorting bias is the ratio of their means: +close to 1, the evaluation is not biased by distance; well below 1 (for +example under 0.5), test presences are much closer to training data +than test absences, which is typical of random folds with clustered +presences. Spatial blocks or environmental folds reduce the bias. +} +\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) + ) + fit <- sdmApp_fit(env, occ, "Faidherbia.albida", method = "glm", k = 3) + sdmApp_ssb(fit) +} +} +} +\references{ +Hijmans, R. J. (2012). Cross-validation of species +distribution models: removing spatial sorting bias and calibration +with a null model. \emph{Ecology}, 93, 679--688. +\doi{10.1890/11-0826.1} +} diff --git a/tests/testthat/test-sdmApp_ssb.R b/tests/testthat/test-sdmApp_ssb.R new file mode 100644 index 0000000..6d1bfe6 --- /dev/null +++ b/tests/testthat/test-sdmApp_ssb.R @@ -0,0 +1,56 @@ +test_that("spatial sorting bias compares test presences and absences", { + skip_if_not(app_deps_available(c("terra", "dismo"))) + h <- app_helpers() + env <- small_env(h) + occ <- small_occ(h, env) + fit <- sdmApp_fit(env, occ, "Faidherbia.albida", "glm", + k = 3, uncertainty = FALSE + ) + ssb <- sdmApp_ssb(fit) + expect_identical(names(ssb), c( + "fold", "presence_distance", "absence_distance", "ssb" + )) + expect_equal(nrow(ssb), 3) + expect_equal(ssb$ssb, ssb$presence_distance / ssb$absence_distance) + expect_true(all(ssb$ssb > 0)) + + # Same distances as dismo::ssb() (which uses a sphere rather than the + # WGS84 ellipsoid, hence the tolerance). + xy <- fit$cv$coords + pa <- fit$data$pa + test <- fit$cv$folds == 1 + d <- dismo::ssb( + p = xy[test & pa == 1, ], a = xy[test & pa == 0, ], + reference = xy[!test & pa == 1, ], lonlat = TRUE + ) + expect_equal(ssb$presence_distance[1], unname(d[1, 1]), tolerance = 0.01) + expect_equal(ssb$absence_distance[1], unname(d[1, 2]), tolerance = 0.01) +}) + +test_that("presences clustered near the training data show sorting bias", { + skip_if_not(app_deps_available(c("terra", "dismo"))) + # Presences in two tight clusters, absences spread over the area: random + # folds put test presences right next to training presences. + set.seed(1) + pres <- rbind( + cbind(stats::rnorm(60, 0, 0.01), stats::rnorm(60, 0, 0.01)), + cbind(stats::rnorm(60, 1, 0.01), stats::rnorm(60, 1, 0.01)) + ) + abs <- cbind(stats::runif(240, -1, 2), stats::runif(240, -1, 2)) + fit <- structure(list( + data = data.frame(pa = c(rep(1, 120), rep(0, 240))), + cv = list( + coords = rbind(pres, abs), lonlat = FALSE, + folds = sample(rep(1:3, length.out = 360)) + ) + ), class = "sdmApp_fit") + expect_true(all(sdmApp_ssb(fit)$ssb < 0.1)) +}) + +test_that("sdmApp_ssb validates its input", { + expect_error(sdmApp_ssb(list()), "sdmApp_fit") + expect_error( + sdmApp_ssb(structure(list(cv = list()), class = "sdmApp_fit")), + "Refit the model" + ) +}) diff --git a/vignettes/workflow.Rmd b/vignettes/workflow.Rmd index 2a32720..597c0df 100644 --- a/vignettes/workflow.Rmd +++ b/vignettes/workflow.Rmd @@ -198,6 +198,16 @@ c( ) ``` +Random folds are optimistic partly because of spatial sorting bias +(Hijmans 2012): their test presences lie close to training presences, so +a model can score well by distance alone. `sdmApp_ssb()` measures it for +each fold; values well below 1 signal an inflated AUC: + +```{r ssb} +sdmApp_ssb(random)$ssb +sdmApp_ssb(glm)$ssb +``` + ## Is the model better than chance? A modest AUC can arise by chance, especially with few or clustered @@ -288,6 +298,11 @@ results and maps. # References +Hijmans, R. J. (2012). Cross-validation of species distribution models: +removing spatial sorting bias and calibration with a null model. +*Ecology*, 93, 679--688. +[doi:10.1890/11-0826.1](https://doi.org/10.1890/11-0826.1) + Raes, N. and ter Steege, H. (2007). A null-model for significance testing of presence-only species distribution models. *Ecography*, 30, 727--736. [doi:10.1111/j.2007.0906-7590.05041.x](https://doi.org/10.1111/j.2007.0906-7590.05041.x)