Extract the residuals of a fitted model
Source:R/model-classes.R, R/model-rf.R
spatial_fit-residuals.Rdresiduals() on a random forest, a GWR or a Bayesian GP fit returns
the observed response minus fitted(), one value per training row:
for a random forest these are out-of-bag residuals, since its fitted values are out-of-bag predictions. Out-of-bag is a random hold-out: use
cv_rf()on folds at the distances the map will be used at for the forest's accuracy;for a GWR they are in-sample. Where
fit_gwr_model()took the response about its centre (a response at a large offset), the response and the fitted values are both taken about that centre, so the residuals keep digits that rounding at the response's size would lose (see "The local solve" in?fit_gwr_model);for a Bayesian GP they are in-sample, from the cached posterior expectation (spatial_fit-fitted).
residual_morans_i() tests them for spatial structure the
model did not capture.
Examples
library(sf)
set.seed(1)
pts <- st_as_sf(
data.frame(x = 5e5 + runif(60, 0, 1000), y = 5e6 + runif(60, 0, 1000),
a = rnorm(60)),
coords = c("x", "y"), crs = 32632
)
pts$z <- 10 + 2 * pts$a + rnorm(60, 0, 0.3)
rf <- fit_rf_model(pts, "z", "a", num_trees = 50, seed = 1)
summary(residuals(rf)) # out-of-bag residuals
#> Min. 1st Qu. Median Mean 3rd Qu. Max.
#> -0.9261726 -0.2510723 0.0065013 0.0008667 0.3091709 0.9810524