In spatial predictive mapping, models are often applied to make predictions far beyond sampling locations (i.e. field observations used to map a variable even on a global scale), where new locations might considerably differ in their environmental properties. However, areas in the predictor space without support of training data are problematic. The model has not been enabled to learn about relationships in these environments and predictions for such areas have to be considered highly uncertain.
In CAST, we implement the methodology described in Meyer&Pebesma (2021) to estimate the “area of applicability” (AOA) of (spatial) prediction models. The AOA is defined as the area where we enabled the model to learn about relationships based on the training data, and where the estimated cross-validation performance holds. To delineate the AOA, first an dissimilarity index (DI) is calculated that is based on distances to the training data in the multidimensional predictor variable space. To account for relevance of predictor variables responsible for prediction patterns we weight variables by the model-derived importance scores prior to distance calculation. The AOA is then derived by applying a threshold based on the DI observed in the training data using cross-validation.
This tutorial shows an example of how to estimate the area of applicability of spatial prediction models.
For further information see: Meyer, H., & Pebesma, E. (2021). Predicting into unknown space? Estimating the area of applicability of spatial prediction models. Methods in Ecology and Evolution, 12, 1620– 1633. [https://doi.org/10.1111/2041-210X.13650]
library(CAST)
library(virtualspecies)
library(caret)
library(raster)
library(sp)
library(sf)
library(viridis)
library(latticeExtra)
library(gridExtra)
As predictor variables, a set of bioclimatic variables are used (https://www.worldclim.org). For this tutorial, they have been originally downloaded using the getData function from the raster package but cropped to an area in central Europe. The cropped data are provided in the CAST package.
<- stack(system.file("extdata","bioclim.grd",package="CAST"))
predictors spplot(stretch(predictors,0,1),col.regions=viridis(100))
To be able to test the reliability of the method, we’re using a simulated prediction task from the virtualspecies package. Therefore, a virtual response variable is simulated from the bioclimatic variables. See Leroy et al. 2016 for further information on this methodology.
<- generateSpFromPCA(predictors,
response means = c(3,1),sds = c(2,2), plot=F)$suitab.raster
To simulate a typical prediction task, field sampling locations are randomly selected. Here, we randomly select 20 points. Note that this is a very small data set, but used here to avoid long computation times.
<- predictors[[1]]
mask values(mask)[!is.na(values(mask))] <- 1
<- rasterToPolygons(mask)
mask set.seed(15)
<- spsample(mask,20,"random")
samplepoints spplot(response,col.regions=viridis(100),
sp.layout=list("sp.points", samplepoints, col = "red", first = FALSE, cex=2))
Next, a machine learning algorithm will be applied to learn the relationships between predictors and response.
Therefore, predictors and response are extracted for the sampling locations.
<- extract(predictors,samplepoints,df=TRUE)
trainDat $response <- extract (response,samplepoints)
trainDat<- trainDat[complete.cases(trainDat),] trainDat
Random Forest is applied here as machine learning algorithm (others can be used as well, as long as variable importance is returned). The model is validated by default cross-validation to estimate the prediction error.
set.seed(10)
<- train(trainDat[,names(predictors)],
model $response,
trainDatmethod="rf",
importance=TRUE,
trControl = trainControl(method="cv"))
print(model)
## Random Forest
##
## 20 samples
## 6 predictor
##
## No pre-processing
## Resampling: Cross-Validated (10 fold)
## Summary of sample sizes: 18, 18, 18, 18, 18, 18, ...
## Resampling results across tuning parameters:
##
## mtry RMSE Rsquared MAE
## 2 0.1073774 1 0.09361901
## 4 0.1137154 1 0.09806945
## 6 0.1152357 1 0.09832305
##
## RMSE was used to select the optimal model using the smallest value.
## The final value used for the model was mtry = 2.
The estimation of the AOA will require the importance of the individual predictor variables.
plot(varImp(model,scale = F),col="black")
The trained model is then used to make predictions for the entire area of interest. Since a simulated area-wide response is used, it’s possible in this tutorial to compare the predictions with the true reference.
<- predict(predictors,model)
prediction <- abs(prediction-response)
truediff spplot(stack(prediction,response),main=c("prediction","reference"))
The visualization above shows the predictions made by the model. In the next step, the DI and AOA will be calculated.
The AOA calculation takes the model as input to extract the importance of the predictors, used as weights in multidimensional distance calculation. Note that the AOA can also be calculated without a trained model (i.e. using training data and new data only). In this case all predictor variables are treated equally important (unless weights are given in form of a table).
<- aoa(predictors, model)
AOA class(AOA)
## [1] "aoa"
names(AOA)
## [1] "parameters" "DI" "AOA"
print(AOA)
## DI:
## class : RasterLayer
## band : 1 (of 6 bands)
## dimensions : 75, 126, 9450 (nrow, ncol, ncell)
## resolution : 0.1666667, 0.1666667 (x, y)
## extent : 0, 21, 42.33333, 54.83333 (xmin, xmax, ymin, ymax)
## crs : +proj=longlat +datum=WGS84 +no_defs
## source : memory
## names : DI
## values : 0, 4.454402 (min, max)
##
## AOA:
## class : RasterLayer
## dimensions : 75, 126, 9450 (nrow, ncol, ncell)
## resolution : 0.1666667, 0.1666667 (x, y)
## extent : 0, 21, 42.33333, 54.83333 (xmin, xmax, ymin, ymax)
## crs : +proj=longlat +datum=WGS84 +no_defs
## source : memory
## names : AOA
## values : 0, 1 (min, max)
##
##
##
## Predictor Weights:
## bio2 bio5 bio10 bio13 bio14 bio19
## 1 0 7.067908 12.56361 4.012916 7.966633 6.67255
##
##
## AOA Threshold: 0.5538818
Plotting the aoa
object shows the distribution of DI
values within the training data and the DI of the new data.
plot(AOA)
The most output of the aoa
function are two raster data:
The first is the DI that is the normalized and weighted minimum distance
to a nearest training data point divided by the average distance within
the training data. The AOA is derived from the DI by using a threshold.
The threshold is the (outlier-removed) maximum DI observed in the
training data where the DI of the training data is calculated by
considering the cross-validation folds. The used threshold and all
relevant information about the training data DI is returned in the
parameters
list entry.
We can plot the DI as well as predictions onyl in the AOA:
grid.arrange(
spplot(truediff,col.regions=viridis(100),main="true prediction error"),
spplot(AOA$DI,col.regions=viridis(100),main="DI"),
spplot(prediction, col.regions=viridis(100),main="prediction for AOA")+ spplot(AOA$AOA,col.regions=c("grey","transparent")), ncol=3)
The patterns in the DI are in general agreement with the true prediction error. Very high values are present in the Alps, as they have not been covered by training data but feature very distinct environmental conditions. Since the DI values for these areas are above the threshold, we regard this area as outside the AOA.
The example above had randomly distributed training samples. However, sampling locations might also be highly clustered in space. In this case, the random cross-validation is not meaningful (see e.g. Meyer et al. 2018, Meyer et al. 2019, Valavi et al. 2019, Roberts et al. 2018, Pohjankukka et al. 2017, Brenning 2012)
Also the threshold for the AOA is not reliable, because it is based in distance to a nearest data point within the training data (which is usually very small when data are clustered). Instead, cross-validation should be based on a leave-cluster-out approach, and the AOA estimation based on distances to a nearest data point not located in the same spatial cluster.
To show how this looks like, we use 15 spatial locations and simulate 5 data points around each location.
<- csample(mask,75,15,maxdist=0.20,seed=15)
samplepoints spplot(response,col.regions=viridis(100),
sp.layout=list("sp.points", samplepoints, col = "red", first = FALSE, cex=2))
<- extract(predictors,samplepoints,df=TRUE)
trainDat $response <- extract (response,samplepoints)
trainDat<- merge(trainDat,samplepoints,by.x="ID",by.y="ID")
trainDat <- trainDat[complete.cases(trainDat),] trainDat
We first train a model with (in this case) inappropriate random cross-validation.
set.seed(10)
<- train(trainDat[,names(predictors)],
model_random $response,
trainDatmethod="rf",
importance=TRUE,
trControl = trainControl(method="cv"))
<- predict(predictors,model_random)
prediction_random print(model_random)
## Random Forest
##
## 74 samples
## 6 predictor
##
## No pre-processing
## Resampling: Cross-Validated (10 fold)
## Summary of sample sizes: 67, 66, 67, 67, 66, 68, ...
## Resampling results across tuning parameters:
##
## mtry RMSE Rsquared MAE
## 2 0.03974841 0.9823678 0.02607400
## 4 0.04141946 0.9768478 0.02723152
## 6 0.04440358 0.9660298 0.02769020
##
## RMSE was used to select the optimal model using the smallest value.
## The final value used for the model was mtry = 2.
…and a model based on leave-cluster-out cross-validation.
<- CreateSpacetimeFolds(trainDat, spacevar="clstrID",k=10)
folds set.seed(15)
<- train(trainDat[,names(predictors)],
model $response,
trainDatmethod="rf",
importance=TRUE,
tuneGrid = expand.grid(mtry = c(2:length(names(predictors)))),
trControl = trainControl(method="cv",index=folds$index))
print(model)
## Random Forest
##
## 74 samples
## 6 predictor
##
## No pre-processing
## Resampling: Cross-Validated (10 fold)
## Summary of sample sizes: 65, 69, 64, 69, 69, 64, ...
## Resampling results across tuning parameters:
##
## mtry RMSE Rsquared MAE
## 2 0.10593803 0.9510812 0.09272544
## 3 0.10148947 0.9497758 0.08949359
## 4 0.09880060 0.9511211 0.08831501
## 5 0.09745684 0.9475100 0.08500127
## 6 0.09405651 0.9358441 0.07826757
##
## RMSE was used to select the optimal model using the smallest value.
## The final value used for the model was mtry = 6.
<- predict(predictors,model) prediction
The AOA is then calculated (for comparison) using the model validated by random cross-validation, and second by taking the spatial clusters into account and calculating the threshold based on minimum distances to a nearest training point not located in the same cluster. This is done in the aoa function, where the folds used for cross-validation are automatically extracted from the model.
<- aoa(predictors, model)
AOA_spatial
<- aoa(predictors, model_random) AOA_random
grid.arrange(spplot(AOA_spatial$DI,col.regions=viridis(100),main="DI"),
spplot(prediction, col.regions=viridis(100),main="prediction for AOA \n(spatial CV error applies)")+
spplot(AOA_spatial$AOA,col.regions=c("grey","transparent")),
spplot(prediction_random, col.regions=viridis(100),main="prediction for AOA \n(random CV error applies)")+
spplot(AOA_random$AOA,col.regions=c("grey","transparent")),
ncol=3)
Note that the AOA is much larger for the spatial CV approach.
However, the spatial cross-validation error is considerably larger,
hence also the area for which this error applies is larger. The random
cross-validation performance is very high, however, the area to which
the performance applies is small. This fact is also apparent if you plot
the aoa
objects which will display the distributions of the
DI of the training data as well as the DI of the new data. For random CV
most of the predictionDI is larger than the AOA threshold determined by
the trainDI. Using spatial CV, the predictionDI is well within the DI of
the training samples.
grid.arrange(plot(AOA_spatial) + ggplot2::ggtitle("Spatial CV"),
plot(AOA_random) + ggplot2::ggtitle("Random CV"), ncol = 2)
Since we used a simulated response variable, we can now compare the prediction error within the AOA with the model error, assuming that the model error applies inside the AOA but not outside.
###for the spatial CV:
RMSE(values(prediction)[values(AOA_spatial$AOA)==1],values(response)[values(AOA_spatial$AOA)==1])
## [1] 0.144699
RMSE(values(prediction)[values(AOA_spatial$AOA)==0],values(response)[values(AOA_spatial$AOA)==1])
## [1] 0.6043159
$results model
## mtry RMSE Rsquared MAE RMSESD RsquaredSD MAESD
## 1 2 0.10593803 0.9510812 0.09272544 0.08646254 0.07738562 0.07948987
## 2 3 0.10148947 0.9497758 0.08949359 0.07678120 0.05976871 0.07336123
## 3 4 0.09880060 0.9511211 0.08831501 0.07396796 0.04235858 0.07082438
## 4 5 0.09745684 0.9475100 0.08500127 0.07095399 0.05115963 0.06752482
## 5 6 0.09405651 0.9358441 0.07826757 0.06947137 0.06544289 0.06521768
###and for the random CV:
RMSE(values(prediction_random)[values(AOA_random$AOA)==1],values(response)[values(AOA_random$AOA)==1])
## [1] 0.02120467
RMSE(values(prediction_random)[values(AOA_random$AOA)==0],values(response)[values(AOA_random$AOA)==1])
## [1] 0.3430948
$results model_random
## mtry RMSE Rsquared MAE RMSESD RsquaredSD MAESD
## 1 2 0.03974841 0.9823678 0.02607400 0.02753849 0.02573214 0.01740092
## 2 4 0.04141946 0.9768478 0.02723152 0.02640911 0.03526562 0.01634504
## 3 6 0.04440358 0.9660298 0.02769020 0.03153891 0.05067483 0.01771655
The results indicate that there is a high agreement between the model CV error (RMSE) and the true prediction RMSE. This is the case for both, the random as well as the spatial model.
The relationship between error and DI can be used to limit predictions to an area (within the AOA) where a required performance (e.g. RMSE, R2, Kappa, Accuracy) applies. This can be done using the result of calibrate_aoa which used the relationship analyzed in a window of DI values. The corresponding model (here: shape constrained additive models which is the default: Monotone increasing P-splines with the dimension of the basis used to represent the smooth term is 6 and a 2nd order penalty.) can be used to estimate the performance on a pixel level, which then allows limiting predictions using a threshold. Note that we used a multi-purpose CV to estimate the relationship between the DI and the RMSE here (see details in the paper).
<- calibrate_aoa(AOA_spatial,model,window.size = 5,length.out = 5, multiCV=TRUE,showPlot=FALSE)
AOA_calib $plot AOA_calib
spplot(AOA_calib$AOA$expected_RMSE,col.regions=viridis(100),main="expected RMSE")+
spplot(AOA$AOA,col.regions=c("grey","transparent"))
The example above used simulated data so that it allows to analyze the reliability of the AOA. However, a simulated area-wide response is not available in usual prediction tasks. Therefore, as a second example the AOA is estimated for a dataset that has point observations as a reference only.
To do so, we will work with the cookfarm dataset, described in e.g. Gasch et al 2015. The dataset included in CAST is a re-structured dataset. Find more details also in the vignette “Introduction to CAST”. We will use soil moisture (VW) as response variable here. Hence, we’re aiming at making a spatial continuous prediction based on limited measurements from data loggers.
<- get(load(system.file("extdata","Cookfarm.RData",package="CAST")))
dat # calculate average of VW for each sampling site:
<- aggregate(dat[,c("VW","Easting","Northing")],by=list(as.character(dat$SOURCEID)),mean)
dat # create sf object from the data:
<- st_as_sf(dat,coords=c("Easting","Northing"))
pts
##### Extract Predictors for the locations of the sampling points
<- stack(system.file("extdata","predictors_2012-03-25.grd",package="CAST"))
studyArea st_crs(pts) <- crs(studyArea)
<- extract(studyArea,pts,df=TRUE)
trainDat $ID <- 1:nrow(pts)
pts<- merge(trainDat,pts,by.x="ID",by.y="ID")
trainDat # The final training dataset with potential predictors and VW:
head(trainDat)
## ID DEM TWI BLD NDRE.M NDRE.Sd Bt Easting Northing
## 1 1 788.1906 4.304258 1.42 -0.051189531 0.2506899 0.0000 493384 5180587
## 2 2 788.3813 3.863605 1.29 -0.046459336 0.1754623 0.0000 493514 5180567
## 3 3 790.5244 3.947488 1.36 -0.040845532 0.2225785 0.0000 493574 5180577
## 4 4 775.7229 5.395786 1.55 -0.004329725 0.2099845 0.0501 493244 5180587
## 5 5 796.7618 3.534822 1.31 0.027252737 0.2002646 0.0000 493624 5180607
## 6 6 795.8370 3.815516 1.40 -0.123434804 0.2180606 0.0000 493694 5180607
## MinT_wrcc MaxT_wrcc Precip_cum cday Precip_wrcc Group.1 VW
## 1 1.1 36.2 10.6 15425 0 CAF003 0.2938029
## 2 1.1 36.2 10.6 15425 0 CAF007 0.2737227
## 3 1.1 36.2 10.6 15425 0 CAF009 0.2723993
## 4 1.1 36.2 10.6 15425 0 CAF019 0.3134010
## 5 1.1 36.2 10.6 15425 0 CAF031 0.2751161
## 6 1.1 36.2 10.6 15425 0 CAF033 0.2602674
## geometry
## 1 POINT (493383.1 5180586)
## 2 POINT (493510.7 5180568)
## 3 POINT (493574.6 5180573)
## 4 POINT (493246.6 5180590)
## 5 POINT (493628.3 5180612)
## 6 POINT (493692.2 5180610)
A set of variables is used as predictors for VW in a random Forest model. The model is validated with a leave one out cross-validation. Note that the model performance is very low, due to the small dataset being used here (and for this small dataset a low ability of the predictors to model VW).
<- c("DEM","NDRE.Sd","TWI","Bt")
predictors <- "VW"
response
<- train(trainDat[,predictors],trainDat[,response],
model method="rf",tuneLength=3,importance=TRUE,
trControl=trainControl(method="LOOCV"))
model
## Random Forest
##
## 42 samples
## 4 predictor
##
## No pre-processing
## Resampling: Leave-One-Out Cross-Validation
## Summary of sample sizes: 41, 41, 41, 41, 41, 41, ...
## Resampling results across tuning parameters:
##
## mtry RMSE Rsquared MAE
## 2 0.03819834 0.009739749 0.03019681
## 3 0.03915934 0.003965186 0.03137026
## 4 0.03927946 0.002627254 0.03150797
##
## RMSE was used to select the optimal model using the smallest value.
## The final value used for the model was mtry = 2.
Next, the model is used to make predictions for the entire study area.
#Predictors:
spplot(stretch(studyArea[[predictors]]))
#prediction:
<- predict(studyArea,model) prediction
Next we’re limiting the predictions to the AOA. Predictions outside the AOA should be excluded.
<- aoa(studyArea,model)
AOA
#### Plot results:
grid.arrange(spplot(AOA$DI,col.regions=viridis(100),main="DI with sampling locations (red)")+
spplot(as_Spatial(pts),zcol="ID",col.regions="red"),
spplot(prediction, col.regions=viridis(100),main="prediction for AOA \n(LOOCV error applies)")+ spplot(AOA$AOA,col.regions=c("grey","transparent")),ncol=2)
Meyer, H., & Pebesma, E. (2022): Machine learning-based global maps of ecological variables and the challenge of assessing them. Nature Communications. Accepted.
Meyer, H., & Pebesma, E. (2021). Predicting into unknown space? Estimating the area of applicability of spatial prediction models. Methods in Ecology and Evolution, 12, 1620– 1633. [https://doi.org/10.1111/2041-210X.13650]
Tutorial (https://youtu.be/EyP04zLe9qo) and Lecture (https://youtu.be/OoNH6Nl-X2s) recording from OpenGeoHub summer school 2020 on the area of applicability. As well as talk at the OpenGeoHub summer school 2021: https://av.tib.eu/media/54879