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 @@ -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)
Expand Down
11 changes: 11 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
96 changes: 95 additions & 1 deletion R/sdmApp_model.R
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
}
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_ssb
- sdmApp_compare
- sdmApp_ensemble
- sdmApp_project
Expand Down
16 changes: 14 additions & 2 deletions inst/shiny/sdmApp/modules/sdm_model.R
Original file line number Diff line number Diff line change
Expand Up @@ -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)"),
Expand Down Expand Up @@ -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
},
Expand Down
60 changes: 60 additions & 0 deletions man/sdmApp_ssb.Rd

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

56 changes: 56 additions & 0 deletions tests/testthat/test-sdmApp_ssb.R
Original file line number Diff line number Diff line change
@@ -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"
)
})
15 changes: 15 additions & 0 deletions vignettes/workflow.Rmd
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
Loading