Skip to contents

Cross-validation designs, fold audits, fossil (temporal) validation and tests against sampling bias.

19. Cross-validation and temporal validation: the full workflow

A typical workflow for choosing the algorithms of an ensemble, building it and mapping it. Steps 1 and 4 are explained in 19.1 to 19.3 below; the selection, the ensemble and the thresholds in sections 17, 21 and 22.

  1. Spatial folds. spatial_folds() splits the study area into square blocks and assigns them to folds with balanced numbers of presences and background points. suggest_block_size(env) gives the median range of spatial autocorrelation of the predictors; with points it adds the scale over which the records are more clustered than random points (or, with value, the range of your model’s residuals at the records), and with transfer_km the distance you mean to transfer the model over, and suggests the largest of these. environmental_folds() clusters the records in environmental space instead, to test transfer to new conditions. Audit the folds with fold_report() (see 19.1 Auditing the folds below).
  2. Fit models on all folds but one, for each algorithm, fold and, optionally, several background sets. Predict on the held-out fold.
  3. Hold-out metrics. evaluate_cv() computes AUC, MAE, bias, TSS and the Boyce index per run and summarises them per algorithm (and, given the coordinates, audits the folds). It also shows whether background sets or folds cause more variation, and AUC per fold.
  4. Temporal validation (optional). temporal_validation() checks hindcasts against fossil records (see 19.3 Fossil (temporal) validation below).
  5. Selection. select_models() keeps every algorithm that reaches conventional minimum values (default AUC >= 0.8, TSS >= 0.6; widely used conventions rather than validated limits, so make them stricter or change them with min_metrics to suit the study), only the Pareto front, or both (rule = "both"). For an ensemble the minimum values are usually the better rule: the Pareto front finds the best single models, and a model can reach it through one criterion alone, e.g. the best present-day fit with weak hindcasts. How the Pareto front and the ranking work is explained in section 17.5 above.
  6. Plots. plot(sel) draws the full view and a zoom on the best models; plot_models() draws any two or three metrics, static or interactive (see section 17.6 above).
  7. Ensemble. ensemble_models() combines the prediction rasters of the selected models and maps where they disagree (see section 21 below).
  8. Binary map (optional). thresholds() gives the threshold of the ensemble (or any prediction) under several rules, and threshold_agreement() the cells on which they agree (see section 22 below).

A complete example you can run with the simulated data. It compares three GLMs on 4 spatial folds and 2 background sets:

library(preENM)
sim <- simulate_enm_data(seed = 1, n_presence = 150, n_absence = 600)
pts <- rbind(cbind(sim$presence, occ = 1, set = 0),                  # presences
             cbind(sim$absence, occ = 0, set = rep(1:2, each = 300))) # 2 background sets
pts$fold <- spatial_folds(pts, k = 4, block_size = 100, occ = pts$occ, seed = 1)
pts <- cbind(pts, terra::extract(sim$env, pts[c("lon", "lat")], ID = FALSE))

formulas <- list(GLM_quadratic = occ ~ env1 + I(env1^2) + env2 + I(env2^2),
                 GLM_linear    = occ ~ env1 + env2,
                 GLM_env2_only = occ ~ env2 + I(env2^2))
holdout <- list()
for (s in 1:2) for (f in 1:4) for (a in names(formulas)) {
  d <- pts[pts$set %in% c(0, s), ]              # presences + background set s
  fit <- glm(formulas[[a]], binomial, data = d[d$fold != f, ])
  test <- d[d$fold == f, ]
  holdout[[length(holdout) + 1]] <- data.frame(
    model = a, set = s, fold = f, obs = test$occ,
    pred = predict(fit, test, type = "response"))
}
cv <- evaluate_cv(do.call(rbind, holdout), set = "set")
cv
sel <- select_models(cv, min_metrics = c(AUC = 0.8, TSS = 0.6))
sel
plot_selection(sel)                       # AUC vs MAE
plot_selection(sel, x_metric = "TSS")     # AUC vs TSS
plot(sel)                                 # full view + zoom on the best models
Selection example
Selection example

The input to evaluate_cv() is a simple long table: one row per held-out point and run, with columns model, fold, obs (1/0), pred and, optionally, set. Any modelling software’s output can be put in this form. With biomod2, for example, project the cross-validation models on the evaluation points and keep, for each run, the points of its held-out fold.

19.1 Auditing the folds: leakage, separation and spatial sorting bias

Cross-validation tests a model on data it has not seen, but data leakage, information about the test data reaching the model during training, inflates the reported performance and is widespread in ecological machine learning (Stock et al. 2023, Nature Ecology & Evolution 7, 1743-1745). fold_report() checks a fold assignment, each fold against the rest:

a <- fold_report(pts, pts$fold, occ = pts$occ, env = sim$env,
                 block_size = 100)
a                                        # leakage? which folds?
plot_folds(a, file = "folds.pdf")        # map, leaking records crossed
Folds with three duplicated records split between folds
Folds with three duplicated records split between folds
  • Leakage: records with the same coordinates, or in the same raster cell, in more than one fold. The model has seen the same place and predictor values in training, so the metrics of those folds are inflated; keep one record per cell (thin_by_cell()) before making folds.
  • Spatial separation: the distance from each test record to the nearest training record, against the block size and against the distance between neighbouring records. Folds whose test records are as close to training records as records are to each other behave like random cross-validation, and spatial autocorrelation makes their metrics optimistic (Yoo and Koo 2025, Cartography and Geographic Information Science 52, 596-609; Koldasbayeva and Zaytsev 2025, Ecological Informatics 92, 103521).
  • Environmental separation (with env): the overlap of each predictor’s distribution between training and testing records, and the share of test records outside the training range (extrapolation).
  • Spatial sorting bias (with occ): see below.
  • Time (with time, e.g. the year of each record): the share of training records later than the test records. A model to be projected forward in time should be tested on records later than those it was trained on (folds ordered in time; Koldasbayeva and Zaytsev 2025). For a model of one period this does not matter, so it is reported, not called leakage.
  • Suspect predictors (with env): layers named like coordinates or time (lon, lat, x, y, year, doy, …), which let a model learn where and when records were made rather than the response to the environment (Stock et al. 2023, Table 1). Only the names are checked.

Give evaluate_cv() the coordinate columns and it audits the folds itself, prints the audit with the metrics and warns when leakage is found:

cv <- evaluate_cv(holdout_with_coordinates, set = "set",
                  coords = c("lon", "lat"), env = sim$env, block_size = 100)

Environmental folds. environmental_folds(pts, env, k = 4) places the records in the environmental space of thin_environment() (a PCA of the standardised predictors) and clusters them by k-means; each cluster is a fold. Folds differ in size, and a fold may have no presences (a warning says so).

Spatial sorting bias. Test presences usually lie closer to the training presences than test background points do, so a model scores well by predicting high values near known records (Hijmans 2012, Ecology 93, 679-688). spatial_sorting_bias() gives SSB = Dp / Da, the mean distance from test presences to the nearest training presence divided by that from test background points: 1 = no bias, near 0 = extreme. It also returns a distance-matched sample (pairwise distance sampling): each test presence is paired with the background point at the most similar distance from the training presences, and evaluating on that sample removes the bias.

test <- pts[pts$fold == 1, ]
train <- pts[pts$fold != 1 & pts$occ == 1, ]
s <- spatial_sorting_bias(test[test$occ == 1, ], test[test$occ == 0, ],
                          train, seed = 1)
s                                         # SSB, matched sample
p <- test[test$occ == 1, ][s$presence_index, ]
b <- test[test$occ == 0, ][s$background_index, ]   # evaluate on p and b

19.2 Other fold designs, and how much they change the result

Spatial blocks test transfer between nearby areas. Other questions need other folds (Roberts et al. 2017, Ecography 40, 913-929):

Design Function Tests
Spatial blocks, boundaries shifted spatial_folds(shift = TRUE, seed = ) whether the result depends on where the blocks fall
Buffered blocks buffer_exclusion(points, fold, buffer_km) transfer at least buffer_km from any training point (drop the marked training points)
Environmental folds environmental_folds() transfer to new conditions
Leave one group out group_folds(region) transfer between regions, populations, lineages, cytotypes
Temporal blocks temporal_folds(year, k) prediction forward in time

cv_sensitivity() takes the evaluate_cv() results of the same models under several designs and says how much the metric and the ranking change, and whether the best model stays the same. geographic_null() gives the AUC of predicting by distance to the nearest training presence alone (Hijmans 2012): models must beat it, and a high value means the folds reward closeness to known records.

cs <- cv_sensitivity(random = cv_random, blocks = cv_blocks,
                     buffered = cv_buffered, regions = cv_regions)
cs                                     # does the best model depend on the design?
plot_cv_sensitivity(cs)
geographic_null(pts, pts$fold, pts$occ, cv = cv_blocks)
AUC of the same models under four cross-validation designs
AUC of the same models under four cross-validation designs

19.3 Fossil (temporal) validation

Hindcasts can be tested against dated records, such as fossils or pollen. Records have no true absences, so each record is compared with background cells of the same time slice. Its score is the proportion of those cells with lower predicted suitability (0.5 = random, 1 = perfect). A record spanning several slices, e.g. a 1000-year bin matched to ten 100-year TraCE21k slices, gets its mean score. The mean over records is a “fossil AUC”.

# sites: one row per record x time slice x model (x run), with the prediction
#        under that slice's climate, e.g. columns record, slice, model, run,
#        period, novel, pred
# bg:    the same for background cells (same cells in every slice): slice,
#        model, run, pred
fos <- temporal_validation(
  sites, bg, run = "run", period = "period", novel = "novel",
  combine = list(deep = c("Lateglacial", "Glacial")),  # the periods that matter
  thresholds = thr,       # optional: 10% presence threshold per model and run
  prefix = "fossil")
all <- merge(cv, fos, by = "model")
sel <- select_models(all,
                     min_metrics = c(AUC = 0.8, TSS = 0.6, fossil_AUC_deep = 0.7),
                     max_metrics = c(MAEbal = 0.3),   # calibration, too
                     criteria = c(AUC = "max", MAEbal = "min", fossil_AUC_deep = "max"),
                     tol = 0.01)
plot_selection(sel, x_metric = "AUC", y_metric = "fossil_AUC_deep")

Call temporal_validation() once for all models (the model column; thresholds as a table with model, run, threshold), not once per model: the per-record scores (attr(fos, "records")) then cover every model, and the bootstrap below can compare them.

max_metrics sets upper limits for “lower is better” metrics. A rule with minimum values for discrimination (AUC, TSS) and a maximum for calibration (MAEbal) keeps models that rank sites well and predict sensible values; a model with good AUC but values shifted upwards everywhere (high MAEbal, positive bias) would otherwise pass. Criteria are only enforced through required values: criteria decides the Pareto front and the ranking, not which models pass. When a selected model is far worse than the other selected models on a criterion without a required value, the printout says so and suggests the limit to add:

  SELECTED: ANN, DNN, GLM, MARS, GBM, GAM, MAXNET, FDA, XGBOOST
  Note: MAXNET is selected but its MAEbal (0.332) is far higher than the other
  selected models (0.196-0.236), and MAEbal has no required value. To require
  one, add max_metrics = c(MAEbal = ...).

Are the differences real? Record bootstrap. With a few hundred fossil records, gaps of a few hundredths may be noise. n_boot resamples the records, scoring the same resampled records for every model (a paired comparison):

fos <- temporal_validation(sites, bg, run = "run", period = "period",
                           combine = list(deep = c("Lateglacial", "Glacial")),
                           prefix = "fossil", n_boot = 2000, seed = 1,
                           compare = "fossil_AUC_deep", margin = 0.02)
fos[c("model", "fossil_AUC_deep", "fossil_AUC_deep_lower",
      "fossil_AUC_deep_upper", "fossil_AUC_deep_diff",
      "fossil_AUC_deep_diff_lower", "fossil_AUC_deep_p_best",
      "fossil_AUC_deep_worse")]

Every metric gets a percentile interval (_lower, _upper). For the compare metric you also get the gap to the best model with its paired interval (_diff, _diff_lower, _diff_upper), the share of resamples in which each model is the best (_p_best) or is beaten by the best (_p_worse), and _worse: the gap exceeds margin with 95% confidence. Because records that are hard for one model are usually hard for all, even small gaps are often consistent; a consistent gap is not necessarily an important one. Fix margin (the difference that would matter to you) before looking at the results, and use the bootstrap to report the ranking and its certainty rather than to drop every model that is detectably worse.

Out-of-fold records are pooled. When each record is scored by only one run (spatial cross-validation: the model of fold k scores the records in fold k), the records of all runs are pooled and every record counts once. Averaging the fold means instead would give a few records in a small fold as much weight as many records in a large one. When records are scored by several runs (e.g. every background set), the run values are averaged. pool = TRUE/FALSE forces either; the _sd columns are always the SD across runs, and attr(fos, "records") has the score of every record.

With thresholds, the result also has the sensitivity (_sens), the share of background predicted suitable (_area) and their ratio (_lift): a model that predicts everything as suitable has a lift of 1, however high its sensitivity.

Fossil records from Neotoma (optional; packages neotoma2 and rintcal). Find the dataset IDs of your taxon in the Neotoma Explorer, then:

smp <- download_neotoma(dataset_ids, cache = "neotoma_downloads.rds")
rec <- neotoma_records(smp, taxon_regex = "^Dryas", area = m,
                       max_age = 22000)       # CHELSA-TraCE21k coverage
table(rec$FLAG)                               # why samples are not usable
sb  <- fossil_site_bins(rec, bin_years = 1000)  # one record per site and millennium
sites <- site_bin_slices(sb)                  # record x TraCE21k slice
# add each slice's prediction to `sites` (column pred), then temporal_validation()

A dated record rarely belongs to one slice with certainty. age_slice_weights() turns an age with its error (or a radiocarbon age, calibrated with IntCal20) into the probability of each slice, and temporal_validation(weight = ) then counts each slice of a record by how likely it is instead of equally:

w <- age_slice_weights(age = 12000, sd = 100)   # or c14 = , err =
w
#>   id slice weight
#> 1  1  -102  0.065
#> 2  1  -101  0.232
#> 3  1  -100  0.405
#> 4  1   -99  0.232
#> 5  1   -98  0.065

Each sample keeps its own age and age window (radiocarbon ages are calibrated with IntCal20) and is matched to the CHELSA-TraCE21k century slices it covers (trace21k_id(); use slice_fun for other climate data). Flags mark samples outside M, with zero values, without (calendar) ages or older than the climate data.

Helpers for preparing the climate of each record:

  • anomaly_climate(): past climate = high-resolution present (e.g. CHELSA) plus the climate-model anomaly (past minus the model’s present). It uses a ratio for precipitation and works on point tables (fast) or rasters.
  • outside_range(): flags non-analog climates (outside the calibration range). The fossil_AUC_analog score ignores them.
  • age_to_period(): Holocene / Lateglacial / Glacial from ages in cal BP.
  • threshold_p10(): the 10th-percentile training presence threshold, for sensitivity.

20. Testing the models against sampling bias

A model can reach a high AUC by predicting where people record. null_model_test() replaces the presences by random locations drawn in proportion to recording effort and recomputes the metrics, many times; the p-value is the share of these null values at least as good as the real one:

tab <- extract_predictions(models, presence, background)
null_model_test(tab, pool = models, weight = effort, n_null = 499, seed = 1)

pool supplies the predictions at candidate cells (the model rasters, or a table); weight is a recording-effort raster (see gbif_effort_rasters()) or a column of the table. Without weight the draws are uniform. The models are not refitted, so it works with predictions of any software; it tests the locations, not the flexibility of the algorithm, unlike the null models of Raes and ter Steege (2007).

The null hypothesis is that the model does no better than one whose presences are random locations drawn in proportion to the effort. With effort as weight the null keeps the sampling bias of the records, so a significant result means the model predicts more than where people record; uniform draws are a weaker null for biased records. Significance does not show that the predictors are the causes of the distribution.