| Title: | Spatial Tessellation, Modelling, and Cross-Validation Toolkit |
| Version: | 3.0.0 |
| Description: | Constructs analysis regions from the distribution of the data itself, as an alternative to aggregating onto administrative boundaries that were drawn for unrelated purposes. Seeds and builds Voronoi, Delaunay, hexagonal and square tessellations with reproducible identifiers. Chooses a cell count, by default from a target number of observations per cell, or by scoring a ladder of counts against the spatial structure of the observations. Assigns features to cells and reports for each cell a count, a mean with its standard error and a pooled value pulled toward the mean of the observations in the 8 nearest cells. A design effect can correct the standard errors for autocorrelation within the cells. Projects lon/lat input to a projected coordinate reference system chosen for the extent of the data. Fits geographically weighted regression (its kernels, diagnostics and forward selection follow 'GWmodel'; Lu et al. (2014) <doi:10.1080/10095020.2014.917453>), Bayesian Gaussian process regression (via 'brms', using the Hilbert space approximation of Riutort-Mayol et al. (2023) <doi:10.1007/s11222-022-10167-2>) and random forests (via 'ranger', with the permutation importance of Strobl et al. (2007) <doi:10.1186/1471-2105-8-25>), each behind one S3 class with consistent predict, fitted, residuals and plot methods. Provides spatial cross-validation with random, block, buffered, leave-location-out and nearest-neighbour distance-matched folds (Milà et al. (2022) <doi:10.1111/2041-210X.13851>; Linnenbrink et al. (2024) <doi:10.5194/gmd-17-5897-2024>), forward variable selection, model comparison, prediction onto a regular surface, and the area of applicability of Meyer and Pebesma (2021) <doi:10.1111/2041-210X.13650> to flag where a fitted model extrapolates beyond its training data. |
| License: | MIT + file LICENSE |
| URL: | https://elkronos.github.io/gis_modeling_toolkit/, https://github.com/elkronos/gis_modeling_toolkit |
| BugReports: | https://github.com/elkronos/gis_modeling_toolkit/issues |
| Encoding: | UTF-8 |
| Depends: | R (≥ 4.1.0) |
| Imports: | sf (≥ 1.0), dplyr (≥ 1.0), logger, digest, FNN, stats, methods, utils, parallel |
| Suggests: | sp, GWmodel, ranger, brms (≥ 2.17.0), cmdstanr, loo, tibble, geometry, gstat, ggplot2 (≥ 3.4.0), patchwork, Matrix, nlme, spdep, testthat (≥ 3.1.7), knitr, rmarkdown, units, vctrs, withr |
| Additional_repositories: | https://stan-dev.r-universe.dev |
| Config/testthat/edition: | 3 |
| VignetteBuilder: | knitr |
| Config/roxygen2/version: | 8.1.0 |
| NeedsCompilation: | no |
| Packaged: | 2026-11-22 05:29:38 UTC; appleair |
| Author: | Justin Chase [aut, cre, cph] |
| Maintainer: | Justin Chase <jchase.msu@gmail.com> |
| Repository: | CRAN |
| Date/Publication: | 2026-11-23 08:10:02 UTC |
spatialkit: Spatial Tessellation, Modelling, and Cross-Validation Toolkit
Description
Constructs analysis regions from the distribution of the data itself, as an alternative to aggregating onto administrative boundaries that were drawn for unrelated purposes. Seeds and builds Voronoi, Delaunay, hexagonal and square tessellations with reproducible identifiers. Chooses a cell count, by default from a target number of observations per cell, or by scoring a ladder of counts against the spatial structure of the observations. Assigns features to cells and reports for each cell a count, a mean with its standard error and a pooled value pulled toward the mean of the observations in the 8 nearest cells. A design effect can correct the standard errors for autocorrelation within the cells. Projects lon/lat input to a projected coordinate reference system chosen for the extent of the data. Fits geographically weighted regression (its kernels, diagnostics and forward selection follow 'GWmodel'; Lu et al. (2014) doi:10.1080/10095020.2014.917453), Bayesian Gaussian process regression (via 'brms', using the Hilbert space approximation of Riutort-Mayol et al. (2023) doi:10.1007/s11222-022-10167-2) and random forests (via 'ranger', with the permutation importance of Strobl et al. (2007) doi:10.1186/1471-2105-8-25), each behind one S3 class with consistent predict, fitted, residuals and plot methods. Provides spatial cross-validation with random, block, buffered, leave-location-out and nearest-neighbour distance-matched folds (Milà et al. (2022) doi:10.1111/2041-210X.13851; Linnenbrink et al. (2024) doi:10.5194/gmd-17-5897-2024), forward variable selection, model comparison, prediction onto a regular surface, and the area of applicability of Meyer and Pebesma (2021) doi:10.1111/2041-210X.13650 to flag where a fitted model extrapolates beyond its training data.
Where to start
vignette("getting-started", package = "spatialkit") takes a layer of
points through the pipeline below, from a cell count to a cross-validated
model and a map that marks where its predictions apply. Each step of the
pipeline names the article that covers it.
Ten scripts, 01 to 10, each on one topic, are installed with the package;
00-run-all.R runs them in order. Each prints what it is doing and
says what to look for in a figure before drawing it:
dir <- system.file("scripts", package = "spatialkit")
list.files(dir)
source(file.path(dir, "03-folds.R")) # one topic
source(file.path(dir, "00-run-all.R")) # 01 to 10 in order
Set SPATIALKIT_TOUR_OUTPUT to a folder to write the figures there
instead of drawing them, and SPATIALKIT_TOUR_PAUSE to "no"
to skip the pause between figures that an interactive session gets.
Three help topics hold what many functions share: spatialkit-geometry (how input geometry and CRSs are read), spatialkit-conditions (every warning and error class the package raises, and how to catch one) and spatialkit-options (the two work limits).
The pipeline, in order
Steps 1 to 5 build cells from the spatial structure of the observations and summarise the observations onto them. Steps 6 to 10 fit a model to the points and check it: spatial cross-validation scores the model on blocks held away from its training data, and the area of applicability marks where its predictions leave the range of that data. Use the steps your question needs, in this order.
-
Prepare the data.
ensure_projected(),harmonize_crs(),coerce_to_points()andprep_model_data()put the observations in a projected CRS as points with complete values. Article:vignette("getting-started"). -
Measure spatial autocorrelation.
estimate_sac_range()estimates the distance over which observations stay correlated, andsac_nugget()returns the nugget of its variogram. The range sets a floor on the number of cells, whichselect_resolution(criterion = "reliability")andresolution_profile(range_floor = TRUE)apply. Sizing blocks from it is one way to set how far the held-out points sit from their training data, and suits a map that has to reach that far from the data. Article:vignette("spatial-cross-validation"). -
Choose a resolution.
resolution_profile()scores candidate cell counts andselect_resolution()reads the count off the profile; by default the count gives 4.5 observations per cell.determine_optimal_levels()reads a count off the elbow of the k-means WSS curve of the coordinates alone, and returnsNAwhen the curve has no elbow. Article:vignette("resolution"). -
Build the cells.
build_tessellation()draws Voronoi, hex, square or Delaunay cells with reproducible identifiers;get_voronoi_seeds()places the Voronoi seeds andclip_target_for()builds the polygon that hex and square cells are clipped to. Article:vignette("cells"). -
Assign and summarise.
assign_features_to_polygons()puts each observation in one cell, andsummarize_by_cell()reduces to one row per cell with a count, a standard error and a pooled value.cell_values_at()reads cell values at other locations, andkriging_adequacy()checks the cell mean against block kriging. Article:vignette("cells"). -
Make folds.
make_folds()builds spatial cross-validation folds: blocked, buffered, leave-location-out or nearest-neighbour distance-matched. A cross-validated error is the error at the distance the folds put between the held-out points and their training data: it reads low for predictions made farther from the data and high for predictions made closer, so the folds to use are the ones matched to where the model will predict.fold_separation()withprediction_pointscompares the two distances.cv_block_size_sweep()scores a range of block sizes. Article:vignette("spatial-cross-validation"). -
Fit a model.
fit_rf_model()(random forest),fit_gwr_model()(GWR, coefficients that vary across the map) andfit_bayesian_spatial_model()(Bayesian GP) return aspatial_fitwithpredict(),fitted(),residuals(),summary()andplot()methods, andcoef()for GWR and the Bayesian GP.new_spatial_fit()builds a backend of your own.model_metrics(),evaluate_insample(),compare_models()andresidual_morans_i()check a fit in sample. Article:vignette("models"). -
Cross-validate and compare.
cv_rf(),cv_gwr(),cv_bayes()andcv_spatial(), which takes any learner, score a model on held-out blocks;compare_models_cv()scores several backends on one set of folds. Articles:vignette("spatial-cross-validation")andvignette("models"). -
Choose predictors.
select_features_forward()chooses predictors inside the cross-validation, andgwr_model_selection()chooses GWR predictors by forward selection. Article:vignette("models"). -
Predict a surface and check where it applies.
predict_surface()predicts onto a regular grid, andarea_of_applicability()marks where the predictors leave the range the model was trained and scored on. Article:vignette("models"). -
Report.
ensure_stable_poly_id()gives the cells identifiers that do not depend on the order of the rows. Article:vignette("reporting").
vignette("spatialkit_nc_demo") runs the pipeline on one simulated
layer.
Two choices are the user's, and each has an argument with a default.
estimate is the cell value to report: the plain mean of a cell's
observations ("mean"), or the pooled value ("pooled", the
default), which is that mean pulled toward the mean of the observations
in the 8 nearest cells (nearest by the centroid of their observations).
resolution_profile() scores a
count for the value it is given, and summarize_by_cell()
reports the value it is given and warns when the count was chosen for
the other one. obs_per_cell is the size: how many observations a
cell is to hold on average, 4.5 by default. For pooled values the size
sets the count (select_resolution(criterion = "size")); for
plain means the lowest leave-one-out error can set it
(criterion = "loo"). select_resolution()'s default
criterion, "auto", takes the rule that goes with the profile's
estimate. The defaults that change results from 2.0.0, and the argument
that restores each, are listed under Breaking changes in
news(package = "spatialkit").
Defaults and their sources
Defaults that follow a reference, each cited on the help page of the function named:
-
fit_rf_model(include_coords = FALSE), andfitted()on a forest returning out-of-bag predictions: Meyer et al. (2019). Permutation importance over impurity importance in
fit_rf_model(): Strobl et al. (2007).The Gaussian-process basis count and boundary factor derived from the length-scale-to-domain ratio in
fit_bayesian_spatial_model(): Riutort-Mayol et al. (2023).The nearest-neighbour distance-matching folds of
make_folds(method = "nndm")and theirmin_train = 0.5: Milà et al. (2022).The area-of-applicability threshold as the outlier-removed maximum of the training dissimilarity, as the paper defines it (the reference implementation, CAST, uses the outlier fence itself, which is larger whenever a training value lies above it), with importance weights applied directly, without taking their square root, as CAST does: Meyer and Pebesma (2021).
Cliff and Ord moments for the residual Moran's I in
residual_morans_i(), withnull = "auto": Cliff and Ord (1981).
Defaults chosen without a citation:
The effective range of an exponential variogram as three times its range parameter, and the identifiability guard against ranges beyond half the maximum separation, in
estimate_sac_range().The 25 k-means++ restarts per candidate level in the sweep of
determine_optimal_levels(): k-means++ seeding follows Arthur and Vassilvitskii (2007) and a fixed budget follows Fränti and Sieranoja (2019); 25 is the package's choice, not a published figure.-
max_levels = 12and the unit-step ladder of candidate levels indetermine_optimal_levels(). The 3:1 fold-imbalance tolerance (
balance_tol = 3) inmake_folds(method = "block_kfold").The 1 percent area-distortion tolerance below which a CRS is taken as equal-area by
ensure_projected(purpose = "area")andsummarize_by_cell(area = TRUE).-
deff_max_n = 500,sample_n = 1500andtop_n = 3, the subsampling and shortlist sizes. -
coverage_levels = c(0.50, 0.80, 0.95)incv_bayes(). The condition-index cut of 30 in the collinearity checks of
fit_gwr_model(), a conventional rule of thumb.The 10 percent posterior-mass warning threshold on the GP length-scale in
fit_bayesian_spatial_model(), which is this package's own operationalisation of a check the reference recommends, not a figure from the paper.The small-sample rescaling applied with every data-derived design effect in
summarize_by_cell(): the package's own derivation from Kish's exchangeable-correlation model, given on that help page.The size of 4.5 observations per cell that
select_resolution(criterion = "size")andresolution_profile(obs_per_cell = "auto")take when none is given.The density kind of partition, kept from the best of 3 k-means++ starts, in
resolution_profile(),get_voronoi_seeds()andvoronoi_seeds_kmeans(): a convention, a kind that puts small cells where observations are dense and holds the counts per cell close once the cells outnumber the dense places, from a number of starts that keeps the cost of a fit to every row down.partition = "kmeans"gives plain k-means.The 8 nearest cells a pooled value is pulled toward in
summarize_by_cell(estimate = "pooled"): a convention, a count large enough to give a cell a stable target. It is not an argument.The 5 residuals expected beyond each end of the interval of
summarize_by_cell(obs_level = ), below which the warningspatialkit_few_residualsis raised: a convention for when the ends of an interval read from quantiles are unstable.The 30 values beyond one per cell below which
spatialkit_pool_few_dfis raised: a convention for when the spread inside the cells, which every own weight rests on, is estimated from little.The 2 percent by which the cells have to beat one mean for the whole layer, in leave-one-out error, for a response to be called
structuredbysummarize_by_cell(estimate = "pooled"): a convention, and the default oftolinselect_resolution(), which sets the same margin there.The two work limits,
getOption("spatialkit.exact_pairs_max", 2e9)pairs for a search made without the FNN package andgetOption("spatialkit.fit_work_max", 1e10)point-to-centre comparisons for the fits of a ladder thatobs_per_cellsets: conventions that keep a search or a fit whose cost grows with the square of the rows or of the cells from starting. Above one,resolution_profile()andcell_values_at()stop with an error, andsummarize_by_cell()returnsNApooled columns with a warning (see spatialkit-options).
Author(s)
Maintainer: Justin Chase jchase.msu@gmail.com [copyright holder]
Authors:
Justin Chase jchase.msu@gmail.com [copyright holder]
See Also
Entry points by task:
build_tessellation() (build cells),
summarize_by_cell() (summarise observations onto them),
make_folds() (split the data into cross-validation folds),
compare_models_cv() (score several models on the same folds),
area_of_applicability() (find where predictions leave the
range of the training data).
Subset a layer that carries a row record
Description
prep_model_data() and
assign_features_to_polygons() return a layer with an
attribute recording what happened to its rows ("dropped" for the
first; "ties" and "unassigned" for the second). Those
records describe the rows the layer was
built with, and [ on an sf object copies attributes through
unchanged, which would leave a subset reporting its parent's numbers for a
different set of rows. Subsetting therefore returns a plain layer with the
record removed, and so do the dplyr verbs that select or reorder
rows (filter(), slice(), arrange(),
distinct()); read the record from the layer the function returned,
before subsetting it. Binding such layers (rbind(),
dplyr::bind_rows()) likewise returns a plain sf layer.
Usage
## S3 method for class 'spatialkit_rows'
x[...]
Arguments
x |
A layer returned by |
... |
Passed to the underlying |
Details
Each record carries n_rows, the number of rows it was made for.
sf::st_drop_geometry() keeps the rows, and with them the record: it
returns a data frame of class c("spatialkit_rows", "data.frame").
Binding such data frames with
rbind() or dplyr::bind_rows() keeps the first one's record
and class, so the record then describes only the first input's rows: its
n_rows no longer equals nrow() of the result. The
package's own readers ignore a record whose n_rows does not match;
when reading attr(x, "dropped"), attr(x, "ties") or
attr(x, "unassigned") yourself from a layer that has been through
such steps, check it the same way.
Value
The subset, without the row records and without this class. A
subset that is not a data frame (a single column taken with
drop = TRUE) is returned unchanged.
See Also
prep_model_data() and
assign_features_to_polygons(), the two functions that
attach the records this method removes.
Other data preparation:
coerce_to_points(),
ensure_projected(),
harmonize_crs(),
prep_model_data(),
spatialkit-geometry
Examples
library(sf)
dat <- st_as_sf(
data.frame(x = 1:5, y = 5:1,
resp = c(1, 2, NA, 4, 5), pred = c(1, 2, 3, 4, Inf)),
coords = c("x", "y"), crs = 32632
)
# prep_model_data() warns that it dropped 2 of the 5 rows.
clean <- suppressWarnings(prep_model_data(dat, "resp", "pred"))
attr(clean, "dropped")$n # 2
attr(clean[1:2, ], "dropped") # NULL: the record does not follow
Mark where a model's predictions apply
Description
Computes the dissimilarity index (DI) of Meyer and Pebesma (2021) for a set of prediction locations and flags those that fall inside the model's area of applicability (AOA), the region of predictor space where the model's cross-validated performance estimate can be expected to hold.
Usage
area_of_applicability(
newdata,
model = NULL,
train_sf = NULL,
predictor_vars = NULL,
weights = "auto",
folds = NULL,
threshold = NULL,
normalizer_max_n = 5000L,
seed = 123L,
chunk_size = NULL,
use_fnn = requireNamespace("FNN", quietly = TRUE),
coords = c("auto", "yes", "no"),
categorical = c("refuse", "indicator", "drop")
)
Arguments
newdata |
Prediction locations: an |
model |
A fitted |
train_sf |
Training data, if not taken from |
predictor_vars |
Predictor names, if not taken from |
weights |
|
folds |
Cross-validation folds: a |
threshold |
Optional numeric override for the DI threshold of the predictor index. The location index, when there is one, always takes its threshold from the rule. |
normalizer_max_n |
Subsample the training data to this many points when computing the mean pairwise distance, which is quadratic. Default 5000. The subsample is drawn from the training rows in a fixed order (by the predictors, and for the location index by the coordinates), so it does not depend on the row order of the training data. |
seed |
Seed for that subsample. Default 123. |
chunk_size |
Query rows per distance block on the dense path. Default
|
use_fnn |
Use FNN for nearest-neighbour search when available. Exposed so the dense fallback can be tested. The two paths return the same distances: the dense one searches with a fast formula and then recomputes the nearest distance exactly, so an exact copy of a training row is at distance 0 on both. |
coords |
Whether location is measured: |
categorical |
What to do with factor and character predictors:
|
Value
An object of class aoa: a list with
-
aoa:newdatawith a numericDIcolumn and a logicalAOAcolumn added, and between them a numericDI_locationcolumn when location has an index of its own. For a forest fitted withinclude_coords = TRUE, unlesscoords = "no", it is the object the computation ran on:newdataafter pointizing, CRS reconciliation and the addition of the"..x"and"..y"columns. In every other case it isnewdataas passed, also when location has an index of its own. A row whose predictors are not all finite getsNAinDI, and a row outside the training range of a predictor indropped_vars, or on a level no training row has, getsDI = InfandAOA = FALSE(see Limitations).AOAisDI <= threshold, and with a location index alsoDI_location <= location$threshold: a row outside on either index isFALSE, and a row with one index missing and the other inside isNA. -
threshold: the DI cut-off used. -
train_DI: the training points' own DI values. -
normalizer: the mean pairwise training distance. -
weights: the weight vector actually applied, named bypredictor_vars. -
predictor_vars: the predictors used, including"..x"/"..y"when a forest uses the coordinates and excludingdropped_varsand, undercategorical = "drop",categorical_vars. -
dropped_vars: predictors dropped for negligible variance. -
scaling: a list withcenterandscale, each named bypredictor_vars: the training means and standard deviations the index is computed in, so a location's DI can be traced to the predictor that put it outside. A predictor coded as indicators has one entry per level, named"<predictor>=<level>". -
n_outliers: the number of training DI values above theQ3 + 1.5 * IQRfence, which the default threshold rule sets aside (the "outlier-removed" in its name); computed whether or notthresholdwas supplied. -
n_duplicates: withfolds = NULL, the number of training rows that repeat an earlier row's predictor values exactly and so share its reference distance;NAwhen folds were supplied (see Training rows with identical predictor values). -
location:NULL, or for a location index a list withthreshold,train_DI,normalizer(the mean distance between training points, in CRS units, sothreshold * normalizeris the cut-off as a distance),n_duplicates(training rows at an earlier row's location;NAwhen folds were supplied) andn_outside(prediction rows beyond the location threshold). -
categorical_vars: the factor and character predictors found, coded or left out asparams$categoricalsays. -
n_train,n_new,n_inside,n_outside,n_na: row counts.n_traincounts the training rows that survived the finite-value filter;n_newis every row ofnewdata, son_new = n_inside + n_outside + n_na, withn_nathe rows whoseAOAisNA.n_outside_predictorscounts the rows beyond the predictor threshold, which isn_outsideunless there is a location index. -
paramsrecords the call:folds_supplied,n_folds,folds_method,threshold_supplied,normalizer_max_n,normalizer_n_used,normalizer_subsampled,weights_supplied(the caller passed a vector),weights_source("model importance","supplied"or"equal"),weights_note(the kind of importance, or why the weights are equal),coords("location index";"location index and predictors"for a forest fitted withinclude_coords = TRUE, whose coordinates are also among the predictors; or"none"),categoricalandseed.folds_methodis themethodof amake_folds()result ("block_kfold","random_kfold", ...),"labels"for a vector of fold labels,"splits"for a bare list of train/test splits, andNAwhen no folds were supplied. It is printed with the object, because the threshold's meaning depends on it: the cross-validated DI that sets it comes from the same kind of hold-out as the CV error it should be quoted beside, so an AOA built onrandom_kfoldfolds is logged as a caution and does not belong next to a blockedcv_*()result.
What the index is for
A fitted model returns a number for any location you hand it, including locations whose predictor values look nothing like anything it was trained on. Those predictions are extrapolations, and a cross-validation score says nothing about them, because the held-out folds were drawn from the same predictor distribution as the training data. The AOA marks where the score applies.
How it is computed
Predictors are centred and scaled using the training data's own means and
standard deviations, then weighted by variable importance when the model
carries one (see Weights). For a
prediction point p, the DI is the distance to its nearest training
point in that space, divided by the mean pairwise distance among training
points. The same quantity is computed for the training data itself, using
each point's nearest neighbour among the training rows of the fold
that holds it out. That means everything outside its own fold for random
and block folds, and the smaller training set that buffered and NNDM folds
leave (see "The fold scheme"); without
folds it is the nearest training row with different predictor values. The
threshold is then the largest
training DI that is not an upper outlier, i.e. not above the fence
Q3 + 1.5 * IQR of the training DI, with the quartiles of
stats::quantile()'s default type 7. Prediction points at or below
that threshold are inside the AOA.
That is the paper's "outlier-removed maximum". CAST, the reference
implementation, computes the same fence with the same quartiles but uses the
fence itself as the threshold, capped at the largest training DI. The two
agree whenever no training DI lies above the fence (n_outliers is 0);
otherwise CAST's threshold is the larger, and so is its AOA. (Earlier
CAST releases used grDevices::boxplot.stats(), which gives the
rule used here but with Tukey's hinges as the quartiles, so they can also
differ when the number of training points is even.) To apply the current
CAST rule to the same training DI, pass
threshold = min(quantile(res$train_DI, 0.75) + 1.5 * IQR(res$train_DI),
max(res$train_DI)) for an earlier result res.
The DI is invariant to the overall scale of weights: the numerator
and the normaliser carry the same factor. Importance values can be passed
as-is.
Training rows with identical predictor values
Repeat visits to a site with static covariates, or covariates read off a raster coarser than the sampling, give training rows that are exact copies of each other in predictor space. A copy is the same point of that space, not a neighbour. Counted as a neighbour it gives a training DI of 0, and once about three quarters of the rows have one the threshold is 0 and only exact copies of a training row count as inside.
With folds = NULL each training row's reference is therefore its
nearest row with different values: the search runs on the distinct
rows and every row takes its point's distance. n_duplicates counts
the rows that repeat an earlier one, and a layer with none is unaffected.
The normaliser stays the mean pairwise distance over
all the training rows, so a prediction point's DI is the same with and
without folds.
With folds supplied the definition is applied as it stands: a
held-out row whose copy is on the training side of its fold has a DI of 0,
because that hold-out did have an identical row to learn from. If the
threshold comes out 0 that way, a warning of class
spatialkit_aoa_zero_threshold gives the count, so a script or a
cross-validation loop can catch it with
tryCatch(..., spatialkit_aoa_zero_threshold = ). Folds that keep
the copies together (make_folds(method = "leave_location_out",
group_var = ...)) give the threshold its meaning back. The same applies
to the location index when training rows share a location.
The fold scheme
With folds = NULL the training reference is each point's nearest
neighbour anywhere in the training data, which for clustered data is very
close, giving a small threshold and a conservative AOA. Passing the folds
you validated with makes the reference distances larger and the AOA
wider. The AOA is defined relative to a performance estimate, and a
spatially blocked estimate is a claim about predicting further away. Pass the same make_folds() result you passed
to cv_spatial. Buffered and NNDM folds use the training set
they left available, not everything outside the fold.
Weights
Meyer and Pebesma weight the predictors by the model's variable
importance, and with the default weights = "auto" so does this
function whenever model carries an importance that means
something: pmax(model$info$importance, 0), which a forest from
fit_rf_model has. Equal weights are used, with a logged
note, when it does not: no model; a model with no importance
(importance = "none", a GWR, a Bayesian fit); an importance that is
not finite (NaN for a forest with no out-of-bag rows); one that
names fewer predictors than are in use; no positive value; or a forest
with no out-of-bag skill (oob_r_squared missing or at most 0),
whose positive importances are noise. print() says which it was.
weights = NULL asks for equal weights whatever the model carries.
Importance weights make the index react to shifts along the predictors
the model uses and much less to shifts along those it does not, which
leave its error unchanged. The cost is on the weak predictors. A weight
multiplies the scaled column, so its square enters the distance, and a
weak but real predictor is down-weighted by the square of its relative
importance. A shift along such a predictor can then go unseen although
it raises the error. weights = sqrt(pmax(importance, 0)) sits
between equal weights and importance weights: a weak predictor loses less
of its weight.
Limitations
Categorical predictors (factor or character columns) have no distance of
their own, and by default they are refused and never silently
dummy-coded. categorical = "indicator" codes each level that
occurs in the training rows as a 0/1 column. The columns of one predictor
share one scale, sqrt(1 - sum(p^2)) with p the levels'
shares of the training rows, so two rows on different levels are the same
distance apart whichever levels they are, two on the same level are 0
apart, and the predictor adds as much to the mean squared distance between
training rows as one standardised numeric predictor. That scaling is a
choice, so it is not the default. A prediction row
on a level no training row has gets DI = Inf, is outside the AOA,
and a warning gives the count. categorical = "drop" leaves the
categorical predictors out and computes the index on the others; a level
the training data never has then goes unseen.
Predictors whose training values do not vary beyond their rounding are
dropped from the distance. A predictor is kept when
sd > sqrt(.Machine$double.eps) * max(abs(x)), and otherwise when its
standard deviation is more than 3 units in the last place of
max(abs(x)). The same variable in metres and in gigametres is
treated identically, and a predictor at an offset (a timestamp in seconds)
is kept as it is at 0. A prediction point taking a value there outside the
training range by more than 3 units in the last place of
max(abs(x)) (of 1 for a column of zeros) is extrapolation along a
direction
the training data never varied in: its scaled distance along it is
infinite, so it gets DI = Inf, is outside the AOA, and a warning
gives the count. A point missing that value is judged on the other
predictors. With equal weights every predictor counts the same, which
overstates dissimilarity along directions the model barely uses; see
Weights.
Models whose predictions depend on location
For three kinds of model the prediction is a function of where the point
is, not only of its covariates, so the index has to measure location too.
Without that a prediction point far outside the training extent but with
ordinary covariate values reads as inside the area of
applicability, which is exactly the extrapolation this index exists to
catch. coords = "auto" (the default) measures location for all
three; coords = "no" turns it off, with a logged caution;
coords = "yes" measures it for any model, or for none.
A GWR (gwr_fit) has coefficients that vary over the map, a
Bayesian GP fit (bayesian_fit) has a Gaussian-process term in the
coordinates, and a forest fitted with include_coords = TRUE splits
on the coordinates. For these, and under coords = "yes", location
gets an index of its own, built like the predictor index but in the
coordinates:
DI_location is the
distance to the nearest training point over the mean distance between
training points; the training points' own values use the same folds; and
the threshold is the same outlier-removed maximum. A prediction point is
inside the AOA only if it is inside on both indices, and both DI columns
are returned so the cause can be read off. Location is kept apart from
the covariates because, as two more equally weighted columns, it would be
diluted as covariates are added, and points well beyond the training
extent would still read as inside.
Inside the extent the index marks an unsampled gap only where the gap is
wider than the distance its threshold allows, and that distance depends
on folds. With folds = NULL it is the spacing of the
training points (the outlier-removed largest nearest-neighbour distance).
With blocked folds it is the largest distance from a held-out point to
the nearest row its fold trained on, outliers removed, which grows with
the block size; a gap narrower than about twice that distance has no
cell beyond it and reads as inside. This follows from the definition:
the cross-validated error the index is paired with was earned on
hold-outs that far from their training rows. With blocked folds the
location index therefore says nothing about a gap narrower than about
twice the cut-off; location$threshold * location$normalizer is the
cut-off in CRS units, and print() shows it.
A forest splits on the coordinates like on any other column, so for a
forest they also stay in the predictor index as "..x" and
"..y", centred, scaled and weighted with the rest. Under
weights = "auto" that weight is the forest's importance, which is
small for a forest that barely splits on its coordinates, so points
beyond the extent can read as inside on the predictor index. The
location index counts location whatever weight the coordinates get.
Geometry is needed on both sides, so train_sf and
newdata must both be sf objects; a data.frame is refused
rather than quietly measured without location. Non-POINT
newdata (grid polygons, say) is reduced to representative points
first, as coerce_to_points would. If exactly one side carries
a CRS the other is brought into it: reprojected when its coordinates look
like longitude/latitude, stamped otherwise, with a warning either way; a
CRS in longitude and latitude is not stamped on coordinates outside
longitude -180 to 360 and latitude -90 to 90, which is refused (see
spatialkit-geometry). Degrees fed into an index in metres would
silently understate the distances. The location index measures distances in
the coordinates and refuses training data in a geographic CRS. Both
layers are read in x and y for the location: a layer whose geometries
mix XY with XYZ or XYM (as rbind() of an XY and an XYZ layer gives), or carry M (XYM or XYZM), is read without its Z
and M. Only one change reaches the result: for a forest fitted with
include_coords = TRUE, newdata that mixes dimensions and is
reprojected into the training CRS comes back in XY, with a warning of
class "spatialkit_zm_dropped", as ensure_projected()
returns such a layer; the points that non-POINT newdata is
reduced to are in XY when they would mix dimensions or carry M.
A row without a location (an empty geometry, or a coordinate that is not
finite or lies beyond 1e150) is read as one both as given and after a
move into the other layer's CRS, which can bring a coordinate of 1e200
back finite. Such a row of newdata gets NA in
DI_location, and for a forest fitted with
include_coords = TRUE in "..x" and "..y" and so in
DI; such a training row is left out of the reference distances,
with a log line. A row of newdata without a location as given that
is reprojected into the training CRS comes back in aoa with an
empty geometry.
References
Meyer, H. and Pebesma, E. (2021). Predicting into unknown space? Estimating the area of applicability of spatial prediction models. Methods in Ecology and Evolution 12(9), 1620–1633. doi:10.1111/2041-210X.13650
See Also
predict_surface() to build the grid,
make_folds() for the fold scheme, and
plot.aoa() to draw the dissimilarity distribution.
Other prediction:
plot.aoa(),
predict_surface(),
print.aoa()
Examples
suppressPackageStartupMessages(library(sf))
set.seed(1)
n <- 120
train <- st_as_sf(
data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
a = rnorm(n), b = rnorm(n)),
coords = c("x", "y"), crs = 32632
)
train$z <- 2 * train$a - train$b + rnorm(n, 0, 0.3)
# Prediction points, some of them well outside the training predictor range
newpts <- st_as_sf(
data.frame(x = 5e5 + runif(50, 0, 1000), y = 5e6 + runif(50, 0, 1000),
a = c(rnorm(40), rnorm(10, 8)), b = rnorm(50)),
coords = c("x", "y"), crs = 32632
)
res <- area_of_applicability(newpts, train_sf = train,
predictor_vars = c("a", "b"))
res
table(res$aoa$AOA)
Assign features to cells and attach a cell ID
Description
Gives every feature the ID of the polygon it falls in and returns the
features, one row each, with that ID column added. Features in several
polygons are settled by tie_break, and features in none are dropped or
kept by keep_unassigned.
Usage
assign_features_to_polygons(
features_sf,
polygons_sf,
polygon_id_col = "poly_id",
keep_unassigned = FALSE,
predicate = sf::st_intersects,
largest = TRUE,
tie_break = c("smallest_area", "first"),
quiet = FALSE
)
Arguments
features_sf |
An sf object containing features to assign. A layer whose geometries mix dimensions or carry M (XYM or XYZM) is joined in x and y, and the rows returned keep their Z and M (see "Z and M coordinates"). |
polygons_sf |
An sf or sfc polygonal layer. Polygons whose geometries mix dimensions or carry M (XYM or XYZM) are read in x and y. |
polygon_id_col |
Name of the polygon identifier column: the column of
|
keep_unassigned |
Logical; retain features that fall inside no
polygon, carrying |
predicate |
Binary spatial predicate function. Default sf::st_intersects.
Not used when |
largest |
Logical; when |
tie_break |
Strategy for resolving features that match multiple
polygons (with |
quiet |
Logical; suppress this function's |
Details
This is the step before summarize_by_cell(), which aggregates over the
IDs. Unlike sf::st_join(), it settles a feature that matches several
polygons by an explicit tie_break rule instead of duplicating the row,
so the assigned layer keeps one row per input feature and each feature is
counted in one cell. How the input layers are read in general (CRS,
dimensions, rows without a location) is in spatialkit-geometry.
Value
An sf object with polygon_id_col attached, one row per input
feature (fewer if keep_unassigned = FALSE dropped unmatched ones, and
features tie_break gives no polygon), in
the CRS features_sf arrived in. A column of features_sf already
called polygon_id_col is dropped before the spatial join (with a
warning), so re-assigning an already-assigned layer replaces the old IDs
and does not fail. Every other column is kept, including one named like
the polygons' own ID column when that is read from a fallback such as
"id" (a site id joined to cells keyed by id). If no feature
falls inside any polygon
the result is empty (or all-NA with keep_unassigned = TRUE) and a
warning is raised, since the usual cause is two layers in different
places (a CRS that could only be stamped, not reprojected). A layer
without a CRS is brought into the other layer's CRS as
harmonize_crs() does; beside a layer in longitude and latitude, one
with an x outside -180 to 360 or a y beyond 90 north or south cannot be
in degrees, and the call stops with an error that names features_sf
or polygons_sf and gives its box.
Ties and unassigned features
Features that fall inside no polygon are counted on the attribute
"unassigned": a list with n, which (their row positions in
features_sf) and n_rows. With keep_unassigned = FALSE they are not
in the result, and a warning of class "spatialkit_unassigned" gives
their number (tryCatch(spatialkit_unassigned = ) catches it without
matching the message; the condition carries n and total). The usual
causes are a polygon layer that stops short of the data (a coastline
drawn at another scale, a tessellation of seeds built without a
boundary or cover; see build_tessellation()) and points outside
the study area. A feature with empty geometry, or with a coordinate
that is not finite or lies beyond 1e150, or in a geographic CRS a
vertex at a latitude beyond 90 degrees (read as given, before any
move into the polygons' CRS), has no location to assign: it matches no
polygon, and the warning says how many of them there are. With
keep_unassigned = TRUE they are kept with an
NA ID and no warning is raised, unless every feature is unassigned.
A polygon of polygons_sf with a coordinate that is not finite or lies
beyond 1e150 (read as given) has no location either: it takes no
feature, and the features inside the rest of its ring are unassigned.
The attribute "ties" records how many features matched more than one
polygon (with largest, overlapped several by exactly the same area)
and had the tie_break rule decide for them: a list with n,
which (their row positions in features_sf), rule, n_rows
(the number of rows returned, which the record was made for) and, when
the rule gave some of them no polygon (see tie_break), unresolved,
the row positions of those among which. A large
n means the polygon layer overlaps, and per-cell counts built from the
result depend on the rule. The record describes the rows this call
returned and does not survive subsetting: joined[i, ], like
dplyr::filter(), slice() or arrange() of it, is a plain layer
with no "ties" attribute, so nothing reports the parent's count
for a different set of rows. sf::st_drop_geometry() keeps the record,
since the rows are the same; see [.spatialkit_rows for
what binding such data frames does. The "unassigned" record is
stamped and removed the same way.
Cells from a resolution profile
When polygons_sf carries attr(, "count_rule"), the record of how
its cell count was set (cells from build_tessellation() on seeds
placed from a select_resolution() result or from a profile built with
an estimate), the result carries the same record.
summarize_by_cell() reads it and checks that the rows and cells it is
given are the ones the count was scored on. It is a plain attribute: a
row subset keeps it and dplyr::mutate(), dplyr::select() and
dplyr::arrange() drop it, which is why the summary also looks for it
on its cells_sf. The profile scores a feature that is not a point at
one point of it (coerce_to_points(, "auto")), in the cell of the
nearest centre; this function gives a polygon feature to the cell it
overlaps most. A feature that straddles a cell boundary can therefore
be assigned to another cell than the one it was scored in, and the
summary does not compare the two for such a layer. To assign the
features as they were scored, assign their points:
assign_features_to_polygons(coerce_to_points(features_sf, "auto"), polygons_sf).
When that record says the cells are the ones the profile scored
(scored_cells is TRUE: the cells build_tessellation() builds on a
selection's seeds, or on the seeds a seeding function returns for one)
and holds the centres it scored (count_rule$scored$centres), a point
on the edge between two or more of those cells is given the cell
resolution_profile() scored it in: that of its nearest centre,
measured in the CRS the record names, and of centres the same distance
away the lower-numbered one (a distance counts as the same as the least
when its square is no more than the square of the least distance
lengthened by a margin, plus one part in ten million of the least
squared distance; the margin is one part in 1e10 of the largest
coordinate of the centres, at most a millionth of the diagonal of their
bounding box and at least four times the spacing of doubles at that
coordinate). Such points occur on
gridded locations (raster cell centres, a regular sampling grid), where
a row can lie the same distance from two centres and the polygons hold
it in either cell or in both. The rows each cell holds are then the rows
its count was scored on, and summarize_by_cell()'s check of them reads
"match". A point counts as on the edge when it lies within a margin of
both cells: one part in 1e10 of the largest coordinate of the cells,
0.44 mm at a UTM northing of 4,400 km, at most a millionth of the
diagonal of their bounding box and at least four times the spacing of
doubles at that coordinate. For a point that two centres tie
for while the cell holding it is that of the strictly nearer one, the
margin also takes in the point's distance from the boundary between the
two, measured in the CRS the record names: midway between centres far
apart the tie reaches about 1.25e-8 of their distance from the boundary,
which can exceed that margin.
build_tessellation() draws such cells in the CRS the record names,
around the centres as the record holds them, whatever CRS the seeds came
back in (unless its crs names another projected CRS), so their corners
carry only the rounding of that computation, far less than the margin.
Cells it returns in a
geographic crs are moved back into the record's CRS for the join (see
"Joins in longitude and latitude"). In a UTM zone the round trip through degrees moves a corner by
about 2e-9 m; in the equal-area CRS the profile works in for a layer
wider than a zone it can move one by more than the margin (how far
depends on the PROJ build), so a point on such an edge can keep the
polygon that holds it, and the summary's check then reads "differ". A
point farther from its nearest centre's cell keeps the polygon that
holds it, and so do features that are not points, points without a CRS
beside a record with one or with a CRS beside a record without one, and
a join in longitude and latitude (polygons
in degrees beside a record in degrees). A centre's cell
is the one cell that holds it and no other centre; a centre outside a
boundary that clipped its cell away from it has the cell, among those
that hold no centre, whose inside is nearest it. Cells built from other
seeds leave most centres without a cell, and their points to the
polygons. Polygons without the record, such as polygons
the caller brings, and cells whose record says scored_cells is
FALSE or NA (other cells built from the count, such as a lattice
sized by it) are placed by the polygons alone.
Joins in longitude and latitude
The join runs in the CRS of polygons_sf whenever that CRS is projected,
so cell edges are the straight lines the cells were drawn with and overlap
areas are planar. Cells in lon/lat whose record of their count says they
are the cells a profile scored, and holds its centres in a projected CRS
(the Voronoi cells build_tessellation() builds on the centres a profile
scored and returns in a geographic crs; see "Cells from a resolution
profile"), were drawn in the
record's CRS, and the join runs there. A copy of features_sf is
transformed for it, and the features come back with the coordinates they
arrived with. Otherwise (other polygons in lon/lat, such as a hex or
square lattice sized by a selection or the cells of centres refitted to
every point, or polygons without a CRS) the join runs in the CRS of
features_sf. In longitude and latitude, with s2 on (sf::sf_use_s2(),
sf's default), sf joins on the sphere with s2, which refuses a polygon
that is not valid there, such as one with two corners it reads as one
point or with edges that cross; cells returned in lon/lat can hold two
corners that differ only by rounding and fall on one point in degrees
(see "Polygons in degrees" in spatialkit-geometry). A join by
predicate then
stops with an error of class "spatialkit_cells_degenerate" that gives
the rows of the polygons s2 refuses (the condition carries them as
rows), names the cause and says to transform polygons_sf to a
projected CRS, where the join runs. The largest-overlap join repairs such
polygons first (see largest), and stops with that error when s2 still
refuses a polygon it repaired, such as one whose hole crosses its outer
ring.
A polygon of features_sf that s2 refuses stops the join by predicate
with an error of class "spatialkit_features_degenerate", with the same
fields, that gives its rows, quotes s2's reason and says to transform
features_sf to a projected CRS, where the join runs; so does one s2
refuses even after the repair of the largest-overlap join. When that
repair makes s2 accept the polygons of both layers and s2 then refuses a
piece of an overlap of the two layers (a figure eight, one vertex listed
twice, is repaired into two parts that touch at a point, and the piece can
hold that point twice), the join stops with the error for the layer whose
polygons s2 refused as they arrived; with s2 on (sf's default), the join
by predicate meets those polygons too. When s2 refused no polygon of
either layer as it arrived, the error says to pass largest = FALSE or to
project both layers. Whether s2 refuses such a piece can differ between
platforms and s2 versions. Where s2 accepts the piece, the join runs and
gives each feature the polygon of its largest overlap.
In longitude and latitude the largest-overlap join
runs on s2, and the areas tie_break compares are measured on the sphere
with s2, whatever sf::sf_use_s2() says, as the package's other areas in
degrees are; the join by predicate runs with the engine the session
names. With s2 off that engine is GEOS, which reads these polygons in
degrees, so the largest-overlap join's error for a polygon s2 refuses also
offers largest = FALSE.
Z and M coordinates
sf reads a layer in the dimension of its first geometry, so s2, GEOS and
sf::st_transform() read a layer that mixes XY and XYZ (or XYM)
geometries wrongly; rbind() of an XY and an XYZ layer gives one. When
either layer mixes dimensions, the join runs on a copy of it without Z and
M, and the rows come back with the geometry they arrived with, Z and M
included. The same holds, with no warning, for a layer whose geometries
carry M (XYM or XYZM), which GEOS does not read: the join is defined in
x and y. Features without a CRS that mix dimensions and are moved from
lon/lat into the polygons' CRS come back moved and in XY, with a warning
of class "spatialkit_zm_dropped", unless their only geometries of
another dimension than the first are empty and not points. Features
without a CRS in one dimension that carry M come back with their own
geometry: with the CRS they were given, or moved from lon/lat with
sf::st_transform(), which keeps their M.
Coordinates far from the origin
Layers so far from the origin of their coordinates that doubles there are
spaced more than a millionth of the extent of the two layers apart (0.125
at 1e15, beside a layer a few kilometres across) are joined with their
edges and points held to that spacing, so a point that lies within it of
an edge near the origin can fall in the polygon beside it. The join runs,
and a warning of class "spatialkit_xy_imprecise" gives the spacing and
the extent (the condition carries them as spacing and extent).
See Also
build_tessellation() to build the polygon layer;
summarize_by_cell() for the aggregation step that consumes the result.
Other assign and summarise:
cell_values_at(),
kriging_adequacy(),
summarize_by_cell()
Examples
library(sf)
set.seed(1)
pts <- st_as_sf(
data.frame(x = 5e5 + runif(20, 0, 100), y = 5e6 + runif(20, 0, 100),
val = rnorm(20)),
coords = c("x", "y"), crs = 32632
)
bnd <- st_sf(geometry = st_sfc(st_polygon(list(rbind(
c(5e5, 5e6), c(5e5 + 100, 5e6), c(5e5 + 100, 5e6 + 100),
c(5e5, 5e6 + 100), c(5e5, 5e6)
))), crs = 32632))
grid <- create_grid_polygons(bnd, target_cells = 9, type = "square")
assigned <- assign_features_to_polygons(pts, grid)
table(assigned$poly_id)
Build Voronoi, triangle, hex or square cells from points
Description
Builds the cells the rest of the pipeline works on. It wraps the four tessellation methods behind one interface that handles
CRS projection, clipping and stable cell IDs the same way, and returns the
cells together with the point-to-cell index. The return shape does not
change with method, so comparing "voronoi" with "hex" takes one
argument. create_voronoi_polygons() and create_grid_polygons() are its
parts; assign_features_to_polygons() and summarize_by_cell() take its
cells next.
Usage
build_tessellation(
points_sf,
boundary = NULL,
method = c("voronoi", "triangles", "hex", "square"),
approx_n_cells = NULL,
cellsize = NULL,
expand = 0,
clip = TRUE,
keep_duplicates = FALSE,
crs = NULL,
quiet = FALSE,
cover = NULL
)
Arguments
points_sf |
An sf object with POINT/MULTIPOINT geometry. Points that mix XY and XYZ (or XYM), or that carry M, are read in x and y, since sf reads a layer in the dimension of its first geometry and GEOS refuses M. |
boundary |
Polygonal sf/sfc study area. Required for
|
method |
One of |
approx_n_cells |
Approximate number of cells. Read by |
cellsize |
Numeric cell size, in the units of the working CRS. Read by
|
expand |
Buffer distance, in the working CRS's units, by which the
Voronoi boundary is grown before the diagram is built. Applied by
|
clip |
Logical; clip the cells to the boundary. Default |
keep_duplicates |
Logical. With |
crs |
Optional target CRS: anything |
quiet |
Logical; suppress this function's progress |
cover |
Optional sf or sfc layer the cells have to hold: the
observations (points), or a polygon. Read by |
Value
A list with components:
cellsAn sf polygon layer, one row per cell. It always carries a
cell_idcolumn; the"hex"and"square"methods also carrypoly_id, which holds the same values and follows the numbering ofcreate_grid_polygons(), not that ofcreate_grid_polygons_cached(). Passpolygon_id_col = "cell_id"toassign_features_to_polygons()andid_col = "cell_id"tosummarize_by_cell()andcell_values_at()to keep that name through the pipeline. With the defaults, Voronoi and triangle cells, which carry onlycell_id, have their IDs read fromcell_idand returned aspoly_id.indexInteger vector of
cell_idvalues, one per row ofpoints_sf, andNAfor a point that falls inside no cell, that is, one outside the study area. For seeds it holds the cell each seed generates. "Points on edges and outside every cell" gives the rules for points on an edge, points snapped to a cell, seeds and the warnings.boundaryThe boundary used (possibly derived and/or reprojected, and for
"voronoi"grown byexpand).methodThe method actually used.
paramsThe parameters the tessellation was built with, plus
snapped, the record of that nearest-cell repair: a list withn,which(row positions inpoints_sf) anddistance(how far outside every cell each sat, in CRS units, and in metres for cells in degrees; a point within the margin of an edge is in that cell and is not listed), which for seeds lists only those whoseindexentry is the cell they were snapped to;n_outside, the number of points ofpoints_sfthat fall in no cell (theNAs ofindex); andcover_outside, the number ofcoverpoints in no cell when a pointcoverwas checked against the cells (NULLotherwise). For"voronoi"alsoboundary_source, where the boundary came from:"boundary","cover","seeds' cover"or"points", and, whenpoints_sfis a layer of seeds that records the kind of partition that placed it (seeget_voronoi_seeds()),partition: that record, a list withkind,init,density_poweranddensity_kand, for seeds a seeding function placed itself,iter,iter_maxandconverged. The cells are the Voronoi cells of the seeds whatever kind placed them. For"hex"and"square"alsocells_occupiedandcells_empty, the number of cells that hold at least one point and that hold none.count_rule, the record of how the count was set, is present on two paths, and the cells then carry it too asattr(cells, "count_rule"). For"voronoi", whenpoints_sfcarries one (attr(points_sf, "count_rule"): the seeds of aselect_resolution()result, or seedsget_voronoi_seeds()orvoronoi_seeds_kmeans()placed from one): the record as the seeds carry it, whosescored_cellssays whether these are the cells the profile scored, andFALSEwhen the seeds are fewer or more than its count. For"hex"and"square", whenapprox_n_cellsis a selection that carries a record, or a profile built with anestimate, and nocellsizeis given: that record withscored_cellsFALSE, since a lattice at that count is not the partition the profile scored.assign_features_to_polygons()copies the record to the rows it assigns, andsummarize_by_cell()checks its result against it.
Choosing a method
"voronoi" gives one cell per point, so the resolution follows sampling
density. Use it when the observations themselves define the cells, or on
seeds placed with get_voronoi_seeds() to set the count. "hex" and
"square" give equal-area cells on a fixed grid, so you set the cell size
and the data do not; hexagons avoid the axis-aligned artefacts of squares
and put all six neighbours of a cell at the same distance. "triangles"
returns the Delaunay triangulation, for interpolation and adjacency work;
it is not meant as an aggregation unit.
"voronoi" and "triangles" are built on the points' vertices: a
MULTIPOINT feature with several vertices gets one cell (or triangle
corner) per vertex, and its index entry is the smallest cell_id among
the cells it touches (see create_voronoi_polygons()). Points on one
circle, such as the four corners of each square of a lattice, have more
than one Delaunay triangulation. They are triangulated in coordinates
centred on the middle of their bounding box, divided by its diagonal and
rounded to multiples of 2^-30 of it, so they are split the same way in
any unit or origin, except for a point with a coordinate within rounding
error of the midpoint between two such multiples.
Setting the cell count from a profile or selection
approx_n_cells accepts, besides a number, what the level-selection step
returned: the integer vector of ranked candidates from
determine_optimal_levels() (its first element is used; its NA is
refused with a note on where it came from), a select_resolution() result
(its $best), or a resolution_profile(). A profile built without an
estimate is read with select_resolution() by cp; one built with
estimate is read by criterion = "auto", the rule that goes with its
estimate: a size for pooled values, the lowest leave-one-out error for
plain means. The count used is returned as params$approx_n_cells and
where it came from as params$approx_n_cells_from (NULL for a plain
number).
A count read off a selection or a profile raises a warning of class
"spatialkit_bound_chosen" when its optimum sits on a bound of the ladder
and one of class "spatialkit_no_structure" when one cell for the whole
layer scores as well (for a count set by a size: when cells of that size
predict no better than one mean; the count stands). A profile without an
estimate and with no cp to read is an error (class
"spatialkit_no_default_criterion" when another criterion is finite). See
resolution_profile().
A count read off a profile or selection is a number of k-means cells:
every one occupied, and small where the points are dense. A lattice lays
that many equal cells over the whole boundary, so on clustered points many
of them hold no point; on evenly spread points it matches.
params$cells_occupied and params$cells_empty report how the points
filled the grid, and a count that came from a profile or selection warns
when fewer than three quarters of it are occupied. For cells that follow
the points, seed a Voronoi tessellation with
get_voronoi_seeds(method = "kmeans", n = <the selection>, sample_points = <the points>):
given the select_resolution() result or the profile itself, it returns
the centres of the partition the profile scored, whose Voronoi cells are
the cells the criteria judged (refitted to every point when the profile,
without an estimate, was fitted to a subsample). Seeds made that way carry
the hull of sample_points as their cover, so the cells built on them hold
every point; made with neither sample_points nor a boundary, they carry
the hull of the points the profile was computed on.
Coordinate reference systems
When exactly one of points_sf and boundary has a CRS, the other is
interpreted in it, with a warning. CRS-less points, and a CRS-less boundary
given with projected points, are read as harmonize_crs() does; CRS-less
points that do not look like lon/lat cannot take a geographic boundary's
CRS and are refused with an error. A CRS-less boundary given with lon/lat
points is read as lon/lat when its coordinates fit the lon/lat envelope,
and refused with an error otherwise. When neither has one, both are read
by the lon/lat test of ensure_projected(): taken as EPSG:4326 and
projected when the points look like degrees (a boundary whose coordinates
do not fit the lon/lat envelope is then refused with an error), otherwise
left in the same unnamed planar space. A boundary without a CRS that crs
stamps with a geographic CRS is tested for a latitude beyond 90 as well.
Whenever the local projected CRS of ensure_projected() is picked for
lon/lat points, or CRS-less ones taken as lon/lat (no crs, or a
geographic one), a hex or square grid with a boundary is laid in it unless
it distorts areas across the boundary by more than 1 percent (Web Mercator
over a near-global extent, say). The grid is then laid, and the points
indexed, in the equal-area CRS ensure_projected(purpose = "area") picks
for the boundary, with a logged warning, as create_grid_polygons() does,
so the cells stay equal-area.
Seeds that carry the record of how their count was set
(attr(, "count_rule")) were scored in the CRS the profile worked in, each
row in the cell of its nearest centre. When the record says they are the
centres it scored and holds them (the seeds of a select_resolution()
result, or those a seeding function returns for one), method = "voronoi"
builds their cells in that CRS, with no crs or a geographic one, whatever
CRS the seeds arrive in, and returns them there or in the geographic crs;
see "Seeds a profile scored" in create_voronoi_polygons(). Voronoi cells
built in another projected CRS, named in crs, are the nearest-seed cells
of that CRS, so a row near a boundary can fall in the neighbouring cell,
and summarize_by_cell() then reports that the cells are not the ones
scored. Voronoi cells returned in a geographic crs can hold two corners
at one point where four seeds stand the same distance from a corner
(gridded locations), which sf's spherical engine (s2) refuses; "Polygons
in degrees" in spatialkit-geometry says what still stops on them.
Points on edges and outside every cell
The edge of a cell has a margin of one part in 1e10 of the largest
coordinate of the cells, at most a millionth of the diagonal of their
bounding box and at least four times the spacing of doubles at that
coordinate. A point within that margin of a cell's edge is in that cell,
and a point in two or more cells (on a shared edge, or within that margin
of it) takes the smallest cell_id among them, so a lattice point on a
cell edge takes the same cell in any unit or origin.
A point outside every cell is snapped to the nearest cell only when it is
within a thousandth of the median cell width of it, and a point the same
distance from two cells, to one part in ten million, takes the smaller
cell_id. For cells in degrees the distances of the snap are taken on the
sphere, in metres, whatever sf::sf_use_s2() says, and the width is taken
as an arc of the sphere, as the margin is. Points outside the study area
are left as NA, so a summary built from index counts only the points
the tessellation covers. When any point is NA, a warning of class
"spatialkit_unassigned" gives the number
(tryCatch(spatialkit_unassigned = ) catches it; the condition carries
n and total).
For "voronoi" and seeds (a layer a seeding function returned, the seeds
of a select_resolution() result, or points given with a cover),
index holds the cell each seed generates, whether the seed lies inside
the boundary or not: a k-means seed outside a boundary that is not convex
has its cell, the part of the study area nearer it than any other seed.
Only a seed whose cell the clip removed whole, or one without a location
(an empty geometry, or a coordinate that is not finite or lies beyond
1e150), is NA, and the warning then names seeds. See
create_voronoi_polygons().
For "voronoi" and "triangles", points so far from the origin of their
CRS that doubles there are spaced more than a millionth of their extent
apart (0.125 at 1e15, beside a layer a few kilometres across) have the
cells' edges and their own cells read at that rounding; the cells are
built, and a warning of class "spatialkit_xy_imprecise" gives the
spacing and the extent. For "hex" and "square" the grid's warning says
the same of the boundary (see create_grid_polygons()).
See Also
Other cell building:
clip_target_for(),
create_grid_polygons(),
create_grid_polygons_cached(),
create_voronoi_polygons(),
ensure_stable_poly_id(),
get_voronoi_seeds(),
plot_tessellation_map(),
voronoi_seeds_kmeans(),
voronoi_seeds_random()
Examples
library(sf)
set.seed(1)
pts <- st_as_sf(
data.frame(x = 5e5 + runif(20, 0, 100), y = 5e6 + runif(20, 0, 100)),
coords = c("x", "y"), crs = 32632
)
tess <- build_tessellation(pts, method = "voronoi", quiet = TRUE)
tess$cells
Read cell values at new locations
Description
Gives each location of newdata the value of the cell it lies in, read
from a summarize_by_cell() result: the pooled value when the summary
holds one, the plain mean otherwise, with the interval for one
observation when the summary holds it. Beside each value it returns the
location's distance from the nearest observation, since a cell's value
describes the part of the cell where its observations lie.
Usage
cell_values_at(
newdata,
values,
points,
response_var,
id_col = "poly_id",
seeds = NULL
)
Arguments
newdata |
The locations: an sf layer. A feature that is not a point
is reduced to one with |
values |
The |
points |
The assigned layer |
response_var |
Name of the summarised column wanted: the response, or a predictor. |
id_col |
Name of the ID column, found as |
seeds |
|
Details
The function works in six steps.
-
The working CRS. The CRS the summary measured in: the one in
attr(values, "count_rule")when that record names a projected CRS, else the one inattr(values, "pooled"), else the CRS ofpointswhen it is projected and the oneensure_projected()picks for it when it is not.points,newdataandseedsare transformed to it.newdata,seedsandpointsare read in x and y: a layer whose points, or the points taken from its other features, do not all have the same dimensions (some with a Z or M coordinate) is read without its Z and M, since sf reads a layer in the dimension of its first point. So is a layer of points, polygons or lines innewdataorpointswhose geometries carry M (XYM or XYZM), which GEOS does not read. So are the polygons ofvalueswhen they do not all have the same dimensions. Polygons ofvalueswhose geometries carry M are read in x and y as well. When neitherpointsnornewdatahas a CRS the coordinates are used as they are, unless those ofpointslook like longitude and latitude: both are then read as EPSG:4326, assummarize_by_cell()readspoints, withensure_projected()'s warning;newdataorseedswith an x outside -180 to 360 or a y beyond 90 north or south cannot be in degrees, and stop the call.seedswithout a CRS besidepointswith one are read asbuild_tessellation()reads a boundary without a CRS, with a warning: beside a projected CRS, coordinates that look like longitude and latitude are taken as EPSG:4326 and transformed, and others are taken to be in the CRS ofpoints; beside a geographic CRS, coordinates within the ranges of longitude and latitude are taken to be in it, and others stop the call.newdatawithout a CRS besidepointswith one stops the call. -
The scored rows. The rows of
pointswith a finiteresponse_var, a cell ID and a location: a point whose coordinates are finite and within 1e150, as given and in the working CRS. Their distinct locations are the observations every distance below is taken from. -
The cell of a location. With
seeds, the cell of the nearest seed. That is the Voronoi cell before its clip to the cover, so every location has one, unless its nearest seed has anNAID: a location nearest such a seed has no cell.build_tessellation()gives each seed of a layer it takes for seeds (seecreate_voronoi_polygons()) the cell it generates, a seed outside a boundary that is not convex (a k-means centre over a bay) included, andNAonly to a seed whose cell the clip removed whole. Other points, such as points placed by hand, are indexed by the cell that holds them, so one outside a boundary that is not convex isNAalthough its cell is built. One that lies in no cell but within a thousandth of the median cell width of a cell takes the ID of the nearest cell instead, which beside a boundary that is not convex can be the cell of another seed; two seeds with one ID stop the call (seeseeds). Whenvaluescarries the cell polygons, a seed that isNAis given its cell here: a seed with anNAID that lies in no polygon ofvaluestakes the ID of the polygon, among those no seed names, that a point inside it finds as its nearest seed. That is the cell the seed generates, since every point of a Voronoi cell is nearer its own seed than any other. A seed that the points inside several such polygons find as their nearest seed generates at most one of them (the seeds of the others are missing fromseedsor have no location), and nothing says which: it keeps itsNAID, with a warning, so the locations nearest it have no cell and are filled (step 5). A seed with anNAID inside a polygon keeps it, and so does one whose cellvaluesdoes not hold. Withoutseeds, the polygon ofvaluesthat holds the location, byassign_features_to_polygons()with its defaulttie_breakand the summary's record of the count, so a location on the edge between two cells the profile scored is placed as that function places such a row (see "Ties"); a location in no polygon has no cell. Polygons without a CRS are read as that function read them for the rows ofpoints: the locations are handed to it in the CRS ofpoints, whatever CRSnewdataarrived in. Where that join runs on the sphere and s2 refuses a polygon ofvalues(see "Joins in longitude and latitude" inassign_features_to_polygons()), the call stops with an error of class"spatialkit_cells_degenerate"that gives the rows ofvaluess2 refuses (rowson the condition), names the cause and says to transformvaluesto a projected CRS. -
The value. The cell's pooled value of
response_var,..pooled_<prefix><response_var>with the prefixresp_orpred_, whenvalueshas that column; otherwise its mean,<prefix>mean_<response_var>. The columnestimatesays which. For a column summarised as response and as predictor the response's columns are read. The interval is the cell's..obs_lo_<prefix><response_var>and..obs_hi_<prefix><response_var>whenvalueshas them. -
The fill. A location with no cell, or whose cell holds no scored row and has no value in
values, takes the value and interval of the cell of its nearest scored row.filledis thenTRUEandfilled_fromis that cell's ID. The ID column still holds the location's own cell, as step 3 finds it, so the two columns together say where a location lies and where its value came from. A cell that holds a scored row is not filled. Wherevalueshas no value for such a cell (the summary could not compute the pooled columns, or has no row for the cell), its locations havevalue = NAandfilled = FALSE; a filled value isNAin the same case, when the cell it is taken from has none. -
The distance.
dist_nearestis the distance from the location to the nearest location of a scored row, in the units of the working CRS.dist_ratiois that distance over the layer's spacing: the median, over the distinct locations of the scored rows, of the distance to the nearest other one.
Cell IDs are matched as text. The ID column of values is character when
the summary joined a cells_sf whose IDs were of another class than the
assigned layer's, while points and seeds keep the class they had; the
IDs of all three are written out as text before any match, and both ID
columns returned have the class of the ID column of values wherever
that class can hold every ID (see Value).
Value
A data frame with one row per row of newdata, in its order:
- the ID column
The cell the location lies in, under the name of the ID column;
NAfor a location in no cell.valueThe cell's value, or for a filled row the value of the cell in
filled_from.estimate"pooled"or"mean": which value of the summaryvalueis.obs_lo,obs_hiThe interval for one observation, when
valuesholds it.filledTRUEwhen the location has no cell, or its cell neither a scored row nor a value, and the value is that of the cell of the nearest scored row.filled_fromFor a filled row, the ID of the cell the value came from;
NAotherwise.dist_nearestDistance to the nearest location of a scored row, in the units of the working CRS.
dist_ratiodist_nearestover the spacing;NAwhen the scored rows sit on one location.
A row of newdata with an empty geometry, or with a coordinate that is
not finite or lies beyond 1e150 as given or in the working CRS, has NA
in every column. The two ID
columns have the class of the ID column of values; when a cell that
values has no row for has an ID that class cannot hold (a string
beside numbers), both are character.
What produced the frame is in attr(, "values_at"), a list of class
"spatialkit_values_at" with a print method: assignment ("seeds"
or "polygons"), crs (the working CRS), column (response_var),
estimate, obs_level (the level of the interval columns; NULL
without them, and NA when values holds them and no longer says at
what level), n (the scored rows), locations (their distinct
locations), spacing (what dist_ratio divides by; NA with one
location),
filled (how many rows of newdata were filled) and count_rule (the
summary's record of how the cell count was set, or NULL). It describes
the call: a subset of the frame's rows keeps it as it is.
The function raises no classed warning of its own; the warning that
says how seeds without a CRS were read (step 1) and the one that
counts the seeds outside the polygons of values left without a cell
(step 3) are plain ones. It passes on the conditions that
coerce_to_points(), a CRS transformation and
assign_features_to_polygons() raise, with two exceptions. The error of class spatialkit_features_degenerate with which
coerce_to_points() refuses a polygon s2 cannot take a centroid of, or
a centroid GEOS puts outside its feature, is raised in this function's
name, with the same class and fields, naming newdata or points and
its rows. The warning
assign_features_to_polygons() raises when no location at all falls in
a polygon is neither raised nor logged, since every such row has
filled = TRUE, which says the same row by row.
Ties
A distance to a seed, a centre or a scored location counts as the same as
the least when its square is no more than the square of the least distance
lengthened by a margin, plus one part in ten million of the least squared
distance. The margin is one part in 1e10 of the largest coordinate of the
seeds, centres or scored locations searched, at most a millionth of the
diagonal of their bounding box and at least four times the spacing of
doubles at that coordinate. A location the same distance from two seeds takes the one
that comes first in seeds. For the seeds of a select_resolution()
result that is the lower-numbered centre, the rule resolution_profile()
scores with. When the summary's record of the count holds the centres the
profile scored and seeds are those centres (the seeds a selection
carries, or those a seeding function returns for it), in any order and any
CRS, the distances are taken to the centres as the record holds them, a tie
goes to the lower-numbered centre, and each centre gives the ID of the seed
that stands at it. Seeds count as the centres when they are as many and
each lies at a different centre, within a thousandth of its distance from
the next nearest one, so a seed that came back from another CRS with its
coordinates rounded, or seeds sorted by their cell, do not settle a tie
another way. A location on the edge between two such cells then takes the
cell assign_features_to_polygons() gives a row there, with seeds and
without. Other seeds, among them a subset of the centres, are searched as
given. A location the same distance from two locations of scored rows takes
the one in the lower column (x values within one part in ten million of the
diagonal of the scored locations' bounding box, or within one part in 1e10
of their largest coordinate (at most a millionth of that diagonal,
and at least four times the spacing of doubles at that coordinate) where
that is more, counting as one), then the
one lower in y, y values read the same way; among scored rows at one
location that lie in different cells, the cell that comes first in the
order of the IDs (ascending for numbers, the C-locale order for strings,
the order of the levels for a factor), and the same among locations in one
column and one row (two records of one station that differ only in the
last bits of their coordinates, which are the same distance from any
location, however near, while they lie within the margin of each
other). Neither rule depends on the order of
the rows of points, or on whether the FNN package is installed. A
tie is a tie between distances computed from the coordinates in the working
CRS, so on gridded locations the same layer in another projected CRS can
put a location on a boundary in the other cell; another unit or origin of
the same CRS moves only the last bits of the distances and settles the ties
the same way, with one exception. The margin grows with the largest
coordinate (about 0.46 mm at a UTM northing near 4,550 km, about half a
micrometre once the origin lies next to data 5 km across), so a location
whose distances to two of them differ by less than the margin with one
origin and by more with another is a tie with the first, settled as
above, and takes the nearer with the second.
Away from the observations
The value and the interval describe locations among the observations.
The interval's two ends are quantiles of leave-one-out errors, each the
error of predicting an observation from the others around it, so it says
nothing of a location far from every observation: a gap in the layer, or
ground beyond its edge. Away from the observations no interval here is
calibrated. dist_nearest and dist_ratio say how far each location is
from the data. No threshold is applied to either and no location is
flagged or left out. area_of_applicability() and fold_separation()
are the tools for deciding where a prediction applies.
The interval's coverage falls as dist_ratio grows; "How this was
checked" gives the figures.
Without the FNN package
The function makes three nearest-neighbour searches: each location's
nearest scored location, each location's nearest seed (and that of a
point inside each cell no seed names, when a seed with an NA ID lies
outside every cell; see step 3), and each scored location's nearest
other one (for the spacing). With FNN each uses
a kd-tree. Without it each compares every pair, and a search that would
compare more than getOption("spatialkit.exact_pairs_max", 2e9) pairs
stops the call first, with an error of class spatialkit_work_limit
that names the search (the fields work, limit and what). The search
for the spacing does not depend on the number of locations asked for:
above about 44,700 distinct scored locations the call stops without
FNN however few they are. The result is the same with and without
the package.
How this was checked
A simulation shows how the interval's coverage falls with dist_ratio
(dev/sim-pooled-values.R
in the package's GitHub repository; "How this was checked" in
summarize_by_cell() describes it). Each of 200 layers has 1,500
clustered observations in 333 cells, 300 further observations held out
at random among them and 300 held out as a block, which leaves a gap in
the layer. Over the held-out observations of all layers, the interval at
obs_level = 0.90 held 91.5 percent of those with a dist_ratio below
1, 89.2 percent from 1 to 2, 83.9 percent from 2 to 4, 77.9 percent from
4 to 8 and 69.5 percent above 8. It held 89.6 percent of the observations
held out at random and 75.1 percent of those in the block.
See Also
summarize_by_cell(), which computes values;
build_tessellation(), whose index gives each seed's cell;
area_of_applicability() and fold_separation() for where a
prediction applies.
Other assign and summarise:
assign_features_to_polygons(),
kriging_adequacy(),
summarize_by_cell()
Examples
library(sf)
set.seed(1)
n <- 400
east <- runif(n, 0, 1e4)
north <- runif(n, 0, 1e4)
all_pts <- st_as_sf(
data.frame(x = 5e5 + east, y = 5e6 + north,
income = 30 + 5 * sin(east / 2000) + 5 * cos(north / 1500) +
rnorm(n)),
coords = c("x", "y"), crs = 32632
)
pts <- all_pts[1:350, ]
newpts <- all_pts[351:400, ]
# The count from a size, the cells, the observations in them, the values,
# all at the defaults: pooled values at 4.5 observations per cell.
prof <- resolution_profile(pts, "income")
sel <- select_resolution(prof)
seeds <- get_voronoi_seeds(method = "kmeans", n = sel, sample_points = pts)
tess <- build_tessellation(seeds, method = "voronoi", quiet = TRUE)
asg <- assign_features_to_polygons(pts, tess$cells, polygon_id_col = "cell_id")
out <- summarize_by_cell(asg, "income", id_col = "cell_id",
cells_sf = tess$cells, obs_level = 0.90)
# The value at other locations, each placed in the cell of its nearest
# seed. `tess$index` gives the cell of each seed.
seeds$cell_id <- tess$index
at <- cell_values_at(newpts, out, asg, "income", id_col = "cell_id",
seeds = seeds)
head(at)
attr(at, "values_at")
# Without the seeds a location is placed in the polygon that holds it. One
# beyond the layer's edge lies in no polygon: it is filled from the cell of
# the nearest observation, and `dist_ratio` says how far that is.
beyond <- st_sf(geometry = st_sfc(st_point(c(5e5 + 2e4, 5e6 + 5e3)), crs = 32632))
cell_values_at(rbind(st_sf(geometry = st_geometry(newpts[1:2, ])), beyond),
out, asg, "income", id_col = "cell_id")
Clear the cached fitted values of a Bayesian GP fit
Description
Removes the cached fitted() values of a bayesian_fit, so the
next call recomputes them from the posterior. You need it only after
editing the brmsfit engine in place. A change to data_sf,
or a refit, invalidates the entry on its own (see "The Bayesian GP cache"
in spatial_fit-fitted). On any other fit it does nothing.
Usage
clear_fitted_cache(object)
Arguments
object |
A |
Details
Every copy of a fit shares the cache, so clearing it through one copy clears it for all of them; the others recompute.
Value
object, invisibly.
See Also
Other options and caches:
clear_grid_cache(),
spatialkit-conditions,
spatialkit-options,
spatialkit_quiet()
Examples
## Not run:
# Needs brms and a Stan toolchain, and takes minutes.
library(sf)
set.seed(1)
n <- 60
dat <- st_as_sf(
data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
elev = rnorm(n)),
coords = c("x", "y"), crs = 32632
)
dat$price <- 10 + 2 * dat$elev + rnorm(n)
fit <- fit_bayesian_spatial_model(dat, "price", "elev", chains = 2,
iter = 1000, compute_loo = FALSE)
f1 <- fitted(fit) # computed from the posterior and cached
clear_fitted_cache(fit)
f2 <- fitted(fit) # computed again
all.equal(f1, f2)
## End(Not run)
Clear the in-session grid cache
Description
Empties the cache that create_grid_polygons_cached() fills, and returns
the number of grids removed.
Usage
clear_grid_cache(cache_env = .gmt_cache)
Arguments
cache_env |
The cache to clear. The default is the package's own;
pass an environment only if you passed the same one to
|
Value
Invisibly, the number of entries removed.
See Also
create_grid_polygons_cached(), which fills the cache.
Other options and caches:
clear_fitted_cache(),
spatialkit-conditions,
spatialkit-options,
spatialkit_quiet()
Examples
library(sf)
bnd <- st_sf(geometry = st_sfc(st_polygon(list(rbind(
c(0, 0), c(100, 0), c(100, 100), c(0, 100), c(0, 0)
))), crs = 32632))
invisible(clear_grid_cache()) # start from an empty cache
g1 <- create_grid_polygons_cached(bnd, target_cells = 9)
g2 <- create_grid_polygons_cached(bnd, target_cells = 9) # cache hit
print(clear_grid_cache()) # 1: the grid cached above
print(clear_grid_cache()) # 0: already empty
Build the area to tessellate within, from points or a boundary
Description
Builds the area that the hex and square cells of
build_tessellation() are clipped to. With a boundary it is that
boundary, row for row; without one it is the axis-aligned bounding box of
points_sf in the working CRS. Either can be buffered by expand.
Usage
clip_target_for(points_sf, boundary = NULL, expand = 0, quiet = FALSE)
Arguments
points_sf |
An sf object with POINT/MULTIPOINT geometry. Points that
mix XY and XYZ (or XYM), or that carry M, are read in x and y, since sf
reads a layer in the dimension of its first geometry and GEOS refuses M.
A point that is empty, or has a coordinate that is not finite or lies
beyond 1e150, has no location and takes no part in the bounding box.
With no |
boundary |
Optional polygonal sf object. One with no CRS, given with
points that have one, is interpreted in the points' own CRS, with a
warning. With points in a projected CRS it is read as |
expand |
A single non-negative number. Below 1 it is a fraction of
the longer side of the bounding box (of |
quiet |
Logical; suppress this function's progress |
Details
Use it to build the boundary that method = "hex" and "square"
require, to check that a study-area polygon contains the observations
before tessellating, or to pass the same envelope to
create_voronoi_polygons() and create_grid_polygons() so that two
tessellations of one dataset cover the same ground.
It is not the target build_tessellation() derives on its own:
method = "voronoi" without a boundary clips to the convex hull of the
points (or of their cover, for seeds) buffered by 2 percent of its
diagonal, and there expand is always a distance. A bounding box over a
non-rectangular point cloud includes corners with no data, so a hex or
square grid laid over it has cells that hold no points; pass the
study-area polygon when there is one.
Value
An sf polygon layer representing the clip target. For lon/lat input
the layer is returned in the automatically selected local projected CRS,
not the input CRS; a message reports this unless quiet = TRUE.
Points with no extent
Points that all share one x or one y, or nearly so (the short side of
their bounding box below a millionth of the long side, or below about
1.5e-154, a length whose square doubles cannot hold), get a small buffer
around them instead of a box. When every point sits at one location, or
the share of their spread the buffer would take (5 percent, or a
fractional expand) is below that length, the box has no extent to take
a share of, and the target is a disk of radius 1 unit of the CRS around
it (1 m in a metre CRS, 1 km in a kilometre CRS), unless expand is 1 or
more, which is then the radius; the message says so. Pass boundary for
a target of real size.
See Also
Other cell building:
build_tessellation(),
create_grid_polygons(),
create_grid_polygons_cached(),
create_voronoi_polygons(),
ensure_stable_poly_id(),
get_voronoi_seeds(),
plot_tessellation_map(),
voronoi_seeds_kmeans(),
voronoi_seeds_random()
Examples
library(sf)
set.seed(1)
pts <- st_as_sf(
data.frame(x = 5e5 + runif(30, 0, 100), y = 5e6 + runif(30, 0, 100)),
coords = c("x", "y"), crs = 32632
)
# No boundary: the bounding box, expanded by 10% of the extent
box <- clip_target_for(pts, expand = 0.1, quiet = TRUE)
st_area(box)
Reduce each geometry to one representative point
Description
Replaces the geometry of each row of an sf object with a point, by the
rule mode names. The result has one row per row of x, in the same
order.
Usage
coerce_to_points(
x,
mode = c("auto", "centroid", "point_on_surface", "surface", "line_midpoint",
"bbox_center"),
tmp_project = TRUE
)
Arguments
x |
An sf object. |
mode |
How each geometry becomes a point: |
tmp_project |
Logical; take line midpoints in a temporary
projection. Default |
Value
An sf object with its geometry reduced to POINTs, row for row
with x; an empty input geometry gives an empty POINT.
Modes
"auto"(default)POINT rows are kept. POLYGON and MULTIPOLYGON rows get a point on the surface. A LINESTRING gets its midpoint, and a MULTILINESTRING the midpoint of its longest part (see "Lines"). MULTIPOINT rows and rows of other types, such as geometry collections, get their centroid.
"centroid"The centroid of every row.
"point_on_surface"(alias"surface")A point that lies on each geometry, taken with GEOS.
"line_midpoint"The midpoint of each LINESTRING, taken in a temporary projection (with
tmp_project = FALSEon lon/lat data, its centroid). Rows of other types (points, polygons and their MULTI forms) get their centroid. A MULTILINESTRING or GEOMETRYCOLLECTION row is an error: cast it to LINESTRING first, or use"auto", which takes the midpoint of a MULTILINESTRING's longest part."bbox_center"The centre of each row's bounding box.
Empty geometries and rows without a location
An empty geometry of any type, lines included, becomes an empty POINT in
its own row; prep_model_data() and make_folds() then drop such rows,
as they drop any other empty geometry. An empty part inside a non-empty
feature is ignored, so the feature gets the point its other parts give.
A geometry with no location (see spatialkit-geometry, "Rows without a
location") gets an empty POINT in every mode, as an empty geometry does.
So does a geometry of a layer in a geographic CRS with a vertex at a
latitude beyond 90 degrees, and a warning of class
spatialkit_lat_beyond_90 gives its rows of x (rows).
Lines
Modes "auto" and "line_midpoint" take the midpoint of a line in a
temporary projection (tmp_project), the one ensure_projected()
chooses for the lines. A line that projection returns empty or without
some of its vertices is not sampled: the call stops with an error of
class spatialkit_features_degenerate (see "Errors").
In mode "auto" a MULTILINESTRING gets the midpoint of its longest part.
When several parts share the greatest length (to one part in ten
million, measured in the projection used), their midpoints are taken
and the one lowest in x, then in y, is kept, so the point does not depend
on the order in which the feature lists its parts. x values within one
part in ten million of the diagonal of the midpoints' bounding box count
as one, so y decides between midpoints whose x differ only in their last
bits, and the point does not move with the origin of the coordinates.
Longitude and latitude
Modes "auto" (for polygons) and "point_on_surface" take the point
with GEOS, which reads a layer in longitude and latitude on the plane in
degrees, under either sf::sf_use_s2() setting. sf's warning that such a
point "may not give correct results for longitude/latitude data" is not
passed on. A polygon that spans more than 180 degrees of longitude (one
written across longitude 180, from 179.5 to -179.5) GEOS reads the long
way round the globe, so its point is tested on the polygon read on the
sphere with s2; when it does not lie on it, the point is taken again
with the longitudes below 0 read from 180 to 360, and brought back into
-180 to 180. A polygon whose point lies on it neither way, or that s2
cannot read, keeps GEOS's point, and a warning of class
spatialkit_surface_point_off gives its rows of x (rows). When x
has no CRS and the lon/lat test of ensure_projected() takes its
coordinates for degrees, its polygons that span more than 180 units are
read so too, as EPSG:4326, and a warning names the rows whose point that
reading moves; the points keep the missing CRS.
Mode "bbox_center", and the centroids that GEOS takes on the plane in
degrees (a lon/lat layer with s2 off) under "centroid", for the rows
other than LINESTRINGs under "line_midpoint", and for MULTIPOINTs and
collections under "auto", read a geometry written across longitude 180
the same way: one that spans more than 180 degrees of longitude as
written, and no more than 180 with the longitudes below 0 read from 180
to 360, gets the centre of that box, or GEOS's centroid of the geometry
so read, brought back into -180 to 180. A layer without a CRS that the
lon/lat test takes for degrees is read so too, with the same warning. A
geometry wider than 180 degrees in both readings, such as one around a
pole, keeps the centre of its box on the plane, or GEOS's planar
centroid. The centroids s2 takes on the sphere are not changed.
With s2 on, sf takes the centroids of a lon/lat layer with s2 (under
"centroid", for the rows other than LINESTRINGs under
"line_midpoint", and for collections under "auto"), and s2 refuses
some polygons GEOS accepts. A polygon s2 refuses because a vertex
repeats the one before it, on its own or inside a collection, gets the
centroid of the same ring without the repeat; the ring's points are
unchanged. A polygon s2 refuses for another reason (edges that cross, a
figure eight) is an error (see "Errors"). With s2 off, the centroids
are GEOS's, planar in degrees.
Z and M coordinates
A layer whose geometries do not all have the same dimensions (XY beside
XYZ or XYM, as rbind() of an XY and an XYZ layer gives) is read in x
and y, and its points come back in XY with a warning of class
spatialkit_zm_dropped whose rows are the rows that carried Z or M
(see spatialkit-geometry, "Mixed dimensions, Z and M"). A layer in one
dimension, XY or XYZ throughout, is read as it is, and so is a layer
whose only geometries of another dimension than the first are empty and
not points.
GEOS does not read M coordinates. When the mode reduces a geometry that
carries M (XYM or XYZM) to a point (any such geometry under
"centroid", "point_on_surface" and "line_midpoint", any that is
not a POINT under "auto"), the layer is reduced in x and y: Z and M
are dropped from every geometry, the points come back in XY, and a
warning of class spatialkit_zm_dropped says so, with the rows whose
geometry carries M as its rows. Empty geometries are not counted. A
POINT layer that carries M is returned as it is under "auto". Mode
"bbox_center" reads the box of each geometry and gives XY points for
any layer, with no warning about Z or M.
Errors
Each of these is an error of class spatialkit_features_degenerate that
gives the rows of x (rows on the condition):
- A polygon s2 refuses
In longitude and latitude with s2 on, a polygon whose centroid s2 cannot take even without its repeated vertices. The message quotes s2 and says to transform
xto a projected CRS or to use anothermode.- A centroid outside its feature
GEOS, which takes the centroids in a projected CRS, without a CRS, and in degrees with s2 off, weights each part of a ring by its signed area. Where the edges of a ring cross (a bowtie), or a hole lies outside its shell, parts of the feature count with opposite signs, and the point can lie far outside the feature. A centroid outside the bounding box of a feature GEOS reports invalid is refused: the condition carries
site = "geos_centroid"and GEOS's reason for each row (reasons), and the message says to passmode = "point_on_surface"or to repair the features withsf::st_make_valid(). A centroid inside the box is returned as GEOS gives it.- A line the temporary projection cannot place
A line that the projection returns empty or without some of its vertices. The condition carries
site = "projection", and the message says to passmode = "centroid"ortmp_project = FALSE, which take the point in longitude and latitude, without the projection.
The functions that reduce a layer they are given to points this way
(prep_model_data(), make_folds(), fold_separation(),
estimate_sac_range(), resolution_profile(),
determine_optimal_levels(), cell_values_at(), summarize_by_cell(),
select_features_forward(), compare_models_cv(),
area_of_applicability(), predict_surface()) raise each of these
errors in their own name, with the same class and fields, naming their
argument and its rows. spatialkit-conditions lists every class.
See Also
spatialkit-geometry for how input geometry and CRSs are read.
Other data preparation:
[.spatialkit_rows(),
ensure_projected(),
harmonize_crs(),
prep_model_data(),
spatialkit-geometry
Examples
library(sf)
poly <- st_sf(
id = 1,
geometry = st_sfc(st_polygon(list(rbind(
c(0, 0), c(2, 0), c(2, 2), c(0, 2), c(0, 0)
))), crs = 32632)
)
coerce_to_points(poly, "auto") # a point on the polygon's surface
Compare fitted models in sample
Description
The table from evaluate_insample(), plus AICc (GWR), LOOIC
(Bayesian GP), convergence and GP-adequacy flags and the residual Moran's
I of each fit. No model is refitted. For scores on held-out blocks use
compare_models_cv().
Usage
compare_models(fits, newdata = NULL, ...)
Arguments
fits |
A |
newdata |
Optional sf object of held-out rows, carrying the response and the predictors. |
... |
Passed to |
Details
The metrics are those of model_metrics(): see its sections
"What the metrics are computed on" and "Percentage errors on responses
with zeros".
Value
A data.frame with one row per model and these columns:
modeland the metric columnsAs in
evaluate_insample().metric_basisWhat each row's metrics were computed on (see
evaluate_insample). A table that mixes"out-of-bag"and"in-sample"rows does not rank the models, and says so in the log.AICc(GWR) andLOOIC(Bayesian)Sums over the rows a model was fitted to, so each column is set to
NA, with a warning, when the fits carrying it were fitted to different rows (a predictor with missing values drops rows, for example) or to different responses (a transformed response on the same rows), and the warning says which.convergence_okTRUEorFALSEfor a Bayesian fit whose convergence was checked (seefit_bayesian_spatial_model) andNAotherwise. A fit that did not converge is ranked like the others, so it also raises a warning.gp_adequacyWhat the posterior of a Bayesian fit said about its Gaussian-process basis (
"ok","below_resolution","unresolved_short_range","no_signal_above_floor"or"not_checked"; see "What the basis resolves" infit_bayesian_spatial_model) andNAfor the other backends. A basis found too coarse scores like one that was adequate, so read the column beside the metrics.resid_morans_I,resid_morans_z,resid_morans_pMoran's I of the residuals, from
residual_morans_i().resid_morans_nullThe null each model was scored against, since that choice is per fit and governs how much the p-value is worth.
resid_morans_basisWhich residuals the statistic was computed on: always those of the rows the model was fitted to, also when
newdatais given, so the column reads"in-sample", or"out-of-bag"for a forest, and never"newdata". Besidemetric_basis = "newdata"the Moran columns describe the training residuals, not the prediction errors onnewdata, and the two can differ in sign.
A significant p-value is noted in the log (not raised as an R warning):
positive autocorrelation as structure the model may have missed,
negative (resid_morans_z < 0) as the alternating residuals of a
model that tracks its data closely. Read the caveats in
residual_morans_i() before treating silence as evidence of
no residual structure.
See Also
Other in-sample checks:
evaluate_insample(),
model_metrics(),
print.morans_i(),
residual_morans_i()
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), b = rnorm(60)),
coords = c("x", "y"), crs = 32632
)
# An offset keeps the response away from zero, where MAPE is undefined.
pts$z <- 10 + 2 * pts$a - pts$b + rnorm(60, 0, 0.3)
# Two predictor sets for the same learner: the model that leaves `b` out
# against the one that has it. These are out-of-bag numbers;
# compare_models_cv() scores the same question on spatial folds.
fits <- list(
a_only = fit_rf_model(pts, "z", "a", num_trees = 100, seed = 1),
a_and_b = fit_rf_model(pts, "z", c("a", "b"), num_trees = 100, seed = 1))
cmp <- compare_models(fits)
cmp[, c("model", "RMSE", "R2", "metric_basis", "resid_morans_I",
"resid_morans_p")]
Compare models on the same cross-validation folds
Description
Cross-validates one or more backends on one set of folds and returns a
comparison table. Unlike compare_models(), this fits the
models, once per fold.
Usage
compare_models_cv(
data_sf,
response_var,
predictor_vars,
models = c("GWR", "Bayesian"),
k = 5,
seed = 123,
folds = NULL,
boundary = NULL,
pointize = "auto",
gwr_args = list(),
bayes_args = list(),
rf_args = list(),
summary = c("mean", "median"),
quiet = FALSE,
block_size = NULL,
auto_range = FALSE,
metrics = NULL
)
Arguments
data_sf |
An sf object. When the folds are built here, a feature that is not a point is reduced to one, and the layer is read in x and y (see spatialkit-geometry). |
response_var |
Response column name. |
predictor_vars |
Predictor column names. |
models |
Character vector: any subset of |
k |
Number of folds to build when |
seed |
RNG seed. Default 123. |
folds |
Optional fold definitions, in any of three shapes: a
|
boundary |
Optional polygon sf/sfc. When the folds are built here,
the block grid is clipped to it, as in |
pointize |
How a feature that is not a point is reduced to one (see
|
gwr_args |
Extra arguments for |
bayes_args |
Extra arguments for |
rf_args |
Extra arguments for |
summary |
|
quiet |
Logical; suppress this function's progress |
block_size |
Optional minimum block edge length for the shared spatial
CV blocks (projected CRS units), passed to |
auto_range |
Logical. If |
metrics |
Optional scoring function of your own, handed to every
backend's |
Value
A list with these elements:
overallOne row per model with the pooled metrics,
n_pred(the rows they are computed on, see "Rows the overall table is computed on"), the coverage and CRPS columns described in "Coverage and CRPS in the overall table" when a Bayesian GP ran, andmodelas its last column.MAPEandSMAPEskip rows whose denominator is zero;n_MAPEandn_SMAPEcount the rows they used, and for a count or other non-Gaussian response RMSE, MAE and the Bayesian GP's CRPS are the numbers to compare (see "Percentage errors on responses with zeros" and "Which metrics survive a non-Gaussian response" inmodel_metrics()).by_foldThe
fold_metricsof every model that ran, stacked, with amodelcolumn.gwr_cv,bayes_cv,rf_cvThe full
cv_gwr(),cv_bayes()andcv_rf()result of each model that ran.
Coverage and CRPS in the overall table
A model can predict well on average and still be badly calibrated, so a
comparison read from RMSE alone can prefer the model whose uncertainty is
wrong. Heaton et al. (2019) found good point prediction routinely
alongside poor interval coverage. When "Bayesian" is among the
models that ran, overall therefore also carries the columns of
cv_bayes()$predictive_coverage: coverage_50,
coverage_80, coverage_95 (the share of held-out rows inside
the posterior predictive interval at each level, averaged across folds
weighted by each fold's n_pred) and mean_CRPS (the
continuous ranked probability score, lower is better). They are NA
on the GWR and RF rows, which produce point predictions and no draws, and
absent when no Bayesian GP ran. Read coverage against its nominal
level: 0.95 at coverage_95 is calibrated, well below it is
overconfident, well above it is wider than it needs to be.
Rows the overall table is computed on
Shared folds do not guarantee shared rows: a model that fails on a fold
(GWR with a fixed bandwidth across a gap in the data, say) or predicts
NA for some rows pools fewer rows, usually without the hardest
ones. When the models predicted different rows, the function warns and
recomputes every model's pooled metrics, your own metrics
included, on the rows all of them predicted, so n_pred is the same
on every row that has predictions; a model that predicted nothing stays
an NA row. Each model's metrics over all the rows it predicted
stay in its *_cv element and in attr(overall, "all_rows"),
a table of the same shape. by_fold and the Bayesian coverage and
CRPS columns are per fold and are not recomputed.
Every model is cross-validated on the layer as passed, so the warnings
prep_model_data() raises about that layer (class
spatialkit_rows_dropped, counting the incomplete rows dropped,
and spatialkit_constant_predictor) are raised once for the
comparison, not once per model.
Only the models that ran appear, so check which names are present: a
backend whose package is missing is dropped with a message. When no
requested backend is available the function stops with
"no viable models." rather than returning an empty comparison.
References
Heaton, M. J., Datta, A., Finley, A. O., Furrer, R., Guinness, J., Guhaniyogi, R., Gerber, F., Gramacy, R. B., Hammerling, D., Katzfuss, M., Lindgren, F., Nychka, D. W., Sun, F. and Zammit-Mangion, A. (2019). A case study competition among methods for analyzing large spatial data. Journal of Agricultural, Biological and Environmental Statistics, 24(3), 398–425. doi:10.1007/s13253-018-00348-w
See Also
plot_cv_metrics() to draw the per-fold scores of
every model, and plot_calibration() for the Bayesian GP's
intervals.
Other cross-validation:
cv_bayes(),
cv_gwr(),
cv_rf(),
cv_spatial(),
plot_calibration(),
plot_cv_metrics()
Examples
library(sf)
set.seed(1)
n <- 120
dat <- st_as_sf(
data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
elev = rnorm(n)),
coords = c("x", "y"), crs = 32632
)
dat$price <- 10 + 0.01 * (st_coordinates(dat)[, 1] - 5e5) +
2 * dat$elev + rnorm(n)
# The random forest, and GWR beside it when sp is installed, on the same
# folds. "Bayesian" is left out here because a Stan fit per fold takes
# minutes; add it to `models` for a run to report.
models <- c("RF", if (requireNamespace("sp", quietly = TRUE)) "GWR")
cmp <- compare_models_cv(dat, "price", "elev", models = models, k = 3,
rf_args = list(num_trees = 100),
gwr_args = list(bandwidth = 30))
cmp$overall[, c("model", "RMSE", "R2", "n_pred")]
Create square or hexagonal grid polygons over a boundary
Description
Lays a regular grid of equal-area cells over boundary and clips it to that
boundary. Use it rather than create_voronoi_polygons() when you set the
cell size yourself instead of letting the observations set it: per-cell
rates comparable across the map, or a resolution that stays fixed as the
sample grows. Hexagons (type = "hex") avoid the axis-aligned artefacts of
squares and put all six neighbours of a cell at the same distance.
Usage
create_grid_polygons(
boundary,
target_cells = NULL,
type = c("square", "hex"),
cellsize = NULL,
n = NULL,
clip = TRUE,
crs = NULL,
quiet = FALSE,
max_cells = 1e+06
)
Arguments
boundary |
Polygonal sf or sfc object, the study area the grid is
laid over and clipped to.
Rows without a location, rows the repair leaves without a polygon,
vertices at a latitude beyond 90 and mixed dimensions are handled as
"Boundaries" in spatialkit-geometry says.
A boundary without a CRS that |
target_cells |
Optional approximate desired number of cells. Besides
a number it accepts what |
type |
Grid type: |
cellsize |
Optional numeric cell size (length 1 or 2), in the units of
the working CRS. Takes precedence over |
n |
Optional grid resolution (integer, length 1 or 2) giving the number
of columns and rows to divide the boundary's bounding box into; the cell
size is derived from it. |
clip |
Logical; clip the grid to the boundary. Default |
crs |
Optional target CRS: anything |
quiet |
Logical; suppress this function's progress |
max_cells |
Upper bound on the number of cells the grid may have,
estimated from the boundary's bounding box before anything is built.
Default |
Details
Size the grid with exactly one of target_cells (roughly how many cells
you want; the package derives the rest), cellsize (a fixed edge length
in CRS units) or n (a fixed number of columns and rows). When more than
one is given, cellsize wins over the other two and n wins over
target_cells; each argument ignored is named in a logged warning.
Value
An sf polygon layer with one column, poly_id, numbering the
cells in the order sf::st_make_grid() lays them (row by row from the
bottom left). The numbering differs from that of
create_grid_polygons_cached() and ensure_stable_poly_id(), which
sort cells by position; pass the result to ensure_stable_poly_id() for
IDs that do not depend on how the grid was built. Use one builder
throughout an analysis, since a summary keyed on the IDs of one drawn on
the cells of the other puts the values on the wrong cells.
See Also
Other cell building:
build_tessellation(),
clip_target_for(),
create_grid_polygons_cached(),
create_voronoi_polygons(),
ensure_stable_poly_id(),
get_voronoi_seeds(),
plot_tessellation_map(),
voronoi_seeds_kmeans(),
voronoi_seeds_random()
Examples
library(sf)
bnd <- st_sf(geometry = st_sfc(st_polygon(list(rbind(
c(0, 0), c(100, 0), c(100, 100), c(0, 100), c(0, 0)
))), crs = 32632))
grid_sq <- create_grid_polygons(bnd, target_cells = 100, type = "square")
grid_hex <- create_grid_polygons(bnd, target_cells = 100, type = "hex")
nrow(grid_sq)
# The hex count runs above the target: clipping keeps every hexagon that
# overhangs the boundary, and that adds more, in proportion, at a small
# target_cells.
nrow(grid_hex)
Create and cache grid polygons over a boundary
Description
Builds a grid with create_grid_polygons(), gives it stable IDs with
ensure_stable_poly_id(), and keeps it, so a repeat call with the same
arguments returns the kept grid.
Usage
create_grid_polygons_cached(
boundary,
target_cells = NULL,
type = c("square", "hex"),
...,
cache_env = .gmt_cache,
max_entries = 50L
)
Arguments
boundary |
An sf or sfc polygonal object. One that mixes XY and XYZ
(or XYM) geometries, or whose geometries carry M (XYM or XYZM), is read
without Z and M, as in |
target_cells |
Approximate desired number of cells, or what
|
type |
Grid type: |
... |
Further arguments to |
cache_env |
Environment the grids are kept in. The default is the
package's own cache, which |
max_entries |
Maximum number of grids the cache holds. Default 50.
Once full, adding a grid evicts the one added earliest, so a loop over
many boundaries holds at most this many grids (about 2 MB per 2,500-cell
grid) rather than every grid it ever built for the life of the session.
|
Details
A grid returned in degrees (a geographic crs passed through ...) is
cached once per sf::sf_use_s2() setting: a grid laid in degrees is
clipped by s2 with the setting on and by GEOS with it off, and
ensure_stable_poly_id() rebuilds the cells s2 or GEOS calls invalid
with s2's rebuild with the setting on and repairs every cell with GEOS with it off,
so the grid differs between the two settings. A call is handed the grid
of the session's setting. A grid laid and returned in a
projected CRS is clipped and repaired by GEOS under either setting and is
cached once.
Value
An sf data frame with a stable poly_id column. The rows are
re-ordered and re-numbered by ensure_stable_poly_id(), which
create_grid_polygons() does not do: the same cell therefore carries a
different poly_id depending on which of the two builders produced
it. Use one builder throughout an analysis; joining a
summary keyed on IDs from one onto geometries from the other draws the
values on the wrong polygons.
See Also
clear_grid_cache() to empty the cache.
Other cell building:
build_tessellation(),
clip_target_for(),
create_grid_polygons(),
create_voronoi_polygons(),
ensure_stable_poly_id(),
get_voronoi_seeds(),
plot_tessellation_map(),
voronoi_seeds_kmeans(),
voronoi_seeds_random()
Examples
library(sf)
bnd <- st_sf(geometry = st_sfc(st_polygon(list(rbind(
c(0, 0), c(100, 0), c(100, 100), c(0, 100), c(0, 0)
))), crs = 32632))
g <- create_grid_polygons_cached(bnd, target_cells = 16, type = "hex")
# 27, not 16: clipping keeps every hexagon that overhangs the boundary,
# which adds more at a small target (see ?create_grid_polygons)
nrow(g)
# The IDs come from ensure_stable_poly_id(), so they follow the geometry:
# the same request with the boundary's vertices in another order gives the
# same ID to the same cell.
bnd2 <- st_sf(geometry = st_sfc(st_polygon(list(rbind(
c(100, 100), c(0, 100), c(0, 0), c(100, 0), c(100, 100)
))), crs = 32632))
g2 <- create_grid_polygons_cached(bnd2, target_cells = 16, type = "hex")
same_cell <- match(st_as_text(st_geometry(g2)), st_as_text(st_geometry(g)))
all(g2$poly_id == g$poly_id[same_cell])
Build Voronoi cells around points
Description
Gives every location in the study area to its nearest input point, so
each point gets one cell. Use it when the observations themselves define
the cells (sampling sites, monitoring stations, service points): cell size
then follows sampling density, with small cells where the points are dense
and large ones where they are sparse. Use create_grid_polygons() instead
for equal-area cells, or for a resolution that does not depend on where
the data are.
Usage
create_voronoi_polygons(
points_sf,
boundary = NULL,
expand = 0,
clip = TRUE,
keep_duplicates = FALSE,
crs = NULL,
quiet = FALSE,
cover = NULL
)
Arguments
points_sf |
An sf object with POINT/MULTIPOINT geometries. Points with
no CRS whose coordinates look like lon/lat (the heuristic
|
boundary |
Optional polygonal sf object. When exactly one of
|
expand |
Numeric; absolute distance, in the working CRS's units, by
which the boundary (or the hull derived from the points) is grown before
the diagram is built. With |
clip |
Logical; clip the cells to the boundary. Default |
keep_duplicates |
Logical. With |
crs |
Optional target CRS: anything |
quiet |
Logical; suppress this function's progress |
cover |
Optional sf or sfc layer the cells have to hold, read when
there is no |
Details
sf::st_voronoi() builds the diagram. This function projects lon/lat
input, builds and buffers an envelope so edge cells are bounded, clips to
boundary, restores the point-to-cell correspondence that st_voronoi()
scrambles, and numbers the cells with stable cell_id values.
The generators are the points' vertices, not the features. A MULTIPOINT
feature with several vertices therefore gets one cell per vertex, and its
index entry is the smallest cell_id among the cells it touches; the
others are referenced by no feature. Other functions in the package
(prep_model_data(), make_folds()) reduce such a feature to its
centroid instead, so cast to POINT, or take centroids, first if one cell
per feature is what you want.
With no boundary the cells are clipped to a boundary derived from the
data. For observations that is their own convex hull grown by 2 percent of
its diagonal, so every observation has a cell. Seeds are different: k-means
centres, random points in a study area and the centres a resolution
profile scored all lie inside the ground they stand for, and cells clipped
to the hull of the seeds leave the edge of that ground uncovered. The
boundary is therefore derived from the cover when
there is one: the argument, or the cover the seeding functions attach to
their result. A layer that looks like seeds and has neither a boundary nor
a cover (seeds bound with rbind(), which drops the attribute, or built
by hand) gets the seeds' own hull and a warning of class
"spatialkit_no_cover".
A seed stands for its cell, so index gives each seed the cell it
generates. A k-means seed is a mean of observations and can lie outside a
boundary that is not convex, in a bay or a bend of a coast (see
get_voronoi_seeds()). Its cell, the part of the study area nearer it
than any other seed, is built, and its index entry is that cell's
cell_id, although the seed lies in no cell. A seed is NA only when
every part of the study area is nearer another seed, so the clip removed
its cell whole, or when it has no location (its geometry is empty, or a
coordinate is not finite or lies beyond 1e150). The points are seeds when
a seeding function returned them (get_voronoi_seeds(),
voronoi_seeds_kmeans(), voronoi_seeds_random(), rbind() of such
layers included), when they are the seeds of a select_resolution()
result, and when a cover is passed with them. A selection's seeds are
seeds by the attributes they carry, which rbind() and a write to a file
drop. Any other points are indexed by the cell that holds them, so a
point outside the study area is NA, unless it lies within a thousandth
of the median cell width of a cell, whose ID it then takes (see index
in build_tessellation()); that includes observations that
carry a selection's record of the count, as
assign_features_to_polygons() returns them. Seeds placed by hand, and
a selection's seeds that lost their attributes, are seeds once they pass
through get_voronoi_seeds(method = "provided", seeds = ).
Value
A list with these elements:
cellsThe cells, one polygon per unique point, with a stable
cell_id.indexOne
cell_idper row ofpoints_sf, andNAfor a point that falls outside every cell: outside the study area (grown byexpandwhen it is positive), and farther than a thousandth of the median cell width from the nearest cell, so a summary built from it counts only the points the tessellation covers. Such points are counted inparams$n_outside, and a warning of class"spatialkit_unassigned"gives their number. For seeds (see "Details")indexholds the cell each seed generates, whether the seed lies inside the boundary or not, andNAonly for a seed whose cell the clip removed whole or without a location (an empty geometry, or a coordinate that is not finite or lies beyond 1e150);params$n_outsidecounts those, the warning names them as seeds, andparams$snappedlists only the seeds whose entry is the cell they were snapped to.boundaryThe boundary the cells were built in: the one supplied or derived, grown by
expand.method"voronoi".paramsThe settings and diagnostics of the build, among them:
-
boundary_source: where the boundary came from,"boundary"(the argument),"cover"(thecoverargument),"seeds' cover"(the cover attached topoints_sf) or"points"(the hull ofpoints_sfitself); -
cover_outside: the number ofcoverpoints outside every cell when a pointcoverwas given with aboundary, andNULLotherwise; -
partition: present whenpoints_sfis a layer of seeds that records the kind of partition that placed it (attr(points_sf, "partition"), seeget_voronoi_seeds()), the same list, so the cells say what built them. Seeds of plain k-means record nothing, andparamsthen has no such element; neither has it for points that are not seeds; -
count_rule: present whenpoints_sfcarries the record of how its count was set (attr(points_sf, "count_rule"): the seeds of aselect_resolution()result, or seeds a seeding function placed from one), the same list, withscored_cells = FALSEwhen the seeds are fewer or more than its count. The cells carry it too, asattr(cells, "count_rule");assign_features_to_polygons()copies it to the rows it assigns, andsummarize_by_cell()checks its result against it.
-
Seeds a profile scored
The seeds of a select_resolution() result, and the seeds
get_voronoi_seeds() or voronoi_seeds_kmeans() return for one, are the
centres resolution_profile() scored, and their record of the count
(attr(, "count_rule")) says so (scored_cells = TRUE) and holds the
centres in the CRS the profile worked in. (On a profile without an
estimate fitted to a subsample the seeds are those centres refitted to
every point, which carry attr(, "refit"); their record says
scored_cells = FALSE, and their cells are built as other seeds' are.
So are seeds fewer or more than the record's count, such as a
selection's seeds cut down to some of its rows: they are not the centres
the profile scored, and their record is handed on with
scored_cells = FALSE, as get_voronoi_seeds() (method = "provided")
marks such seeds.)
Unless a projected crs is
given, their cells are built in that CRS, whatever CRS the seeds arrive
in (degrees, or the CRS of a boundary they were placed in), and returned
in it, or in a geographic crs when one is given. When the seeds are
those centres (as many, each at a different centre, within a thousandth
of its distance from the next nearest), each is first put at its centre
as the record holds it, so rounding the seeds took on in another CRS
does not move an edge. The cells are then the cells each row was scored
in, and assign_features_to_polygons() gives a point on an edge between
two of them the cell the profile scored it in.
Points far from the origin of their CRS
Points so far from the origin of their CRS that doubles there are spaced
more than a millionth of their extent apart (0.125 at 1e15, beside a layer
a few kilometres across) have the cells' edges and their own cells read
at that rounding, so two points that close can fall in one cell. The
cells are built, and a warning of class "spatialkit_xy_imprecise"
gives the spacing and the extent.
See Also
Other cell building:
build_tessellation(),
clip_target_for(),
create_grid_polygons(),
create_grid_polygons_cached(),
ensure_stable_poly_id(),
get_voronoi_seeds(),
plot_tessellation_map(),
voronoi_seeds_kmeans(),
voronoi_seeds_random()
Examples
library(sf)
set.seed(1)
pts <- st_as_sf(
data.frame(x = 5e5 + runif(15, 0, 100), y = 5e6 + runif(15, 0, 100)),
coords = c("x", "y"), crs = 32632
)
res <- create_voronoi_polygons(pts, quiet = TRUE)
res$cells # one polygon per unique point, with stable cell_id
res$index # cell_id assignment for each input point
Cross-validate a Bayesian GP with spatial folds
Description
Refits the Gaussian-process model of fit_bayesian_spatial_model() on
each training fold and scores it on the held-out fold. Besides the
point-prediction metrics the other cv_*() functions report, it scores
the whole predictive distribution: predictive_coverage gives the share of
held-out observations inside the 50, 80 and 95 percent intervals, and
mean_CRPS rates sharpness and calibration together. A Bayesian model is
often chosen for its uncertainty, and held-out coverage shows whether
those intervals are honest at locations the model has not seen.
Usage
cv_bayes(
data_sf,
response_var,
predictor_vars,
folds = NULL,
k = 5,
seed = 123,
boundary = NULL,
pointize = "auto",
fit_args = list(),
summary = c("mean", "median"),
compute_pred_intervals = TRUE,
coverage_levels = c(0.5, 0.8, 0.95),
block_size = NULL,
auto_range = FALSE,
parallel = FALSE,
metrics = NULL
)
Arguments
data_sf |
An sf layer with the response and the predictors. |
response_var |
Name of the response column. |
predictor_vars |
Character vector of predictor column names. |
folds |
Optional fold definitions, in one of three shapes: a
|
k |
Number of folds to build when |
seed |
Seed for building the folds when |
boundary |
Optional polygon layer (sf or sfc). Data without a CRS are
aligned to it, and the blocks built when |
pointize |
How a feature that is not a point is reduced to one before
fitting: a mode of |
fit_args |
Named list of extra arguments for
|
summary |
|
compute_pred_intervals |
Logical, default |
coverage_levels |
Numeric vector of the nominal coverage levels to
score, as proportions strictly between 0 and 1 ( |
block_size |
Optional minimum block edge length, in the units of the
CRS the folds are built in, for the blocks built when |
auto_range |
Logical, default |
parallel |
Logical or positive integer. |
metrics |
Optional scoring function of your own, a
|
Details
Every fold is a full MCMC run, so this is the slowest of the cv_*()
functions. Use few folds, and parallel = TRUE if you have the cores.
For a quicker first pass on the same question, cross-validate a random
forest with cv_rf() and come back here once the predictor set has
settled.
Value
A list with the elements cv_spatial() returns (overall,
fold_metrics, predictions, folds, n_folds_attempted,
n_folds_succeeded, fold_status, orphan_rows, n_unknown_ids and
n_dropped; see its Value for each, and for the five fold statuses),
plus:
formulaThe model formula, as text.
predictive_coverageOne entry per
coverage_levelsvalue, plusmean_CRPS: averages across folds weighted by each fold'sn_pred. The per-fold values infold_metricsare means over that fold's test rows, so an unweighted average would not be the pooled quantity when fold sizes differ, as they do for spatial blocks.coverage_levelsThe nominal levels, named by their
coverage_*column.
fold_status keeps the error text of a fold whose sampler failed.
predictions also carries yhat_sd, the posterior predictive standard
deviation of each held-out row, from the same draws that give the
coverage (NA when compute_pred_intervals = FALSE or the draws failed
for that fold). overall$Adj_R2 is always NA, as for every
cv_*().
fold_metrics also carries gp_k, gp_n_basis, n_draws, CRPS, the
coverage_* columns, convergence_ok and gp_adequacy.
convergence_ok is TRUE or FALSE as fit_bayesian_spatial_model()
judged that fold's sampler (divergent transitions, R-hat, effective
sample size and E-BFMI; see its check_convergence), and NA when
fit_args sets check_convergence = FALSE. A fold that did not
converge is scored like the others, so a run with any FALSE raises one
warning of class spatialkit_convergence naming those folds and the
checks each failed. gp_adequacy is what that fold's posterior said
about its Gaussian-process basis ("ok", "below_resolution",
"unresolved_short_range", "no_signal_above_floor" or
"not_checked"; see "What the basis resolves" in
fit_bayesian_spatial_model()). A fold whose basis was found too
coarse is scored like the others too; see the section "Warnings from the
folds".
Warnings from the folds
fit_bayesian_spatial_model() warns about a fit under four condition
classes: spatialkit_gp_basis_size, spatialkit_gp_resolution,
spatialkit_convergence and spatialkit_gp_adequacy (see its section
"Warnings"). Each fold is a fit, and none of those warnings says which
fold it came from, so they are collected as the folds run and each class is
raised once after the last fold, under this function's name and with the
same class. Each warning names the folds and carries folds (their
labels) and fold_messages (every fold's own text, named by fold) as
fields of the condition. The convergence warning covers the folds that
were scored and gives the checks each failed, also as the field failed;
the other three quote the first fold's own text. Each fold's own line is
in the log. Warnings that Stan or brms raise themselves are not
collected and are passed on.
Percentage errors on responses with zeros
MAPE divides by the observed value and SMAPE by
|y| + |\hat{y}|, so neither is defined where its denominator is zero.
Neither returns Inf or NaN. Both are averaged over the rows
whose denominator is non-zero, and are NA when no row qualifies.
Non-zero is judged at the scale of the data: a denominator no larger
than 100 machine epsilons times the largest one counts as zero, so the
rule does not depend on the units of the response.
The n_MAPE and n_SMAPE columns record how many rows that was;
the n column (n_pred in a cross-validation result) counts
finite observation/prediction pairs. Read a percentage error next to that
count: when n_MAPE is smaller, MAPE is an average over a
subset of the data, whatever its value.
Any response taking exact zeros is affected: counts, rainfall, abundance,
claim amounts. On a zero-inflated response with 62 zeros out of 120,
MAPE averages the 58 non-zero rows and n_MAPE is 58.
SMAPE drops the rows where observation and prediction are both
near zero, which on a well-fitted zero-inflated model are the rows it got
right, so it averages the harder rows only and reads worse than the fit
deserves. n_SMAPE shows how many rows it kept; it does not correct
the average.
RMSE, MAE and R^2 use every finite row; prefer them
whenever the response can be zero. For a Bayesian GP fit,
cv_bayes() also reports CRPS and interval coverage, which
are proper scoring rules and are defined at zero.
Which metrics survive a non-Gaussian response
RMSE and MAE are defined for any numeric response and are what to read for
a count, a rate or a bounded outcome. MAPE and SMAPE assume a response
that is rarely zero (see "Percentage errors on responses with zeros"), and
R^2 and adjusted R^2 compare residual variance to total
variance, which suits a Gaussian response and fits loosely anything whose
variance tracks its mean. On a Poisson or zero-inflated response read the
four as a rough summary rather than a score.
For the Bayesian GP, cv_bayes() also reports CRPS and
interval coverage at its coverage_levels (50, 80 and 95 percent by
default). Both are proper scoring rules computed from posterior draws, so
they are meaningful for any family that predicts one number per row
(a count, a rate, a binary or bounded outcome), and they are the numbers
to compare when the response is not Gaussian. A categorical or ordinal
family predicts a probability per response category instead, so
cv_bayes() refuses one before fitting anything. When every fold
fails, the fold_metrics frame cv_bayes() returns carries
the CRPS column but not the coverage_* columns, so code that
reads those columns must allow for their absence.
See Also
Other cross-validation:
compare_models_cv(),
cv_gwr(),
cv_rf(),
cv_spatial(),
plot_calibration(),
plot_cv_metrics()
Examples
## Not run:
# Not run: fits with Stan, which needs a working C++ toolchain and takes
# minutes of MCMC.
library(sf)
set.seed(1)
n <- 60
dat <- st_as_sf(
data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
elev = rnorm(n)),
coords = c("x", "y"), crs = 32632
)
dat$price <- 10 + 0.01 * (st_coordinates(dat)[, 1] - 5e5) +
2 * dat$elev + rnorm(n)
# Two short chains per fold keep this to a few minutes and leave the
# posterior rough, so the intervals below will run narrow; a run to
# report uses the defaults of brms (chains = 4, iter = 2000).
cv <- cv_bayes(dat, "price", "elev", k = 2,
fit_args = list(chains = 2, iter = 1000))
cv$overall
cv$predictive_coverage # coverage at 50, 80 and 95 percent, and mean CRPS
## End(Not run)
Cross-validate at a ladder of block sizes
Description
Runs cv_spatial() once per block size on a ladder of sizes, and by
default once with random folds as the reference, whose held-out points keep
most of their neighbours in the training data. It returns the pooled
metric and its fold-to-fold spread at each size, with the estimated
autocorrelation range alongside. The wider the blocks, the farther the
held-out points sit from their training data. The rise of the curve with
block size measures the error at that distance from the data: how much
worse the model predicts a location the farther it lies from the
observations. It is the error of a map only at locations that far from
the data, so the curve does not by itself say which size to report. The
size to read is the one whose held-out distances match those of the
locations the model will predict at: fold_separation() with
prediction_points reads the folds of each size (the $folds of each
element of attr(x, "results")) against them.
Usage
cv_block_size_sweep(
data_sf,
response_var,
predictor_vars,
fit_fn,
block_sizes = NULL,
n_sizes = 6L,
k = 5L,
metric = "RMSE",
include_random = TRUE,
max_fits = 60L,
sac = NULL,
seed = 123L,
quiet = FALSE,
...
)
## S3 method for class 'block_size_sweep'
plot(x, ...)
Arguments
data_sf |
An sf layer with the response and the predictors. |
response_var |
Name of the response column. |
predictor_vars |
Character vector of predictor column names. |
fit_fn |
A |
block_sizes |
Optional numeric vector of block edge lengths to sweep,
in the units of the CRS the folds are built in (plain numbers; a |
n_sizes |
Number of sizes in the default ladder. Default 6. |
k |
Folds per cross-validation. Default 5. |
metric |
Which column of |
include_random |
Also cross-validate with random folds, as the
reference: the error of predicting among the samples, where each
held-out point keeps most of its neighbours in the training data.
Default |
max_fits |
The most model fits the sweep may run, the random reference included; a sweep that needs more refuses to start. Default 60. See the section "The fit budget". |
sac |
Optional |
seed |
Seed for the folds at every size, for each |
quiet |
Suppress the progress messages. Default |
... |
For |
x |
A |
Value
A data.frame of class "block_size_sweep" with one row per
cross-validation: block_size (NA for the random reference),
method, blocks_used, k (the folds built), n_folds_succeeded,
value (the pooled metric), fold_min, fold_max and fold_sd (its
spread across folds), and block_width and block_height (the width and
height of the grid cells built at that size, NA for the random
reference). Attributes: metric, sac_range (the effective range, or
NA), crs, k (the folds requested, which print() and plot()
report), n_fits (the fits planned, which the max_fits check reads;
print() and plot() count the fits made from the k column),
response_var, and results, the full cv_spatial() result at every
size.
plot() returns a ggplot object (see the section "The plot").
The fit budget
Each block size is a full cross-validation, so the cost is
length(block_sizes) * k fits, plus k for the random reference.
max_fits caps that (default 60: room for up to eleven sizes at k = 5
plus the reference; the default six-size ladder at k = 5 needs at most
35). A sweep that would run past the cap refuses to start, naming the
number of fits it would have needed; lower n_sizes or k to cut it
(with block_sizes supplied: pass fewer block_sizes or a smaller k),
or pass include_random = FALSE when the count includes the reference.
The random forest of the example takes seconds; a Bayesian fit_fn takes
minutes per fit, so raise max_fits with that in mind.
The ladder
When block_sizes is NULL, n_sizes values are log-spaced from a
twenty-fifth of the shorter side of the data's extent (of the longer side
when the points lie on one line parallel to an axis) to the largest size,
at most half that side, at which the grid still holds k blocks. Half
the side gives a grid two blocks across, enough for k up to 4 and, for
larger k, on an extent long enough in the other direction; on a roughly
square extent at the default k = 5 the top is about a third of the side.
Any size at which the grid would hold more than the 1,000,000 blocks
make_folds() will build is dropped; when that drops every size, the
sweep refuses and names the largest size whose grid holds k blocks, to
pass as block_sizes. The count is of grid cells: on clustered data a
grid of k or more cells can have fewer than k that hold points, and
make_folds() then lowers k at that size, which the k column shows;
the sweep warns once, naming the sizes. On an extent much longer than it
is wide every rung can fall below the autocorrelation range while longer
blocks would still fit k times along the longer side; the sweep warns
when that happens, and block_sizes is then the way to reach past the
range.
Sizes are in the units of the CRS the folds are built in (the
params$crs of make_folds(), metres for lon/lat input), and the
returned table records that CRS. Each is the minimum block edge handed to
make_folds(), which fits a whole number of cells across each axis of the
extent, so on an axis at least as long as the size the cells are somewhat
longer than it (up to just under twice as long). An axis shorter than the
size is spanned by one row or column of cells, which are then shorter than
the size there. The block_width and block_height columns give the
cells built at each size.
Warnings raised once for the sweep
Every size is a cv_spatial() on the same layer. The warnings
prep_model_data() raises about that layer (class
spatialkit_rows_dropped, counting the incomplete rows dropped, and
spatialkit_constant_predictor) are raised once, not once per size. With
a GWR learner, the two warnings in which predict() counts held-out
locations ("spatialkit_gwr_not_estimable" and
"spatialkit_gwr_extrapolation") are raised once each, under this
function's name, with the totals over every size; the same rows are
predicted at every size, so a location can be counted once per size (see
predict.gwr_fit()).
The plot
plot() draws the curve as a ggplot2 object: the pooled metric at
each block size asked for, the fold-to-fold range as a band, the
random-fold reference as a dashed line, and the estimated autocorrelation
range as a dotted vertical line. The curve rises as the blocks widen
because the held-out points sit farther from their training data: its
height at a size is the error at that distance from the data, and the
error of a map only where the locations it predicts at sit that far from
the observations. The caption says which way is better: higher for R2
and Adj_R2, closer to the nominal level for a coverage_* column (0.975
for coverage_97.5), since over-coverage is miscalibration too, and lower
for everything else. print() shows the same results as a table.
See Also
fold_separation() to read the folds of each size against the
locations a map will predict at, and make_folds() for the blocks.
Other folds:
fold_separation(),
make_folds(),
plot_folds()
Examples
library(sf)
set.seed(1)
n <- 200
x <- 5e5 + runif(n, 0, 1000); y <- 5e6 + runif(n, 0, 1000)
d <- as.matrix(dist(cbind(x, y)))
field <- as.numeric(t(chol(exp(-d / 100) + diag(1e-6, n))) %*% rnorm(n))
dat <- st_as_sf(data.frame(x = x, y = y, a = rnorm(n)), coords = c("x", "y"),
crs = 32632)
dat$z <- field + 0.5 * dat$a + rnorm(n, 0, 0.2)
rf_fn <- function(train_sf)
fit_rf_model(train_sf, "z", "a", include_coords = TRUE, num_trees = 100,
seed = 1)
sw <- cv_block_size_sweep(dat, "z", "a", fit_fn = rf_fn, k = 4, n_sizes = 4,
quiet = TRUE)
sw # the curve as a table, with the random-fold reference
# Dashed: the random-fold reference. Dotted: the estimated
# autocorrelation range.
if (requireNamespace("ggplot2", quietly = TRUE)) plot(sw)
Cross-validate a GWR with spatial folds
Description
Refits a geographically weighted regression from scratch on each training
fold and scores it on the held-out fold, so the reported error is the
model's at locations it did not see. Use it for an accuracy figure for a
GWR: the in-sample R^2 that model_metrics() reports on a
gwr_fit says little, because a local regression with a small bandwidth
can track the training points almost exactly. The bandwidth is selected
again in each fold unless bandwidth fixes it, so the selection itself is
inside the cross-validation, with no tuning on the full data first.
Usage
cv_gwr(
data_sf,
response_var,
predictor_vars,
folds = NULL,
k = 5,
seed = 123,
adaptive = TRUE,
bandwidth = NULL,
kernel = c("bisquare", "gaussian", "tricube", "boxcar", "exponential"),
boundary = NULL,
pointize = "auto",
block_size = NULL,
auto_range = FALSE,
parallel = FALSE,
metrics = NULL
)
Arguments
data_sf |
An sf layer with the response and the predictors. |
response_var |
Name of the response column. |
predictor_vars |
Character vector of predictor column names. |
folds |
Optional fold definitions, in one of three shapes: a
|
k |
Number of folds to build when |
seed |
Seed for building the folds when |
adaptive |
Logical; use an adaptive bandwidth, a number of
neighbours, rather than a fixed distance. Default |
bandwidth |
Optional bandwidth, applied to every fold. For
|
kernel |
The kernel that weights each location's neighbours:
|
boundary |
Optional polygon layer (sf or sfc). Data without a CRS are
aligned to it, and the blocks built when |
pointize |
How a feature that is not a point is reduced to one before
fitting: a mode of |
block_size |
Optional minimum block edge length, in the units of the
CRS the folds are built in, for the blocks built when |
auto_range |
Logical, default |
parallel |
Accepted so that every |
metrics |
Optional scoring function of your own, a
|
Details
Folds default to spatial blocks (make_folds(method = "block_kfold")),
not random ones. A random split leaves a held-out point's neighbours in
the training set, so its score is the error of predicting among the
samples; blocks hold out whole areas, and folds says what their score
estimates. Use cv_bayes() for the same treatment of a Bayesian GP,
cv_rf() for a random forest, and compare_models_cv() to score several
backends on one set of folds.
Value
A list with the elements cv_spatial() returns (overall,
fold_metrics, predictions, folds, n_folds_attempted,
n_folds_succeeded, fold_status, orphan_rows, n_unknown_ids and
n_dropped; see its Value for each, and for the five fold statuses),
plus:
formulaThe model formula, as text.
adaptiveWhether the bandwidth was adaptive.
fold_metrics also carries each fold's bandwidth. Adj_R2 is NA in
both overall and fold_metrics: the pooled predictions have no single
parameter count, and a GWR's effective parameter count is not its
predictor count.
A held-out location whose local regression cannot be estimated has
yhat NA, and one beyond the reach of its fold's fit is predicted and
scored; each case raises one warning for the whole run (classes
"spatialkit_gwr_not_estimable" and "spatialkit_gwr_extrapolation"),
with the totals over the folds that had any. See predict.gwr_fit().
Where a fold's fit took the response about a centre (a response at a
large offset; see fit_gwr_model()), predictions also carries
y_centre (that centre, 0 in the rows of a fold fitted on the raw
response), yhat_centred and y_train_mean_centred (yhat and
y_train_mean less the centre, which keep digits that rounding at the
response's size would lose), and the metrics are those of the centred values, as
model_metrics() computes them.
Percentage errors on responses with zeros
MAPE divides by the observed value and SMAPE by
|y| + |\hat{y}|, so neither is defined where its denominator is zero.
Neither returns Inf or NaN. Both are averaged over the rows
whose denominator is non-zero, and are NA when no row qualifies.
Non-zero is judged at the scale of the data: a denominator no larger
than 100 machine epsilons times the largest one counts as zero, so the
rule does not depend on the units of the response.
The n_MAPE and n_SMAPE columns record how many rows that was;
the n column (n_pred in a cross-validation result) counts
finite observation/prediction pairs. Read a percentage error next to that
count: when n_MAPE is smaller, MAPE is an average over a
subset of the data, whatever its value.
Any response taking exact zeros is affected: counts, rainfall, abundance,
claim amounts. On a zero-inflated response with 62 zeros out of 120,
MAPE averages the 58 non-zero rows and n_MAPE is 58.
SMAPE drops the rows where observation and prediction are both
near zero, which on a well-fitted zero-inflated model are the rows it got
right, so it averages the harder rows only and reads worse than the fit
deserves. n_SMAPE shows how many rows it kept; it does not correct
the average.
RMSE, MAE and R^2 use every finite row; prefer them
whenever the response can be zero. For a Bayesian GP fit,
cv_bayes() also reports CRPS and interval coverage, which
are proper scoring rules and are defined at zero.
See Also
Other cross-validation:
compare_models_cv(),
cv_bayes(),
cv_rf(),
cv_spatial(),
plot_calibration(),
plot_cv_metrics()
Examples
library(sf)
set.seed(1)
n <- 60
dat <- st_as_sf(
data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
elev = rnorm(n)),
coords = c("x", "y"), crs = 32632
)
dat$price <- 10 + 0.01 * (st_coordinates(dat)[, 1] - 5e5) +
2 * dat$elev + rnorm(n)
cv <- cv_gwr(dat, "price", "elev", k = 3, bandwidth = 30)
cv$overall # pooled over the held-out rows of every fold
cv$fold_metrics # and fold by fold
Cross-validate a random forest with spatial folds
Description
A wrapper over cv_spatial() that refits a ranger
forest on each training fold. By default it holds out whole spatial
blocks, so most neighbours of a held-out point are not in the training
set; the forest's out-of-bag error holds out single rows. The folds you
pass decide what the score measures (see "Fold methods" in
make_folds()).
Usage
cv_rf(
data_sf,
response_var,
predictor_vars,
folds = NULL,
k = 5,
seed = 123,
parallel = FALSE,
block_size = NULL,
auto_range = FALSE,
boundary = NULL,
pointize = "auto",
metrics = NULL,
...
)
Arguments
data_sf |
An sf object. |
response_var |
Response column name. |
predictor_vars |
Predictor column names. |
folds |
Optional fold definitions, in any of three shapes: a
|
k |
Number of folds when |
seed |
RNG seed. Default 123. It seeds fold construction and,
through a per-fold draw, each fold's forest, so two different seeds give
different results even on identical |
parallel |
Passed to |
block_size, auto_range, boundary |
Passed to |
pointize |
How non-POINT geometry is reduced to a point before
fitting; passed to |
metrics |
Optional scoring function of your own, passed to
|
... |
Passed to |
Value
The cv_spatial() result. MAPE and
SMAPE skip rows whose denominator is zero; n_MAPE and
n_SMAPE count the rows they used (see "Percentage errors on
responses with zeros" in model_metrics()).
Comparing the forest with and without coordinates
Whether include_coords = TRUE lowers the error depends on how far
from the training data the predictions are (see "Coordinates as
predictors" in fit_rf_model), so it is a comparison to make
on your own data, at the block size the map will be used at. Score the
two forests on the same folds: build the folds once with
make_folds and pass the result as folds to two
calls, one with include_coords = TRUE and one without. Each fold
then holds out the same rows in both, so the two overall rows
compare like with like and the two fold_metrics tables pair up
fold by fold. A difference in overall that is small beside the
spread of the per-fold differences is not evidence for either forest.
The example below runs the comparison. compare_models_cv()
takes one set of forest arguments (rf_args) per call, so it scores
only one of the two forests.
See Also
fit_rf_model() for the forest's arguments, and
plot_cv_metrics() to draw the per-fold scores.
Other cross-validation:
compare_models_cv(),
cv_bayes(),
cv_gwr(),
cv_spatial(),
plot_calibration(),
plot_cv_metrics()
Examples
library(sf)
set.seed(1)
n <- 200
dat <- st_as_sf(
data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
a = rnorm(n)),
coords = c("x", "y"), crs = 32632
)
# An offset keeps the response away from zero, where MAPE is undefined.
dat$z <- 10 + 2 * dat$a + rnorm(n, 0, 0.3)
cv_rf(dat, "z", "a", k = 4)$overall
# The forest with and without the coordinates, on the same blocked
# folds. The second call logs the include_coords caution once per
# session. This response has no spatial structure, so here the
# coordinates can only cost accuracy.
folds <- make_folds(dat, k = 4, method = "block_kfold", seed = 1)
plain <- cv_rf(dat, "z", "a", folds = folds, num_trees = 200)
with_xy <- cv_rf(dat, "z", "a", folds = folds, num_trees = 200,
include_coords = TRUE)
c(plain = plain$overall$RMSE, with_xy = with_xy$overall$RMSE)
# Fold by fold: positive where the coordinates lowered the error.
plain$fold_metrics$RMSE - with_xy$fold_metrics$RMSE
Cross-validate any learner with spatial folds
Description
You supply fit_fn(train_sf), which fits on one fold's training rows and
returns a spatial_fit; cv_spatial() builds or takes the folds, calls
fit_fn once per fold, predicts the held-out rows and returns pooled and
per-fold scores. cv_rf() is a wrapper over it.
Usage
cv_spatial(
data_sf,
response_var,
predictor_vars,
fit_fn,
folds = NULL,
k = 5,
seed = 123,
boundary = NULL,
pointize = "auto",
predict_args = list(),
fold_info_fn = NULL,
p = NULL,
block_size = NULL,
auto_range = FALSE,
parallel = FALSE,
metrics = NULL,
.caller = "cv_spatial"
)
Arguments
data_sf |
An sf layer with the response and the predictors. |
response_var |
Name of the response column. |
predictor_vars |
Character vector of predictor column names. |
fit_fn |
A function of one argument, the training slice of
|
folds |
Optional fold definitions, in one of three shapes: a
|
k |
Number of folds to build when |
seed |
Seed for building the folds when |
boundary |
Optional polygon layer (sf or sfc). Data without a CRS are
aligned to it, and the blocks built when |
pointize |
How a feature that is not a point is reduced to one before
fitting: a mode of |
predict_args |
A list of extra arguments for |
fold_info_fn |
Optional |
p |
Number of predictors for the per-fold adjusted
|
block_size |
Optional minimum block edge length, in the units of the
CRS the folds are built in, for the blocks built when |
auto_range |
Logical, default |
parallel |
Logical or positive integer. |
metrics |
Optional scoring function of your own; see the section
"Your own metrics". Default |
.caller |
For package wrappers; do not set it. |
Value
A list with:
overallOne row of metrics pooled over the held-out rows of every fold that produced predictions.
fold_metricsOne row per fold that produced predictions:
fold,n_train,n_test,n_pred, the metrics, and the columns offold_info_fnandmetrics.predictionsOne row per held-out row scored:
..row_id,fold,y,yhatandy_train_mean, the mean response of that fold's training rows.foldsThe splits as run, each with its
fold_id.n_folds_attempted,n_folds_succeededThe folds supplied (or built) and the folds scored. A
fit_fnthat fails on every fold otherwise looks like a run that scoredNA, so compare the two before readingoverall.fold_statusA data frame with one row per fold supplied:
fold,statusandmessage.statusis one of-
"ok":messageis empty unlessfold_info_fnfailed on the fold; -
"error": the fit or itspredict()threw, andmessageis the error text; -
"skipped": nothing to score (too few matched rows, a prediction of the wrong length, or no finite pair of observed and predicted values); -
"dropped": an empty test set, or fewer than two training rows once incomplete rows were removed, so the fold never reached the fitter; -
"worker_error": a parallel worker died, for example killed for lack of memory.
Every fold missing from
fold_metricshas its reason here, after the console output of a long run is gone.-
orphan_rowsThe
..row_ids of rows in the data that no fold names: they enter no training set and are never scored. It is empty unless the folds were built on a different or subsetted layer.n_unknown_idsThe number of distinct row IDs the folds name that the data do not have (expected when rows were removed for missing values). Each such row is named by every fold, once as a test row and once in each other fold's training set, and this counts the row, not the mentions.
n_droppedThe number of rows
prep_model_data()removed for missing or non-finite values or a bad geometry before any fold was fitted.
A failure costs that fold only: with parallel = TRUE each fold runs in
its own worker, and a sequential run catches the error per fold. An
error that stops a sequential run (a metrics or fold_info_fn return
value of the wrong shape) stops a parallel one too, naming the fold. When some folds, but not all, end as "error", "skipped" or
"worker_error", the function warns, naming them and how many rows
overall covers: it is pooled over the folds that produced predictions,
and the fold that fails is often the hardest to predict, so it may
flatter the model. A "dropped" fold has its own warning.
The fold column of fold_metrics, predictions and fold_status
carries the fold's index in the folds object that was supplied, so it
lines up with make_folds()$assignment$fold even when some folds were
unusable and dropped. Splits that already carry a fold_id, as the
folds of a cv_*() result do, keep it: handing one run's folds to
another labels each fold as the first run and fold_separation() do, a
dropped fold's gap included.
R2 is the out-of-sample R^2: the total sum of squares is
taken about the mean of the training rows (in overall, each held-out
row about its own fold's training mean), the null prediction available
when the fold is predicted, and not about the held-out rows' own mean,
a null model that would know the test data. On spatial blocks the two
can differ widely; R2 is below 0 when the model predicts worse than
the training mean. model_metrics(newdata = ) uses the same baseline.
overall$Adj_R2 is always NA: the pooled out-of-sample predictions
come from k separately fitted models and have no single parameter
count to adjust for. The per-fold fold_metrics$Adj_R2 carries the
adjusted value when p is supplied, and is NA otherwise. A fit_fn
that returns a gwr_fit of a response at a large offset gives
predictions the columns y_centre, yhat_centred and
y_train_mean_centred (see cv_gwr()).
Name collision with blockCV
The blockCV package exports a function of the same name that does
the opposite job: blockCV::cv_spatial() builds spatial folds, where this
function runs a cross-validation over folds it is given. With both
packages attached, whichever was attached last masks the other;
spatialkit::cv_spatial() always resolves to this one. The two work
together: blockCV::cv_spatial() returns its fold assignment as
$folds_ids, a vector of fold labels, and that vector is accepted as the
folds argument here and in every other cv_*() function.
Your own metrics
The built-in columns (RMSE, MAE, MAPE, SMAPE, R2, Adj_R2) are
the Gaussian regression set; see "Which metrics survive a non-Gaussian
response" in model_metrics() for which of them hold up on a count or a
bounded response. metrics scores what they cannot: a
function(y, yhat) that returns a named numeric vector (a named list of
scalars, or a one-row data frame, also serve), for example a Poisson
deviance, a log score on a probability, or a loss with your own weights.
It is applied twice, as the built-in metrics are: once per fold, to that
fold's held-out rows, so each name becomes a column of fold_metrics; and
once to the pooled out-of-sample predictions of every fold, so each name
becomes a column of overall. Only the pairs the built-in metrics use
reach the function (both y and yhat finite), so its columns describe
the same rows as RMSE, and n_pred counts them.
The contract: every element named, names unique and not one of the
built-in column names, one number per name. The built-in names include
the per-fold extras of the backend or of your fold_info_fn (bandwidth
for cv_gwr(); CRPS, coverage_*, gp_k, gp_n_basis and n_draws
for cv_bayes()), and mean_CRPS, which compare_models_cv() writes.
Anything else is an error, since a scoring function that returns the wrong
shape is a mistake to report, not a fold to skip. A function that throws
on a fold is logged and its columns are NA for that fold (and for
overall, if it throws on the pooled predictions); a fold is never
dropped for it. When no fold produced a prediction the empty
fold_metrics frame still carries the function's columns, typed, provided
the function can be called on zero-length input.
fold_info_fn is the per-fold half of the same mechanism, with access to
the fitted object and the held-out layer; metrics sees only the two
vectors but is also pooled. compare_models_cv() hands one metrics to
every backend, so the columns are comparable across the rows of its
overall.
Warnings a learner raises in every fold
A warning from a fold's fit or from its predict() reaches the caller as
it is raised, so a learner that warns in every fold warns once per fold.
Two groups of the package's own warnings are collected over the folds
instead and raised once per call, under this function's name and with the
class they had:
the two in which
predict()on a GWR counts locations ("spatialkit_gwr_not_estimable"and"spatialkit_gwr_extrapolation"), with the totals over the folds that had any, ascv_gwr()raises them (seepredict.gwr_fit());the four
fit_bayesian_spatial_model()raises about a fit, naming the folds, ascv_bayes()raises them (see the section "Warnings from the folds" there).
With parallel above one core a fold's warnings are raised after the folds
have run, once per distinct text; one of the package's own classes keeps
its class and its fields.
Percentage errors on responses with zeros
MAPE divides by the observed value and SMAPE by
|y| + |\hat{y}|, so neither is defined where its denominator is zero.
Neither returns Inf or NaN. Both are averaged over the rows
whose denominator is non-zero, and are NA when no row qualifies.
Non-zero is judged at the scale of the data: a denominator no larger
than 100 machine epsilons times the largest one counts as zero, so the
rule does not depend on the units of the response.
The n_MAPE and n_SMAPE columns record how many rows that was;
the n column (n_pred in a cross-validation result) counts
finite observation/prediction pairs. Read a percentage error next to that
count: when n_MAPE is smaller, MAPE is an average over a
subset of the data, whatever its value.
Any response taking exact zeros is affected: counts, rainfall, abundance,
claim amounts. On a zero-inflated response with 62 zeros out of 120,
MAPE averages the 58 non-zero rows and n_MAPE is 58.
SMAPE drops the rows where observation and prediction are both
near zero, which on a well-fitted zero-inflated model are the rows it got
right, so it averages the harder rows only and reads worse than the fit
deserves. n_SMAPE shows how many rows it kept; it does not correct
the average.
RMSE, MAE and R^2 use every finite row; prefer them
whenever the response can be zero. For a Bayesian GP fit,
cv_bayes() also reports CRPS and interval coverage, which
are proper scoring rules and are defined at zero.
See Also
new_spatial_fit() for the constructor a fit_fn must use;
cv_gwr(), cv_bayes() and cv_rf() for the built-in backends.
Other cross-validation:
compare_models_cv(),
cv_bayes(),
cv_gwr(),
cv_rf(),
plot_calibration(),
plot_cv_metrics()
Examples
library(sf)
set.seed(1)
n <- 80
site <- st_as_sf(
data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
elev = rnorm(n)),
coords = c("x", "y"), crs = 32632
)
site$price <- 10 + 0.01 * (st_coordinates(site)[, 1] - 5e5) +
2 * site$elev + rnorm(n)
# 1. A fit_fn returning a spatial_fit of your own subclass.
lm_fit <- function(train_sf) {
new_spatial_fit(
subclass = "lm_fit",
engine = lm(price ~ elev, st_drop_geometry(train_sf)),
formula = price ~ elev,
response_var = "price",
predictor_vars = "elev",
data_sf = train_sf
)
}
# 2. The predict() method cv_spatial() scores each fold with. Without it
# every fold fails and `overall` comes back all-NA.
predict.lm_fit <- function(object, newdata = NULL, ...) {
if (is.null(newdata)) newdata <- object$data_sf
as.numeric(stats::predict(object$engine, st_drop_geometry(newdata)))
}
registerS3method("predict", "lm_fit", predict.lm_fit)
cv <- cv_spatial(site, "price", "elev", fit_fn = lm_fit, k = 3, seed = 1)
cv$overall
# Compare these before reading the metrics above; fold_status says why
# any fold is missing from fold_metrics.
c(attempted = cv$n_folds_attempted, succeeded = cv$n_folds_succeeded)
cv$fold_status
# 3. A metric of your own beside the built-in ones: per fold and pooled.
med_ae <- function(y, yhat) c(MedAE = stats::median(abs(y - yhat)))
cv2 <- cv_spatial(site, "price", "elev", fit_fn = lm_fit, k = 3, seed = 1,
metrics = med_ae)
cv2$overall$MedAE
cv2$fold_metrics[, c("fold", "RMSE", "MedAE")]
Choose a cell count from the elbow of the k-means WSS curve
Description
Fits k-means to the coordinates at k = 1 to max_levels cells
and returns the count at the elbow of the within-cluster sum of squares
(WSS), read on log-log axes, with its two neighbours. Points with no
cluster structure have no elbow, and the result is then NA with a
warning. For a count chosen from the response, use
resolution_profile().
Usage
determine_optimal_levels(
data_sf,
max_levels = 12L,
top_n = 3L,
sample_n = 1500L,
set_seed = 123L,
response_var = NULL,
predictor_vars = NULL,
criterion = c("geometric", "morans_i", "combined"),
select_on = c("all", "split"),
on_no_elbow = c("na", "warn", "error")
)
Arguments
data_sf |
An sf object. Non-point geometries are reduced to points
with |
max_levels |
Integer upper bound on levels. Default 12. The sweep also stops at the number of distinct locations (k-means cannot place more centres) and one short of the number of points. |
top_n |
Integer; how many candidates to return. Default 3. Under
|
sample_n |
Integer; subsample size for speed. Default 1500. |
set_seed |
Integer RNG seed for the subsample and the k-means++ restarts; restored afterwards. Default 123. The rows are put in coordinate order before either, so the answer does not depend on the order they come in. |
response_var |
Name of the response column (numeric or logical), or
|
predictor_vars |
Optional predictor column names, read where
|
criterion |
One of |
select_on |
|
on_no_elbow |
What to do when the count is not a finding about the
data: the WSS curve has no elbow, the ladder is too short to show one,
or there are too few points or locations for a ladder at all. Each
choice raises a condition of class |
Value
An integer vector of candidate counts, best first:
"geometric"The elbow, then its lower and upper neighbours.
"morans_i"The candidates in the order of
|z|, with a warning of classspatialkit_diagnostic_ranking."combined"The candidates around the elbow in the order of the sag.
- No elbow
NA_integer_, with a warning of classspatialkit_no_elbow; underon_no_elbow = "warn", the ladder's choice and its neighbours, with the same warning. So it is when the ladder is too short to show an elbow (max_levelsof 1 or 2), and for a layer with fewer than three points or every point on one location, which has no ladder (1 under"warn"). A layer with no points is an error.
k[1] is the top-ranked count, or NA, on every path, and
top_n = 1 returns it alone. The vector can carry these
attributes:
structured,sagUnder the default
on_no_elbow = "na", on every result:structuredisTRUEwhen the WSS curve has an elbow andFALSEwith theNA, andsagis the curve's largest log-log sag. None under"warn"or"error". The geometric path carries no other attribute.diagnosticsUnder
"morans_i"and"combined": a list with per-kMoran's I (moran_i) and standardised deviates (moran_z), the WSS curve (wss) with the relative between-restart spread at eachk(wss_spread), the number of rising steps on it (wss_bumps), the restart budget (nstart), the elbow the scored neighbourhood was drawn around (knee_k), whether the WSS curve has an elbow (structured) and its largest log-log sag (sag), thekat which k-means failed (failed_k; theirwssentries are interpolated from the neighbours, not measured) and thekthe model-aware pass scored (eval_ks, the elbow's neighbourhood). Under"combined"it also carries the WSS of the re-run clustering at thosek(wss_eval, the clustering Moran's I is computed on; reported, not ranked on), the rank of the sag ofwssthat ordered them (combined_rank, named byk; with no elbow every candidate ties and the order is by distance fromknee_k) andcriterion = "combined". When"combined"returned the geometric ranking because the elbow is below ten cells, it carriescriterion = "geometric"andfallback(the reason) in place ofcombined_rank. TheNAthe default returns on a model-aware call whose WSS curve has no elbow (or a ladder too short to show one) carries the attribute too, with what the sweep measured:moran_iandmoran_zallNAandeval_ksempty, since no count was scored,knee_kthe count the chord rule lands on, andstructured = FALSE. Under"combined", Moran's I computable at no candidate of a neighbourhood that reaches ten cells leaves the attribute in place, withmoran_iandmoran_zallNA, and a logged warning says so. The attribute is absent when the model-aware path falls back to the geometric result (no viablekin the elbow's neighbourhood, a neighbourhood that ends at nine cells or fewer, or, under"morans_i", Moran's I computable at no candidate); these fallbacks are logged as warnings. It is absent too on theNAof a layer with no ladder (fewer than three points, one location, or k-means failing at everykfrom 2).splitWith
select_on = "split", on every path: a list withselectionandestimation(integer row positions indata_sf),methodandseed.
A rising WSS curve is logged on every path. For a per-level table of
criteria, cell support, restart spread and the flat region, see
resolution_profile().
How the elbow is read
Points with no cluster structure have a WSS curve close to c/k. The
classical rule, the point furthest below the chord from the first to the
last k, still finds a "knee" on such a curve on linear axes, at about
\sqrt{K_{max}}: 4 at the default max_levels = 12 and 13 at
160, whatever the data. On \log k against \log WSS that curve
is a straight line, while separated clusters fall faster than it until
there is one cell per cluster and like it after, a bend at the cluster
count. The elbow is therefore the k whose \log WSS sags
furthest below the straight line joining k = 1 and K_{max} on
those axes, and it counts as one only when the sag is at least
\log 1.25 (the WSS a fifth below the power law through the ends).
An elongated extent also bends, at about its aspect ratio, because the
first cuts go across its long axis; past the threshold that bend is
reported as an elbow, and it describes the shape of the extent rather
than clusters in it. When locations repeat (stations visited many
times), the sweep can reach one cell per distinct location, where the WSS
is zero (to within 10^{-12} of the total). That k has no
place on log axes and is left out of the line, but the fall to zero is
the sharpest bend there is: when the rest of the curve has no elbow, the
number of distinct locations is the elbow.
When there is no elbow
With no elbow the function returns NA, so that a count which is
not a finding is not passed on as one. The result carries
structured = FALSE and the largest sag as sag, and a
warning of class spatialkit_no_elbow says why. The count the
linear-axis rule gives there is the ladder's and not the data's: about
\sqrt{K_{max}}, 3 or 4 cells at the default, close to one mean for
the whole layer. The warning carries it as k and the largest sag
as sag. on_no_elbow = "warn" returns that count all the
same, with the same warning, and "error" stops.
Model-aware criteria
Under criterion = "morans_i" or "combined", with a
response_var, the elbow is supplemented with Moran's I of the cell
means at each candidate k: the cell means are regressed on the
cell-mean predictors (on an intercept alone when no
predictor_vars are given) and Moran's I is computed on the
residuals over each cell's 8 nearest cells. Under "geometric",
the default, response_var and predictor_vars are not read,
whether one or both are given.
Moran's I of the cell means tests whether neighbouring cells are independent. It does not measure the autocorrelation the cells leave unexplained in the response, and it does not say how well they represent it: on an autocorrelated response it grows as the cells get finer than the range, because neighbouring cells then resemble each other, and it is close to 0 at about 10 to 20 cells whatever the data, where the neighbour graph is nearly complete.
"morans_i" prefers the candidate with the smallest |z|: the
count at which neighbouring cell means stop resembling each other, cells
about as wide as the range. Only the elbow's neighbourhood is scored, so
the response moves the answer by at most a few cells either side of the
elbow. That ranking is by a diagnostic of the cell means and not by a
count rule, and it is returned with a warning of class
spatialkit_diagnostic_ranking that says so and gives the count
ranked first, the first count the statistic could be computed at and the
counts scored. select_resolution() refuses the same
statistic unless asked with diagnostic = TRUE; here the criterion
is asked for by name, so the count is returned and the warning carries
the caveat.
"morans_i" ranks on the standardised deviate
|z| = |I - E[I]| / \mathrm{sd}(I), using the Cliff and Ord
regression residual moments, and not on |I|: both E[I] and
Var[I] depend on the number of cells, so |I| falls as
k grows whether or not the finer cells capture anything, and a
ranking by |I| would prefer the largest candidate for arithmetic
reasons alone. The cell-level residuals are OLS residuals by
construction, which is the case those moments are derived for, but the
derivation also assumes errors of equal variance, and a cell mean over
n_j points has a variance proportional to 1/n_j, so
z is less reliable where single-point cells sit next to cells of
many points. Where structure remains, |z| mixes its size with the
number of cells it is measured on, since \mathrm{sd}(I) shrinks as
cells are added. Both quantities are reported in the
"diagnostics" attribute, as moran_i and moran_z.
Moran's I is computed with an 8-nearest-neighbour weight matrix, so it
carries information only once there are more than nine cells. At nine or
fewer, every cell is a neighbour of every other, the row-standardised
weight matrix is complete, and Moran's I is exactly -1/(k - 1) for
any residual vector. The residual moments then give E[I] = I and
\mathrm{Var}[I] = 0, so the standardised deviate is 0/0: those
candidates return NA and are left out of the ranking of
"morans_i". When no candidate in the elbow's neighbourhood clears
the floor, the call falls back to the geometric ranking and logs a
warning that says so. On points with no cluster structure the elbow
sits near \sqrt{K_{max}} and the neighbourhood is the elbow plus or
minus max(4, top_n), so the neighbourhood reaches ten cells only
from about max_levels = 40. On such a layer
resolution_profile(), which scores Moran's z at every level
of its ladder, is the model-aware view.
"combined" is the elbow's ranking of the counts around it, best
sag first, with Moran's I of the cell means and its z beside it in
the diagnostics; Moran's I does not take part in the ranking, and the
result is not an estimate of the number of clusters. The sag is read off
the sweep's WSS curve, the one the elbow is read from, so with an elbow
the first count is the elbow and the counts after it come in order of
sag; they can differ from the two neighbours "geometric" returns.
An elbow below ten cells is a count Moran's I cannot score: the geometric
ranking is returned, the elbow and its two neighbours, with a logged
warning, and the diagnostics record it (see Value). When the WSS curve
has no elbow (under on_no_elbow = "warn") the sag is flat, every
candidate tied, and the window comes out in order of distance from the
count the chord rule lands on, which is the geometric order. The k-means
re-run at each candidate, whose cells Moran's I is computed on, can land
in another optimum than the sweep; its WSS is reported as
wss_eval and does not rank. Where Moran's I can be computed at no
candidate of a window that reaches ten cells (a constant response, too
few cells holding a row with one, or too few in the half that
select_on = "split" reads), moran_i and moran_z are
NA, the log gives the reason at the WARN level, and the counts are
ranked as they would be otherwise.
Use "geometric" when the cell count should follow the clustering
of the points, "morans_i" for a ranking by the diagnostic, and
resolution_profile() when the response should drive the
count.
The k-means sweep
The WSS curve is read for its shape, so it is fitted to be smooth. Every
point on it is a k-means local optimum, and with a few random restarts
the curve mixes level effects with optimisation noise and can rise from
one k to the next. Each k is therefore fitted as the best of
25 restarts seeded by k-means++ (Arthur and Vassilvitskii 2007). A fixed
budget of restarts follows Fränti and Sieranoja (2019), and Steinley (2003)
shows why the usual handful is not enough; 25 is the package's choice, not
a published figure. A
curve that still rises somewhere is reported and not refused. A logged
warning names the number of rising steps, and the model-aware paths
return it as wss_bumps in the "diagnostics" attribute beside
wss_spread, the relative spread of WSS across the restarts at each
k.
The sweep is plain k-means, whatever the cells are built with
afterwards. This function has no partition argument: the elbow is
a reading of the sum of squares that plain k-means minimises, and the
cells behind Moran's z are that partition's. A count returned here says
nothing about density-weighted cells; resolution_profile(),
whose cells are of that kind by default, scores counts of those.
To keep memory use and run time bounded for large max_levels, the
sweep records only the WSS at each k, without the cluster
assignments. Moran's I is then evaluated on demand: k-means is re-run
only for a neighbourhood around the elbow (plus or minus 4 by default, or
plus or minus top_n if larger). The re-run at each count draws
its starts from a stream of its own, seeded before the sweep, so for one
set_seed a count gets the same cells, wss_eval and Moran's
I in any neighbourhood that holds it, whichever top_n and
max_levels set the neighbourhood: a larger top_n adds
counts to the neighbourhood and leaves the scores of the others as they
were.
Post-selection inference
When the selection reads the response (here, under
criterion = "morans_i" with a response), everything
estimated afterwards on the chosen cells is estimated on data that already
influenced the choice, and its standard errors are post-selection ones:
descriptive, not at nominal coverage (Gao, Bien and Witten 2022; Chen and
Witten 2023 give the exact selective test for two k-means clusters, the
first link of this chain). The exposure is narrower than "the partition
was chosen on the response": every partition here is k-means on the
coordinates alone, and the response only decides which count is ranked
first. It is not zero, because the count determines every cell the
downstream standard errors are computed over. Under "combined"
the response reaches the diagnostics and not the ranking, which is the
same whether or not Moran's I can be computed.
select_on = "split" is sample splitting: the layer is cut into two
spatially blocked halves (make_folds(k = 2, method =
"block_kfold")), the criteria that read the response (Moran's I on the
cell means) read the first half only, and the row positions of both
halves come back in the "split" attribute (selection and
estimation). The WSS curve and the k-means cells still use every
point: they read coordinates alone, and the count is for a tessellation
of every point, so it is chosen on that layer's extent and clusters
rather than on half of them. Build the tessellation on every point
(cells are geometry), but aggregate and fit on
data_sf[attr(x, "split")$estimation, ], whose response the
selection never saw. That keeps the selection's use of the response out
of the estimates, but only as far as the two halves are independent: the
split has no buffer, so points near the border between them are
correlated with the selection half over the autocorrelation range, and
coverage is nominal only when that range is short against the blocks.
The price is precision: half the points estimate, and García Rasines and
Young (2023) show a contiguous spatial half is less efficient than the
exchangeable split the i.i.d. theory assumes, because the two halves are
not interchangeable. Two alternatives keep the whole sample: data
thinning for count responses (Neufeld et al. 2024) and data fission for
Gaussian-like ones (Leiner et al. 2023). Neither is implemented here;
the split needs no distributional assumption. Under "combined"
the split changes only the rows the diagnostics read. Selection on
coordinates alone ("geometric", whatever variables are given) is
not exposed in this way, and "split" then changes nothing but the
attribute.
The estimation rows cover only the estimation half's blocks, while the
cells cover the whole layer, so the estimation rows do not fill every
cell. A cell inside the selection half gets none and comes back
NA; a cell across the border between the halves is estimated from
its estimation-half points alone, and its standard error describes that
part, not the cell. Count, per cell, how many of its points are
estimation rows, and read inferential results only off cells whose
points all are.
References
Arthur, D. and Vassilvitskii, S. (2007). k-means++: the advantages of careful seeding. Proceedings of the 18th Annual ACM-SIAM Symposium on Discrete Algorithms, 1027–1035.
Fränti, P. and Sieranoja, S. (2019). How much can k-means be improved by using better initialization and repeats? Pattern Recognition, 93, 95–112. doi:10.1016/j.patcog.2019.04.014
Steinley, D. (2003). Local optima in K-means clustering: what you don't know may hurt you. Psychological Methods, 8(3), 294–304. doi:10.1037/1082-989X.8.3.294
Gao, L. L., Bien, J. and Witten, D. (2022). Selective inference for hierarchical clustering. Journal of the American Statistical Association, 119, 332–342. doi:10.1080/01621459.2022.2116331
Chen, Y. T. and Witten, D. M. (2023). Selective inference for k-means clustering. Journal of Machine Learning Research, 24(152), 1–41. https://jmlr.org/papers/v24/22-0371.html
García Rasines, D. and Young, G. A. (2023). Splitting strategies for post-selection inference. Biometrika, 110(3), 597–614. doi:10.1093/biomet/asac070
Leiner, J., Duan, B., Wasserman, L. and Ramdas, A. (2023). Data fission: splitting a single data point. Journal of the American Statistical Association, 120(549), 135–146. doi:10.1080/01621459.2023.2270748
Neufeld, A., Dharamshi, A., Gao, L. L. and Witten, D. (2024). Data thinning for convolution-closed distributions. Journal of Machine Learning Research, 25(57), 1–35. https://jmlr.org/papers/v25/23-0446.html
See Also
build_tessellation() and get_voronoi_seeds(), which accept
this function's result directly as approx_n_cells and n (the first
candidate is used, and the output records that it came from here; an
NA from it stops them with a note on where it came from);
assign_features_to_polygons() and summarize_by_cell() for the steps
that follow.
Other resolution:
plot.resolution_profile(),
resolution_profile(),
select_resolution(),
summary.resolution_profile()
Examples
library(sf)
set.seed(1)
# Two clearly separated clusters: the elbow should sit near k = 2
pts <- st_as_sf(
data.frame(x = 5e5 + c(runif(25, 0, 10), runif(25, 90, 100)),
y = 5e6 + c(runif(25, 0, 10), runif(25, 90, 100))),
coords = c("x", "y"), crs = 32632
)
determine_optimal_levels(pts, max_levels = 6) # 2 1 3: the elbow first
# Points spread evenly have no elbow: NA, with structured = FALSE and a
# warning of class spatialkit_no_elbow that says why (printed here
# wrapped, in place of the warning)
even <- st_as_sf(data.frame(x = 5e5 + runif(200, 0, 100),
y = 5e6 + runif(200, 0, 100)),
coords = c("x", "y"), crs = 32632)
withCallingHandlers(
determine_optimal_levels(even, max_levels = 6),
spatialkit_no_elbow = function(w) {
writeLines(strwrap(conditionMessage(w), 76))
invokeRestart("muffleWarning")
}
)
Project an sf object to a CRS suited to its extent
Description
Returns a spatial object in a projected CRS, so that distances and areas
computed on it are close to true. Without target_crs, an object that
already has a projected CRS is returned as it is, and lon/lat input is
moved to a CRS chosen from its extent; with target_crs, the object is
moved to that CRS.
Usage
ensure_projected(x, target_crs = NULL, purpose = c("distance", "area"))
Arguments
x |
An sf or sfc object (other objects are returned unchanged). |
target_crs |
Optional target CRS (sf object, integer EPSG, or crs).
Must resolve to a usable CRS via |
purpose |
|
Details
Without target_crs, only geographic (lon/lat) input is transformed, and
the CRS chosen depends on the extent of the data:
- Local extents
The UTM zone containing the data's centre (EPSG:326xx north of the equator, EPSG:327xx south). Distances and areas are close to true over a few degrees of longitude, which is the case this package is usually in. The centre is the centroid on the sphere, computed with s2 whatever
sf::sf_use_s2()is set to, so data near a zone edge get the same zone in every session.- Wide extents
Once the data reach well beyond the roughly 3 degrees a UTM zone is designed for, a single zone can distort distances by several percent, and that error propagates into variogram ranges, block sizes, GWR bandwidths and GP length-scales. The projection used is then the one with the smallest measured distortion among the zone, a Lambert azimuthal equal-area centred on the data and (where its standard parallels do not degenerate or pass a pole) an Albers conic. Each is scored by projecting representative points of the data and comparing planar with geodesic distances over the pairs at least 1 mm apart. A non-POINT layer is reduced to one point per feature, plus the vertices of its outline when fewer than 40 distinct points remain, so a single study-area polygon is scored too, however many rows repeat it; copies of one location count once, and rows without a finite location are left out. A candidate must place every location of the layer to be used: one under which a vertex of the layer has no coordinates (a UTM zone about 90 degrees or more from its central meridian) gets
distance_errorNAand is not chosen, and the log line names it. A vertex at a latitude beyond 90, which no CRS places, takes no part in this test. When no candidate places every vertex, Web Mercator (Equal Earth forpurpose = "area") is used. The choice, its distance error and the zone's, and this argument are logged (seespatialkit_quiet()); they are not R warnings, sotryCatch(warning = )does not see them.- Antimeridian
Data straddling longitude 180 have a bounding box wider than a hemisphere. The wrap is detected from the coordinates (one very large gap in the sorted longitudes) and an equal-area projection centred on the true extent is used.
- Around a pole
Data spanning more than 180 degrees of longitude with no such gap surround a pole. When every point also lies on one side of the equator (Antarctic stations, a pan-Arctic network), a Lambert azimuthal equal-area centred on that pole is used, provided it measures a smaller distance error than the global fallback. Web Mercator splits such a layer at longitude 180 and stretches it towards the pole. Only the coverage left over, spanning both hemispheres or a low-latitude belt the polar projection fits worse, falls back to EPSG:3857 (Equal Earth for
purpose = "area").- Missing CRS
A layer without a CRS is read by the lon/lat test of spatialkit-geometry ("Layers without a CRS"). With no
target_crs, coordinates the test takes for degrees are read as EPSG:4326, with a warning, and the rules above then apply; coordinates it declines are left as they are. Withtarget_crs, coordinates the test takes for degrees are read as EPSG:4326 and reprojected to the target, with a warning, and any others have the target stamped on without reprojection. A stamp is a relabel, logged only, so check that the coordinates are in that CRS. Set the CRS onxto avoid either. Atarget_crsin longitude and latitude is not stamped on coordinates that cannot be in it: an x outside -180 to 360 or a y beyond 90 north or south, in the box of the coordinates that have a location, stops the call with an error that gives the box.- Rows without a location
Such rows (see spatialkit-geometry, "Rows without a location") take no part in the lon/lat test or the choice of a projection. The lon/lat test reads the coordinates that have a location vertex by vertex, so a polygon with one vertex beyond 1e150 is read on its other vertices. A layer in which no row has a location, or each row of which is empty, has no location or has a vertex at a latitude beyond 90, gets Web Mercator (Equal Earth for
purpose = "area"). Moved to another CRS, a row without a location comes back empty, in its own geometry type. A row that has a location and that the move cannot place in full comes back empty, or without the vertices the CRS cannot place, with a warning of classspatialkit_rows_unplacedthat names the rows (rowson the condition). With the projection chosen here that happens only at a coordinate no CRS places, such as a latitude beyond 90; with atarget_crs, wherever that CRS cannot place the layer.
target_crs overrides all of this. Pass it whenever you need a specific,
reproducible projection: comparing runs, matching an existing layer, or
fixing the units that make_folds()'s block_size will be interpreted in.
A layer that mixes XY and XYZ (or XYM) geometries is returned in XY when
it is transformed, with a warning of class spatialkit_zm_dropped, and
the projection is chosen from the layer in XY; see spatialkit-geometry,
"Mixed dimensions, Z and M". A layer that is not transformed is returned
with its own geometry.
Value
x in target_crs when one is given. Otherwise x in the
projected CRS chosen here, as it came when it already had a projected
CRS, or without a CRS when it had none and the lon/lat test declined it
(see "Missing CRS").
Two attributes record how the CRS was reached:
crs_choicePresent when a projection was chosen here (lon/lat input, no
target_crs): a data.frame with one row per projection considered, holdingname,crs(its definition), the measured worst-casedistance_error(relative, over sampled pairs;NAwhere it could not be measured) andchosen. The figure is measured for the single candidate on the paths where no comparison runs (a UTM zone on a local extent, the equal-area projection chosen for a layer straddling the antimeridian).NULLwhen no local projection was chosen here: input that already had a projected CRS, atarget_crsyou supplied, or an extent no local projection fits, which falls back to Web Mercator or Equal Earth.crs_assumedOn input without a CRS:
"EPSG:4326"when the lon/lat test took the coordinates for degrees,"none"when it declined. The attribute is also read on the way in: an object already carrying"none"is returned as it is, without the test, which is how apredict()method replays a fit's decision so that a subset of the training rows is not judged differently from the whole.
Equal-area check
Under purpose = "area", input that already has a projected CRS is
returned as it is, but its area distortion over the extent is measured
and logged as a warning when it exceeds 1 percent. The measure is the
spread of planar-to-geodesic area ratios over probe polygons. The probes
are the layer's distinct polygons (exact copies of a polygon count once).
A 6 by 6 grid over the bounding box is used instead for a layer without
polygons, a layer of one distinct polygon, which gives one ratio and no
spread, and a layer with a polygon s2 cannot measure in degrees (edges
that cross, a spike) or that sf::st_is_valid() rejects in its
CRS (a hole outside its shell), whose planar area is not the area it
encloses. When the grid gives no figure either (a single point, a line
along one axis), a warning says that the distortion could not be
measured. An equal-area projection still shows some spread, from the
sphere the geodesic areas are computed on against the ellipsoid the
projection uses. summarize_by_cell() applies the
same check before it computes a density.
See Also
spatialkit-geometry for how input geometry and CRSs are read.
Other data preparation:
[.spatialkit_rows(),
coerce_to_points(),
harmonize_crs(),
prep_model_data(),
spatialkit-geometry
Examples
library(sf)
pts_ll <- st_as_sf(
data.frame(lon = c(9.1, 9.2), lat = c(48.7, 48.8)),
coords = c("lon", "lat"), crs = 4326
)
# A local extent gets the containing UTM zone; the zone's measured
# distance error over the extent travels with the result.
st_crs(ensure_projected(pts_ll))$epsg # 32632
attr(ensure_projected(pts_ll), "crs_choice")
# A continental extent is scored against the zone and may get an
# equal-area projection instead. The choice is logged with its distance
# error and the zone's, not raised as an R warning (see ?spatialkit_quiet);
# crs_choice holds every candidate scored.
wide <- st_as_sf(
data.frame(lon = c(-120, -70), lat = c(30, 48)),
coords = c("lon", "lat"), crs = 4326
)
wide_p <- ensure_projected(wide)
st_crs(wide_p)$proj4string
attr(wide_p, "crs_choice")[, c("name", "distance_error", "chosen")]
# target_crs overrides the choice.
st_crs(ensure_projected(pts_ll, target_crs = 3035))$epsg # 3035
# For densities per cell the CRS has to be equal-area. Two candidates are
# scored, an Albers conic and a Lambert azimuthal, both centred on the data,
# and whichever distorts distance less over the extent is used: here Albers.
st_crs(ensure_projected(pts_ll, purpose = "area"))$proj4string
Give cells IDs that follow their position
Description
Numbers the polygons of a layer from west to east, and from south to
north among polygons at the same longitude, by a representative point of
each (its centroid by default) taken by default in EPSG:4326
(transform_for_sort); ties go to the smaller area. The same polygons get
the same IDs whatever their row order or projection, except as
transform_for_sort says, so use it before joining summaries made from
different runs.
Usage
ensure_stable_poly_id(
polygons_sf,
id_col = "poly_id",
method = c("centroid", "surface_point", "bbox_center"),
make_valid = TRUE,
transform_for_sort = 4326
)
Arguments
polygons_sf |
An sf or sfc object containing polygonal features.
Polygons that mix XY and XYZ (or XYM) geometries are keyed without Z
and M, since sf reads a layer in the dimension of its first geometry
(see |
id_col |
Name of the ID column to write. Default |
method |
The point each polygon is sorted by: |
make_valid |
Logical; apply st_make_valid() first. Default TRUE.
The copy the sort key is measured on is repaired as well, after it has
been transformed (see Details); with |
transform_for_sort |
CRS used only for computing sort-key coordinates.
Default 4326. This is the whole mechanism by which the IDs are stable
(sorting in one common CRS is what makes the same layer get the same IDs
whichever projection it arrives in), so if the transform fails the
function says so rather than quietly sorting in the input's own CRS. A
transform that cannot place every polygon with a location (a projected
layer far outside its CRS's area, whose rows PROJ returns empty) counts
as failed in the same way: the whole layer is sorted in its own CRS, and
the log says so. In a geographic CRS the
sort key is rounded to 7 decimal degrees (about 1 cm) before ordering, so
the floating-point noise of a round trip through a different projection
does not reverse two neighbouring cells, except where two cells'
centres lie within about that step of the same longitude, as fine cells
stacked north-south near a projection's central meridian do. No
rounding step removes that, so to match cells computed in different
projections, join them on geometry rather than on the ID. The key is computed on the sphere (s2) whether or not
A key in a CRS that is not geographic (with NULL, for a layer without a CRS, after a failed transform, or in a projected sort CRS) is rounded to a step that grows with the magnitude of the coordinates: the power of two at or above 2^-44 of the layer's largest coordinate, never under 1e-7 of its unit, so a layer within about 1.7e6 units of its origin is rounded to 7 decimals. Keys that tie at that step are ordered by keys rounded at the step of each polygon's own largest coordinate. Cells 1e12 units out are then not ordered by the last bits of their centres, which doubles do not hold there, and take the order they have at the origin. |
Details
A feature that is valid in its own CRS is not always one s2 can measure.
Only the vertices are transformed to the sort CRS, and on the sphere they
are joined by great-circle arcs, so a long edge that is straight in the
layer's CRS and passes about a metre from another vertex of the same ring
can end up on the other side of that vertex. The ring then crosses itself,
and s2 refuses it. The repair of the sort copy does not split crossing edges, so a feature s2
still refuses is handled on its own. Its sort copy is repaired a second
time with the crossing edges split. If s2 refuses that as well, or with
make_valid = FALSE, which asks for no repair, the feature's
centroid and area are measured as plane geometry in the layer's own CRS
and the centroid is transformed to the sort CRS. With the methods
"surface_point" and "bbox_center" only the area needs this,
because those points are not taken with s2.
The function warns once, saying how many features took each route. Their keys are close to the spherical ones and not equal to them, so a feature measured in the plane can sort on the other side of a neighbour whose centre is nearly at its own longitude. Every other feature's key is unaffected, and the geometry returned is never the sort copy.
A polygon of a layer in a geographic CRS with a vertex at a latitude
beyond 90 degrees is no place on the Earth. It is keyed as an empty
polygon is, after every polygon with a location, it is not repaired and
comes back as it came, and a warning of class spatialkit_lat_beyond_90
gives its rows of polygons_sf (rows).
Value
An sf polygon layer re-ordered, with sequential IDs in id_col.
Non-polygonal rows are dropped (with a warning), so the result can
have fewer rows than the input; if no polygonal rows remain, an error is
raised.
See Also
Other cell building:
build_tessellation(),
clip_target_for(),
create_grid_polygons(),
create_grid_polygons_cached(),
create_voronoi_polygons(),
get_voronoi_seeds(),
plot_tessellation_map(),
voronoi_seeds_kmeans(),
voronoi_seeds_random()
Examples
library(sf)
bnd <- st_sf(geometry = st_sfc(st_polygon(list(rbind(
c(0, 0), c(100, 0), c(100, 100), c(0, 100), c(0, 0)
))), crs = 32632))
g <- create_grid_polygons(bnd, target_cells = 9)
# Reverse the rows and re-derive the IDs: the same cell gets the same ID,
# which is the property a row-position ID does not have. The check joins
# the two layers on geometry, because comparing sorted ID vectors would
# pass for any two permutations of 1:9.
fwd <- ensure_stable_poly_id(g)
rev <- ensure_stable_poly_id(g[nrow(g):1, ])
same_cell <- match(st_as_text(st_geometry(rev)), st_as_text(st_geometry(fwd)))
all(rev$poly_id == fwd$poly_id[same_cell])
Estimate the spatial autocorrelation range from data
Description
Fits an exponential variogram model with a nugget and returns the
effective range: three times the fitted range parameter, where the
semivariance reaches about 95 percent of the sill. Beyond it two
observations are close to uncorrelated, so it is the distance a block or a
buffer has to exceed. The range is in the units of the projected CRS the
variogram is fitted in. Pass it as the block_size of make_folds(), or
let make_folds(auto_range = TRUE) estimate it, so that the blocks are at
least as wide as the autocorrelation range.
Usage
estimate_sac_range(
points_sf,
response_var,
predictor_vars = NULL,
n_max = 5000L,
cutoff = 0.5,
range_frac = 1,
seed = 123L,
detrend = c("ols", "reml"),
reml_max_n = 400L,
keep_directional_fits = FALSE,
lags = c("adaptive", "equal"),
n_lags = 15L,
structure_alpha = 0.05
)
## S3 method for class 'sac_range'
print(x, ...)
Arguments
points_sf |
An sf layer of points. A lon/lat layer is projected
first (spatialkit-geometry); other geometry is reduced to
representative points, and Z and M are dropped, since
|
response_var |
Name of the response column. Rows where it is missing
or infinite are left out before anything else is done, so they take no
part in the choice of projection for lon/lat input and do not use up the
|
predictor_vars |
Optional character vector of predictor column names.
When given, the trend on these predictors is removed first and the
variogram describes the residual autocorrelation, the part a spatial
model has to handle once the covariates have done their work. How the
trend is removed is set by |
n_max |
The most points the variogram is computed on, at least 30;
|
cutoff |
Fraction of the largest distance between two points to use as the variogram lag cutoff, above 0 and at most 1. That distance is the farthest pair, found on the convex hull, not the diagonal of the bounding box, which depends on how the axes are oriented. Default 0.5. |
range_frac |
A positive number, default 1. A fitted range beyond
|
seed |
RNG seed for the |
detrend |
How the trend on |
reml_max_n |
A whole number of at least 30, default 400. With
|
keep_directional_fits |
|
lags |
How the lags are binned: |
n_lags |
A whole number from 5 to 100, default 15. With
|
structure_alpha |
The level of the test for spatial structure, above 0
and at most 1; default 0.05. A layer whose adjusted p-value is not below
it gets no range. |
x |
A |
... |
Ignored. |
Details
The layer is first tested for spatial structure, and a range the data
cannot identify is refused: the answer is then NA, with the reason and
the evidence attached (see Value). plot.sac_range() draws the variogram
behind the estimate, and sac_nugget() reads its nugget.
Value
A single number, in one of three shapes, each of which behaves as
an ordinary number. A range that was fitted, and a range fitted and
refused, are of class sac_range; a call that could fit nothing returns
an unclassed NA. The attributes and the class do not affect is.na()
or is.finite(), so code that tests for a missing range treats all
three alike.
- Success
A positive effective range in the units of the projected CRS, with the fit attached as attributes:
-
crs: the projected CRS the variogram was fitted in, which gives the unit of the range;max_distandcutoff_dist: the farthest pair and the lag cutoff. -
variogram: the empirical variogram, in the units of the response's variance;variogram_model: the fitted model, in gstat's layout, or withdetrend = "reml"one built from the REML parameters. -
lags,lag_boundariesandlag_fallback: the binning behind the result, its upper bin edges, andTRUEwhen adaptive lags were asked for and the equal-lag result is returned (see the section "The lags"). -
first_lag: the mean separation in the first bin, the shortest lag resolved, from which the nugget is extrapolated;bins_below_range: how many bins lie inside the fitted range (with fewer than three, the split between nugget and structure rests on very little). -
structuresandshort_range: how many structures the model has besides the nugget, and the effective range of the short one when there are two (NAotherwise). -
nugget(the model's nugget variance),nugget_at_bound,nugget_floor,short_lag_semivariance,short_lag_pairs,short_lag_dist,zero_lag_semivarianceandzero_lag_pairs: the nugget and the evidence to judge it by, described insac_nugget().zero_lag_semivarianceisNAandzero_lag_pairs0 when no location has two rows. -
structure_p,morans_iandstructure_test: the adjusted p-value of the test for spatial structure, Moran's I on the 8 nearest neighbours, and the statistic, z and p for each neighbourhood size. -
directional: the ranges at azimuths 0, 45, 90 and 135 degrees, named by azimuth,NAwhere that direction's fit was unusable;directional_status: per azimuth, why a direction isNAindirectional:"ok","over_cutoff"(its range ran past the largest lag fitted),"not_converged"(its fit has no minimum inside the ranges searched) or"no_fit"(a flat variogram, or too few bins);directional_fitted: the range each direction's fit reported, usable or not, so a refused directional range stays recoverable;directional_fits: withkeep_directional_fits = TRUE, a list by azimuth of each direction's empiricalvariogramand fittedmodel(NULLwhere there is none), andNULLotherwise;anisotropy: the largest directional range over the smallest;anisotropy_used: alwaysFALSE, since the all-pairs fit is the estimate. -
detrended: whether the variogram is of the residuals onpredictor_vars(TRUE) or of the raw response. A predictor that is not a column is an error, and a detrending fit that fails warns and falls back to the raw response with this set toFALSE.detrend_method:"ols"or"reml"when detrended,NAotherwise.reml: withdetrend = "reml", a list withn_used,subsampled,nugget_prop,sigma2,logLik(the REML log-likelihood of the fit kept),logLik_gain(its gain over the same trend with independent errors) andn_fits(the starts fitted);NULLotherwise. -
n_used,n_missingandn_subsampled: the points the variogram was computed on, the rows left out for a missing response or predictor, and the rows then_maxsubsample left out.
-
- Rejected range
NA_real_when no range is identified. It is classedsac_rangeas well, so it prints asNAwithout dumping its attributes, and it carries every attribute of a success (the evidence for the rejection), plusrejected_range(the value that was refused,NAwhen none was fitted) andrejected_reason, one of:-
"no spatial structure detected at the nearest-neighbour scale": the test in the section "The test for spatial structure". The model attached is a pure nugget at the variance of the modelled variable, and nothing fitted is handed on. -
"the empirical variogram is flat: no spatial structure at the lags resolved": no model with a range fits the variogram better than a constant. The model attached is that constant, a pure nugget. -
"empirical variogram decreases with distance": the semivariance falls over the shorter lags (a net fall of more than 15 percent of the mean semivariance there, weighted by pairs), which is the shape of a periodic, hole-effect structure or of a variance that differs between a dense cluster and the rest of the layer. Sampling noise in the short-lag bins of a small sample can make that fall too. -
"fitted range exceeds the largest lag fitted": the range is pastrange_frac * cutoff * max_dist(seerange_frac). An unremoved trend ends here when the variogram rises past the fitted lags; a milder trend only lengthens the fitted range and passes, which is whatpredictor_varsis for. -
"fitted range is below the shortest lag fitted": too few pairs of points lie inside the range to identify it, because it is shorter than the shortest lag the empirical variogram resolves (first_lag) or, withdetrend = "reml", than the distance within which 30 pairs of the points the REML fit used lie, when that is shorter (the REML range is fitted to the point pairs, not to the bins). A structure that short cannot be told from a nugget.range_floorholds the distance the refused range fell short of. -
"fitted range is non-positive or non-finite". -
"no variogram model could be fitted: fewer than three lag bins hold point pairs".variogram_modelis thenNULLandnuggetisNA.
The reason names one ground for the refusal, in the order above.
attr(attr(range, "variogram_model"), "converged")says one thing more about the model: it isFALSEwhen the least-squares criterion is still falling at an edge of the ranges searched (a variogram with no sill inside four cutoffs), and the nugget and sill of such a model are that edge and not fitted values. For a model with two structures the flag is that of the equal-lag fit the long range came from: when that fit has no minimum, the long structure's range and partial sill are the edge of its search and the flag isFALSE, although the nugget and the short structure were fitted at the adaptive lags. A model built from REML parameters carries no such attribute.resolution_profile()reads it, and takes no nugget from a model markedFALSE.-
- No fit
An unclassed
NA_real_when estimation could not be attempted at all, whose one attribute,rejected_reason, says why:"package 'gstat', which the variogram needs, is not installed","<n> points, fewer than the 30 a variogram range is estimated from","<n> point(s) with a finite value to model, fewer than the 30 a variogram range is estimated from"(the count is of the whole layer's rows with a value),"<k> distinct location(s) among the <n> point(s) with a finite value to model, fewer than the 30 a variogram range is estimated from"(rows that share a location count once; when the layer has 30 or more locations and then_maxsubsample kept fewer, the counts are the subsample's and"of the n_max subsample"stands in place of"with a finite value to model"),"the response is constant","the residuals on predictor_vars are constant: the predictors explain the response exactly"or"the points have no extent (the largest distance between them is zero or could not be computed)". Nothing is fitted, so none of the other attributes exist: novariogram,variogram_modelorrejected_range, which is what tells it from a range that was fitted and refused.
What is estimated
The estimate is the omnidirectional (all-pairs) fit of an exponential model with a nugget. Only the exponential family is fitted. On fields smoother than exponential that makes the range long, and blocks sized from it come out larger: they still hold the test points at least the field's range from their training data, which blocks sized from a short range do not. Choosing the family by the smaller weighted sum of squares would correct a spherical field but send exponential fields short, and blocks sized from them smaller than the range.
The model is fitted without iteration. The criterion is gstat's
weighted least squares (weights N / h^2) on lags divided by
the cutoff. For each trial range the nugget and the partial sill are
solved exactly, both kept at or above zero, and the range is found by a
search over a logarithmic grid from a quarter of the first lag to four
cutoffs, refined in one dimension. There is no start value, no iteration
limit and no fit that fails to converge.
The test for spatial structure
A variogram model can be fitted to anything, and on a layer with no
structure the fit returns a finite range for a large share of draws. So
Moran's I of the modelled variable is computed first, on its 2, 4, 8 and
16 nearest neighbours, each standardised with the moments that fit the
variable (those of regression residuals when predictor_vars are given),
and the smallest one-sided p-value is multiplied by four. When that
adjusted p-value is not below structure_alpha, the result is NA with
rejected_reason "no spatial structure detected at the nearest-neighbour scale", a pure-nugget model and no fitted range. The test uses no random
numbers, and structure_p, morans_i and structure_test are attached
to every classed result. Its power is limited where few neighbours lie
inside the range, so a short range on a sparse layer can be refused;
structure_alpha = 1 switches the refusal off.
Neighbours tied at the k-th distance, those whose squared distances are
within one part in ten million of the k-th's, share its slot's weight
equally, as in residual_morans_i(). The graphs then do not depend on the
unit or the origin of the coordinates wherever the doubles hold them to
better than about one part in 1e8 of the distances between neighbours.
Where they do not, and a distance lies past a tie by less than that
rounding, the call warns with class "spatialkit_xy_imprecise" (see
spatialkit-geometry), as it does for the nearest other location of the
short-lag semivariances. The results are those the coordinates as stored
give.
Rows that share a location (repeat visits) are one place and not each
other's neighbours, so on such a layer the test is made on the means of the
locations: it asks whether locations near each other are alike, which a
location's own effect, however large, does not answer. With very unequal
numbers of visits the p-value is approximate. For the same reason a layer
needs 30 distinct locations, not only 30 rows; below that the result is the
unclassed NA whose reason gives the count (see Value), and nothing is
fitted. Five locations visited 20 times give ten pairs of locations and
five means, from which neither a range nor a verdict on structure can be
read. Two rows are at one location when both their coordinates are equal
to the last bit after the projection, so repeat visits recorded with
slightly different coordinates count as separate locations; round the
coordinates first to pool them.
The lags
With lags = "adaptive" (the default) the first bin runs from zero to the
distance within which the closest max(50, n / 4) pairs of distinct
locations lie, and up to n_lags further bins are spaced geometrically
from there to the cutoff; a bin holding fewer than 30 pairs is merged with
the next. The short lags, which the nugget and a short range are read
from, are then resolved at the spacing of the points. With
lags = "equal" there are n_lags bins of equal width out to the cutoff,
as gstat bins by default. Each is cutoff * max_dist / n_lags
wide; a structure shorter than the first of them is counted as nugget, and
the range fitted is that of whatever longer structure the layer has. Below
about a hundred points neither binning resolves much, and the adaptive
bins bring no gain.
The adaptive lags put little weight on the long ones, and a weak, long
structure under much noise can be clear at equal lags while the adaptive
fit runs past the largest lag. So when the adaptive range is refused as
past the fitted lags and the equal-lag fit has a range it would itself
return, the result is the equal-lag one, whole, as lags = "equal" gives
it, with lags saying "equal" and lag_fallback set to TRUE. Its
nugget is then the equal-lag nugget. No other refusal falls back.
Structure at two scales
One structure fitted to lags that resolve the spacing of the points
follows the shortest structure of the layer. A layer can have a weaker
structure several times longer as well, and blocks sized from the short one
would leave the long one across folds. So with lags = "adaptive" the
equal-lag fit is made too, and when its range is at least twice the
adaptive one, a model with a nugget and both structures, at those two
ranges, is fitted to the adaptive variogram. That model is returned
(structures is 2 and short_range holds the range of the short
structure) and the range is the long one, unless the long structure carries
under 3 percent of the model's semivariance at the largest lag; then the
single structure stands.
The bar is low because the two mistakes are not alike. A long structure
that is missed is lost: the range returned is the short one alone. One
that is believed in error returns the equal-lag range, which is too long,
and short_range still holds the short one. When the equal-lag range is
one that lags = "equal" would itself refuse (past the fitted lags, as
under an unremoved trend), the model with it is refused as well, the answer
is taken away and not lengthened, and the long structure has to carry 10
percent. The nugget comes from the adaptive lags either way. A long
structure whose equal-lag range is under twice the adaptive one is not
separated: the range is then that of the single fit, which lies between the
two.
Directional ranges and anisotropy
Directional variograms are fitted as well, at azimuths of 0 (north-south),
45, 90 (east-west) and 135 degrees, each with a tolerance of 22.5 degrees
either way. Those four windows tile all 180 distinct azimuths once, and
their ranges are returned in the directional attribute, with their
largest-over-smallest ratio in anisotropy. They are a diagnostic and
never the answer, for two reasons. Each direction sees about a quarter of
the point pairs, and the maximum of four quarter-sample fits is biased
upward. And the windows are fixed to the coordinate axes, so any answer
built from them changes when the layer is rotated, which a property of the
field must not do. The all-pairs fit is the best-powered estimate
available and does not change under rotation. When it identifies no range,
no range is returned: the largest directional range does not stand in for
it.
A direction whose variogram is flat or has too few bins, whose range runs
beyond the longest fitted lag, or whose fit has no minimum inside the
ranges searched is left out and recorded as NA in directional.
Where a field is known to be anisotropic and blocks are to be at least as
large as its autocorrelation range in every direction, size them from the
longest directional range yourself. Read it from directional_fitted,
not directional: on a strongly anisotropic field the major axis is the
direction most likely to run past the fitted lags, which leaves it NA in
directional, so max() of that is NA, or with na.rm = TRUE the
second-longest range. Check directional_status first: a major axis
marked "over_cutoff" has no identified range at all, and a longer
cutoff or make_folds(method = "nndm") is the way on. A ratio above
1.5 is written to the package log at INFO level with that advice, which
reaches the session log file but not the console (the ratio passes 1.5 on
most isotropic fields too).
The nugget
The model is fitted with a nugget. A nugget-free model forces the curve
through the origin, and on a measurement that has a nugget the
N / h^2 weights buy that constraint by collapsing the range.
The fitted nugget can sit at its lower bound of zero; the result then
carries nugget_at_bound = TRUE, and sac_nugget() lists what else is
attached to judge a nugget by.
Two rows at one location are a pair at zero separation and are in no bin,
whichever the binning, since the variogram and the model describe positive
separations. Their semivariance, the variance between visits to a
location, is returned on its own as zero_lag_semivariance. The nugget
fitted to the variogram is not let under it when the layer has 30 or more
rows beyond one a location to estimate it from; a model from
detrend = "reml" takes no such floor.
Detrending and the residual-variogram bias
Fitting a variogram to the residuals of a least-squares trend
underestimates both the sill and the range, because the trend fit absorbs
part of the long-wavelength spatial variation (Lark, Cullis and Welham
2006). Blocks sized from that range are then narrower than the field's
range, and hold the test points less far from their training data than
range-sized blocks are meant to. How large the effect is depends on how
smooth the trend terms are in space and on how many there are: it is small
for ordinary covariates and large for trend surfaces in the coordinates.
Iterating between a GLS trend fit and a variogram refit (Neuman and
Jacobson 1984) recovers only part of it, because the variogram of GLS
residuals is biased too. REML fits no variogram to residuals, which is why
detrend = "reml" returns its own range estimate. Its price is a single
family (exponential with nugget), a cubic cost in n, and a somewhat wider
sampling spread. The default is "ols"; a script that detrends on smooth
or coordinate-based terms should pass detrend = "reml", or size its
blocks with a margin above the range returned, to make up the shortfall.
Detrending removes a trend the predictors explain; it does not make an
unidentified range identified.
Count and other non-Gaussian responses
The empirical variogram assumes second-order stationarity: a variance that is the same everywhere, so that semivariance depends on separation alone. A count response breaks that assumption by construction, because its variance tracks its mean, and so does any response with a mean-variance relationship (rates, proportions, skewed amounts). On such data the variogram mixes distance-dependence with mean-dependence: where the mean is high the semivariance is inflated whatever the distance, which flattens the curve and can lengthen or shorten the apparent range depending on where the high-mean areas sit.
Detrending on predictor_vars removes the part of the mean the covariates
explain, but it does not fix the variance structure: the residuals of an
OLS fit to a count still have a variance that tracks the fitted mean. The
remedy is a variogram of Pearson residuals from a model in the right
family, which this function does not compute. Treat the range from a
count response as no more than an order of magnitude, since it can come out
long or short, and prefer make_folds(method = "nndm"), which needs no
fitted range.
Numerical behaviour
The result is a function of the data alone. The same layer gives the same answer whatever the unit of the response or of the coordinates and whatever the order of its rows, and a change in the last bits of the values changes the answer by about as much.
The rows are sorted by their coordinates as supplied, then by the response
and the predictors, before anything else, so the projection chosen for
lon/lat input, the n_max subsample and the pair sums do not depend on
their order. First coordinates within 1e-7 of the diagonal of the points'
bounding box count as one column, sorted by the second coordinate, so a
lattice whose first coordinates in one column differ in their last bits
after a change of unit or origin gets the same order and the same
subsample in each. Rows that share a location are therefore in the order
of their values, and no step treats the first of them as special.
The variogram is computed on the standardised variable. A response is
called constant only when its standard deviation is under 1e-12 of its
largest absolute value, which no change of unit alters, and the values
centred on their median and scaled have a standard deviation of at most
three units in the last place of that value. Residuals of the predictors
are called constant when they are no more than the rounding of the
regression, taken on the size of the fit's terms, or three such units of
the response, whether or not the floor finds spread in them, as the test
for cp of resolution_profile() reads them. So 1e15 plus a spread of
1, stored to an eighth, is not constant, and the residuals of a response
the predictors fit exactly are, on a predictor far from 0 (a northing) as
well. A response that loses its spread on the raw values is centred on its
median before the predictors are fitted to it and before the test for
spatial structure, neither of which changes under a shift; so is a response
whose OLS residuals on the raw values lose their spread (1e15 plus 1e5
times a predictor plus a spread of 1, on that predictor).
The test for spatial structure, the semivariances and the REML fit are
taken on the response divided by a power of two near its spread. A
response near 1e-160 or 1e160, whose squares lie past what doubles hold,
then gives the range, the test and the folds it gives in ordinary units.
The variogram, the nugget, the short-lag semivariances and the REML
variance are returned in the response's units squared, which near 1e160
are Inf and near 1e-160 are subnormal doubles that keep few bits, or 0.
A response so far from zero that doubles there are spaced more than a
millionth of its standard deviation apart (a standard deviation of 1 at
about 1e10, 2^33, or beyond) is read as stored, rounded to
that spacing, with a warning of class spatialkit_response_imprecise.
With detrend = "reml" the REML fit reads the coordinates of the rows it
uses centred on the middle of their bounding box, divided by its diagonal
and rounded to 2^-30 of it, and the response and each
numeric predictor centred on the middle of their range on those rows,
divided by it and rounded the same way. Its range, coefficients and
variance are taken back to the layer's units. Where the REML range is not
identified the likelihood is flat, and whether the fit converges or falls
back to OLS is set by the last bits of the coordinates, the response and
the predictors; in that frame it does not depend on their units or
origins. A value within its own rounding noise of the middle of a step,
about a billionth of the diagonal or the range, can still fall on either
side of it.
Printing
print() shows the effective range as a plain number, and beneath it the
directional ranges and their ratio when the directional fit is available.
A direction whose fit was unusable is labelled with why
(directional_status) and the range its fit reported
(directional_fitted) when the object carries them, and unidentified
otherwise. A last line names the unit and the CRS the range is a length
in (attr(x, "crs"), which for lon/lat input is the projected CRS the
estimate chose; for a layer with no CRS, it says the range is in that
layer's own coordinate units), and whether the variogram is of the
response or of its residuals on predictor_vars (detrended,
detrend_method). print() returns x invisibly.
References
Cliff, A. D. and Ord, J. K. (1981). Spatial Processes: Models and Applications. Pion, London.
Lark, R. M., Cullis, B. R. and Welham, S. J. (2006). On spatial prediction of soil properties in the presence of a spatial trend: the empirical best linear unbiased predictor (E-BLUP) with REML. European Journal of Soil Science, 57(6), 787–799. doi:10.1111/j.1365-2389.2005.00768.x
Neuman, S. P. and Jacobson, E. A. (1984). Analysis of nonintrinsic spatial variability by residual kriging with application to regional groundwater levels. Mathematical Geology, 16(5), 499–521. doi:10.1007/BF01886329
See Also
sac_nugget() for the nugget behind the estimate, and
plot.sac_range() to see the variogram the estimate rests on.
Other spatial autocorrelation:
plot.sac_range(),
sac_nugget()
Examples
library(sf)
# A Gaussian random field with an exponential covariance: range parameter
# 100, so the true effective range is 3 x 100 = 300, plus a small nugget.
set.seed(9)
n <- 150
xy <- data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000))
D <- as.matrix(dist(xy))
xy$z <- as.numeric(t(chol(exp(-D / 100) + diag(0.1, n))) %*% rnorm(n))
pts <- st_as_sf(xy, coords = c("x", "y"), crs = 32632)
r <- estimate_sac_range(pts, response_var = "z")
r # the effective range, in metres
attr(r, "directional") # the four directional ranges
attr(r, "variogram_model") # the fitted model behind it
attr(r, "nugget_at_bound") # TRUE: the fit put the nugget at its bound;
# ?sac_nugget says how to read that
attr(r, "structure_p") # the test for spatial structure
# A field whose range the data cannot pin down: the variogram never
# reaches a sill within the lags fitted, so the answer is NA, with the
# refused value and the reason attached.
xy$trend <- sin(xy$x / 400) + rnorm(n, sd = 0.2)
r2 <- estimate_sac_range(st_as_sf(xy, coords = c("x", "y"), crs = 32632),
response_var = "trend")
r2
attr(r2, "rejected_reason")
attr(r2, "rejected_range")
# White noise: no structure, so no range.
xy$noise <- rnorm(n)
r3 <- estimate_sac_range(st_as_sf(xy, coords = c("x", "y"), crs = 32632),
response_var = "noise")
attr(r3, "rejected_reason")
Compute the metrics of several fitted models
Description
Runs model_metrics() on each fit in a list and binds the
rows, with a model column and a metric_basis column saying
whether each row is in-sample, out-of-bag or on newdata. It takes
a single spatial_fit too. No model is refitted: the fitted values
are read with fitted(), and newdata is scored with
predict(). compare_models() adds information criteria
and residual Moran's I to the same table.
Usage
evaluate_insample(fits, newdata = NULL, ...)
Arguments
fits |
A |
newdata |
Optional sf object for out-of-sample evaluation. Must contain the response variable and all predictors. If NULL, in-sample metrics are computed. |
... |
Passed to |
Details
The metrics are those of model_metrics(): see its sections
"What the metrics are computed on" and "Percentage errors on responses
with zeros".
Value
A data.frame with one row per model and columns for
model name, all regression metrics, and metric_basis: what the
row's metrics were computed on, "in-sample" (fitted values),
"out-of-bag" (an rf_fit's fitted values, see "What the
metrics are computed on") or "newdata". Rows with different
bases do not compare like for like. An element that is not a
spatial_fit is skipped, with a logged warning, and has no row;
a list in which no element is a spatial_fit is an error.
See Also
Other in-sample checks:
compare_models(),
model_metrics(),
print.morans_i(),
residual_morans_i()
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
)
# An offset keeps the response away from zero, where MAPE is undefined.
pts$z <- 10 + 2 * pts$a + rnorm(60, 0, 0.3)
# Fit on 40 rows and keep 20 back, so the second call is out of sample.
fit <- fit_rf_model(pts[1:40, ], "z", "a", num_trees = 50, seed = 1)
evaluate_insample(fit) # out-of-bag for a forest
evaluate_insample(fit, newdata = pts[41:60, ]) # on the 20 held-out rows
Fit a Bayesian Gaussian-process regression with brms
Description
Fits a regression whose residual spatial structure is modelled as a
Gaussian process over the coordinates, and so kept out of the errors.
Every quantity has a posterior, so predictions come with intervals;
cv_bayes() reports their held-out coverage and CRPS. The
spatial term is a smooth surface at a stated resolution. The Gaussian
process is fitted through a reduced-rank basis, and that basis has a
floor: an effective range below which it cannot represent structure,
reported in CRS units as $info$gp_resolution and by print().
With the defaults the floor is about 32 km along each axis on points
spread evenly over a 100 km square. Structure shorter than the floor is
counted as noise: the fitted range comes out too long, the residual
standard deviation too large, and the intervals too narrow where the
structure is. See "What the basis resolves" below.
Usage
fit_bayesian_spatial_model(
data_sf,
response_var,
predictor_vars,
family = NULL,
gp_k = NULL,
gp_c = NULL,
gp_iso = FALSE,
prior = NULL,
chains = 4,
iter = 2000,
warmup = floor(iter/2),
cores = getOption("mc.cores", 1L),
seed = 123,
backend = c("auto", "cmdstanr", "rstan"),
control = list(),
compute_loo = TRUE,
standardize_predictors = FALSE,
check_convergence = TRUE,
pointize = "auto",
boundary = NULL,
gp_resolution = NULL,
.already_prepped = FALSE
)
Arguments
data_sf |
An sf object with response, predictors, and geometries. |
response_var |
Response column name. |
predictor_vars |
Predictor column names. May be |
family |
A model family accepted by |
gp_k |
Positive integer giving the number of GP basis functions
per dimension, or NULL (default) to derive it from the
length-scale/domain ratio. The fitted model carries
|
gp_c |
Positive numeric boundary factor for the approximate GP, or
NULL (default) to derive it alongside |
gp_iso |
Logical; passed to |
prior |
Optional brms prior specification. When NULL and
|
chains |
Number of MCMC chains. Default 4. |
iter |
Total iterations per chain. Default 2000. |
warmup |
Warmup iterations. Default |
cores |
Number of cores for the sampler, one chain per core. Default
|
seed |
Integer seed. Default 123. |
backend |
|
control |
Named list of sampler controls, merged over the package
defaults |
compute_loo |
Logical; compute PSIS-LOO. Default TRUE. |
standardize_predictors |
Logical; centre and scale numeric predictors
before fitting. Default FALSE. When TRUE, the centre and scale of each
predictor are stored in |
check_convergence |
Logical, default TRUE. After fitting, read the
sampler's diagnostics and the GP basis against the posterior and the
residuals, and set |
pointize |
How a feature that is not a point is reduced to one: one of
|
boundary |
Optional polygonal sf/sfc whose CRS the data are projected to. It is not a clip: rows outside it are kept. |
gp_resolution |
The shortest effective range the basis should resolve,
as a single positive number in the units of the data's CRS (metres for a
UTM layer), or NULL (default) for the rule described under "GP basis
count and boundary factor". |
.already_prepped |
Internal; leave at the default. |
Details
The fitted length-scale is an estimate of how far the spatial dependence
reaches only when its posterior sits clear of both that floor and its
prior. $info$gp_adequacy says whether it does, and when it does
$info$gp_adequacy$effective_range holds the posterior effective range
per axis in CRS units (the raw lscale draws are in per-axis
standardised units and are not a distance).
Choose it over fit_gwr_model() when you want one global
relationship plus a spatial random field, with posterior intervals; choose
GWR when the question is how a coefficient varies across the map. Choose
fit_rf_model() when predictive accuracy matters more than an
interpretable model and the response is non-linear in the predictors. The
cost is time: this is full MCMC through brms and Stan, so a fit takes
minutes rather than seconds, and the basis size (gp_k) trades
fidelity against run time.
Value
A bayesian_fit object (inherits from spatial_fit).
Supports predict(), fitted(), residuals(),
coef(), summary(), and model_metrics().
Model-specific metadata lives in $info (coords: the names of the
scaled coordinate columns handed to brms::gp(); coord_scaling,
predictor_scaling, gp_k, gp_c, gp_iso, gp_n_basis, gp_ell_min,
gp_resolution: the smallest effective range the basis resolves, as
c(x, y) in CRS units; gp_resolution_requested: the
gp_resolution argument, or NULL;
gp_prefit: the check made before sampling, a list with status
("ok"; "below_floor", the one that warns;
"below_floor_no_autocorrelation" and
"below_floor_long_range", a range below the floor that the
short-lag or the floor-distance test did not bear out;
"not_estimated" or "not_run"), range (the
estimated range in CRS units), floor, k_needed,
moran and moran_floor (the two Moran's I tests, each with
I, z and a one-sided p; NULL where the
test is not run, or where the residuals are the rounding of an exact
fit), reason and
unit;
gp_adequacy: a list with status (see "What the basis resolves"), frac_below
(the share of length-scale draws below gp_ell_min),
identified and identified_by ("spatial_share" or
"length_scale", the rule that decided it; see "What the basis resolves"),
contraction (one minus the ratio of posterior to prior variance,
per length-scale, negative when the posterior is the wider of the two)
and prior_gap (the largest gap between the posterior's and the
prior's distribution functions, per length-scale; both NA for a
length-scale prior this function did not set), spatial_share and
sdgp (2.5,
50 and 97.5 percent quantiles; the share only for a gaussian or lognormal
family), effective_range (the posterior effective range per axis
in CRS units, same quantiles), residual_moran (the test on the
residuals the status rests on: I, z, a one-sided p
and k, the number of neighbours; absent when it could not be
run, and residual_untested then says why), resolution,
unit and prior_mass_below;
b_prior: the slope prior brms used ("(flat)" for its default,
NA for a model with no slopes), and b_prior_source: where it came
from; predictor_levels: the levels each factor or character predictor
has in the training rows, which predict() holds new data to;
gp_S: the pooled centred range brms::gp(c = ) multiplies;
gp_cmeans: the column means brms centred the scaled coordinates on;
gp_xy_range: the training extrema of the scaled coordinates, which
predict() uses, with gp_S and gp_cmeans, to hold the GP boundary
at its fitted value;
gp_lengthscale_bounds: the c(lower, upper) the length-scale prior
was calibrated over; gp_lscale_prior: the length-scale prior
brms::validate_prior() reports the model will actually use,
which is not necessarily the one this function requested (several entries,
semicolon-separated, if brms resolved the axes differently); loo, looic,
convergence_ok (TRUE or FALSE, and NA when nothing
was checked, as under check_convergence = FALSE),
convergence_diagnostics: n_divergent, n_max_treedepth,
ebfmi (per chain), max_rhat, min_neff_ratio,
min_ess (the smallest bulk or tail effective sample size) and
ess_required (100 per chain), and rhat_failed /
neff_failed / ess_failed, the parameters that failed each
check by name with their values (R-hat, ESS ratio and ESS; empty when
none failed), which is what makes a failed check actionable,
rhat_caution, the parameters whose R-hat is between 1.01 and 1.05
with enough effective draws, which do not fail the verdict, plus
gp_lscale_below_resolution and gp_adequacy, the share and
status described under "What the basis resolves"; and n_dropped: the rows
prep_model_data() removed for missing or non-finite values or a
bad geometry, so $n can be read against nrow(data_sf));
response_scaling: the centre and scale the response was
handed to brms with, absent when it was handed over as it is (see "The
response's centre and scale").
The raw brmsfit is in $engine.
Sampler settings
adapt_delta defaults to 0.99, not Stan's 0.8, because one divergent
transition sets convergence_ok to FALSE (see "Convergence
checks") and lower values can leave a few on ordinary data. A lower
value, such as list(adapt_delta = 0.9), runs faster, since the
smaller step of 0.99 costs sampling time. Some divergent transitions can
remain at 0.99 too, for example on a layer whose spatial field is weak
against the noise; then raise it to 0.995 or 0.999, which costs more time
again.
Convergence checks
Under check_convergence = TRUE the verdict in
$info$convergence_ok follows Stan's own diagnostics, with these
thresholds:
any divergent transition after warmup;
bulk or tail effective sample size below 100 per chain for any parameter (Vehtari et al. 2021; the rule rstan warns on). It is an absolute count, not a share of the draws;
rank-normalised split R-hat, in two tiers. Above 1.05, the value rstan's own sampler warning uses, for any parameter. Above 1.01, the value Vehtari et al. (2021) recommend, for a parameter whose effective sample size is also below the count in the previous item, or cannot be read;
E-BFMI below 0.3 in any chain (Betancourt 2016).
An R-hat between 1.01 and 1.05 on a parameter with enough effective
draws is a caution, not a failure: it is stored by name in
$info$convergence_diagnostics$rhat_caution, logged, and counted
by print(). The model has one weight per basis function, about
540 parameters at the basis derived for points spread evenly over a
square, and among that many the largest R-hat sits near 1.01 in a fit
that has converged. Vehtari et al. give 1.01 beside an effective sample
size above 400, so the two are read together here.
Transitions that stop at max_treedepth are counted and logged but
do not change the verdict: Stan treats them as a cost, not as invalid
draws. A failed verdict sets convergence_ok to FALSE,
raises one R warning of class spatialkit_convergence naming each
failed check with its count and its first five parameters, and
print() flags it; $info$convergence_diagnostics holds every
value. The warning closes with the remedy for the checks that failed: a
higher adapt_delta for divergent transitions, which more
iterations do not remove, and more iterations for R-hat and effective
sample size. A short run usually fails on effective sample size.
cv_bayes() marks such folds
in fold_metrics$convergence_ok and compare_models()
names such a model.
The same step checks the GP basis against the posterior and the
residuals (see "What the basis resolves") and stores the result as
$info$gp_adequacy. The residuals need the fitted values, one
pass over the posterior that fitted() caches for later calls.
That check is about the approximation, not the sampler, so it does not
change convergence_ok; print() and summary() show
its status, and two of its states raise a warning of class
spatialkit_gp_adequacy.
GP basis count and boundary factor
brms::gp() builds a full tensor grid over its covariates, so a term
gp(..x, ..y, k = gp_k) carries gp_k^2 basis functions: the
gp_k argument is the count per dimension, not the total rank.
Both gp_k and gp_c are therefore chosen from the ratio of the
estimated length-scale to the domain extent, following
Riutort-Mayol et al. (2023): gp_c is set large enough to contain the
upper length-scale bound, and gp_k large enough to resolve the lower
one. The derived value depends on the layout, not on n: about 23
for points spread evenly over a square; other layouts give other values,
up to the cap of 50.
The domain extent used is the one brms::gp(c = ) itself multiplies:
the full pooled range of the column-centred coordinates
(brms:::choose_L(), taken over the unique coordinate rows,
because brms:::.data_gp() reduces the covariates to unique rows first
under the default gr = TRUE, so repeat visits to one location do not
widen the domain), not the per-axis half-range in which
Riutort-Mayol et al. state their inequalities. Both constraints are on
the boundary L = c \times S, and stating them in brms's units keeps
gp_c, gp_k and $info$gp_ell_min describing the basis
brms builds. A
gp_c derived on the half-range convention and handed to
brms::gp() produces a boundary twice as wide as intended, against
which gp_k under-resolves by a factor of two.
The GP term is built with scale = FALSE. brms::gp() otherwise
rescales its covariates so the maximum Euclidean distance between two points
is 1, and reports lscale in that space; since this function already
standardises the coordinates, and the length-scale prior, gp_c and the
adequacy check below are all expressed in those standardised units, a second
normalisation would leave every length-scale quantity in the wrong units.
What the basis resolves
The smallest length-scale the chosen basis can resolve is
1.75 * gp_c * S / gp_k, stored in standardised units as
$info$gp_ell_min. As an effective range (the distance at which the
squared-exponential correlation has fallen to 5 percent, 2.45 length-scales)
and in CRS units it is $info$gp_resolution, one value per axis
because each coordinate is divided by its own standard deviation. The
floor is soft: the basis keeps 99 percent of a process's variance at the
floor, 69 percent at half of it and 41 percent at a third. The default
length-scale prior is what makes it bind, with 1 percent of its mass below
the floor and about one part in a hundred million below half of it.
Three checks hold the basis against the data.
Before anything is compiled, the autocorrelation range of the response (of its OLS residuals when there are predictors) is estimated with
estimate_sac_range()and compared with the coarser axis's floor. That range is a variogram estimate and can be wrong in both directions, so a range below the floor raises a warning only when two other things agree with it. The same variable is autocorrelated at short range (Moran's I over 4 nearest neighbours, one-sided, at 5 percent): a variogram fitted to a response with no spatial structure can still return a short range, thoughestimate_sac_range()refuses most such layers itself. And it is no longer autocorrelated at the floor's distance (Moran's I over the pairs 0.75 to 1.25 floors apart is not both above 0.05, the correlation that defines an effective range, and significant at 5 percent): a variogram can also return a short range for a surface that is smooth over long distances. The warning has classspatialkit_gp_resolution, gives both numbers and the basis size that would resolve the range, says that it is an estimate which the check after sampling tests against the residuals of the fitted model, and says when the basis size is past the cap or past the number of rows, where kriging is the better tool if the range is right. A short range the floor-distance test contradicts is logged and shown byprint()without a warning: it can still mean short-range structure beside a longer one, which the basis counts as noise. Nothing before sampling separates the two; the residuals after it do (the third check). A range that cannot be estimated is logged with the reason and shown byprint(); the result is in$info$gp_prefit. An exponential field has structure at every scale, so the warning on one is not plainly wrong.Also before sampling, the share of the length-scale prior below the floor is computed (
$info$gp_adequacy$prior_mass_below). A derived basis keeps it near 0.01; a smallgp_kdoes not, and a share above 0.10 is logged and flagged byprint().After sampling, under
check_convergence = TRUE, the posterior and the residuals are read. The posterior says whether the Gaussian process carries a share of the variance and where its length-scale sits against the floor. It cannot say what the surface left behind, so the residuals are tested for autocorrelation at short range in every fit (Moran's I over 4 nearest neighbours, one-sided, at 5 percent;$info$gp_adequacy$residual_moran).$info$gp_adequacy$statusis one of:"ok"The Gaussian process carries a share of the variance, its length-scale is clear of the floor, and the residuals show no autocorrelation at short range. A surface smoother than the prior expects (a plane, a range longer than the extent) is
"ok": its length-scale posterior sits on the long side of the prior and is wider than it."below_resolution"The Gaussian process carries a share of the variance and more than 10 percent of the length-scale draws fall below the floor. The 10 percent trigger is this package's operationalisation of the check Riutort-Mayol et al. recommend, not a figure from the paper.
"unresolved_short_range"The residuals are autocorrelated at short range: the signature of structure finer than the basis, counted as noise. It is reached two ways, and
$info$gp_adequacy$identifiedsays which. The Gaussian process carries no variance that can be told from zero (FALSE): all of the structure is below the floor. Or it carries a share and its length-scale is clear of the floor (TRUE): it fitted a surface, and finer structure sits beside it, as with a regional trend plus short-range structure."no_signal_above_floor"The Gaussian process carries no variance that can be told from zero, and the residuals show nothing left over. A response with no spatial structure gives this, so it is not a failure by itself.
"not_checked"check_convergence = FALSE.
The second and third raise a warning of class
spatialkit_gp_adequacy; the fourth is logged. When the residuals cannot be tested (an ordinal or categorical family has no residual per row; a posterior that cannot be drawn), the status rests on the posterior alone, a line is logged, the reason is in$info$gp_adequacy$residual_untested, andprint()keeps its flag on a variogram range that was below the floor.On a fit with nothing left over the test is conservative, because the surface takes up part of the noise and leaves the residuals slightly negatively autocorrelated. It is not sharp just below the floor, where the length-scale draws report the structure (
"below_resolution"). An exponential field has structure at every scale and can be reported with a range above the floor. The 5 percent level is the usual one and is not tuned; with many rows a small leftover autocorrelation is significant, so read the size of I beside its p."No variance that can be told from zero" is decided on the Gaussian process's share of the variance,
sdgp^2 / (sdgp^2 + sigma^2): its 2.5 percent quantile is under 0.01. It does not mark off a response whose structure is all below the floor: such a process can still carry a share, and the residual test reports it. The share exists for a gaussian or lognormal family. For any other family the length-scales decide instead: the process is not identified when on every axis the posterior kept more than three quarters of its prior's variance and the largest gap between its distribution function and the prior's is under 0.30.$info$gp_adequacy$identified_bysays which rule was used. The width of the length-scale posterior does not decide by itself, because a posterior that moved to longer length-scales is wider than its prior; and the share of draws below the floor cannot detect an unidentified process, because a posterior the data did not move puts 1 percent below the floor, the same as the prior.
A response whose range is below the floor needs a finer basis and a prior
that allows the shorter length-scale, both of which gp_resolution
sets, up to the cap. Past the cap this model cannot resolve the range,
and kriging, which has no such floor, is the better tool; see
kriging_adequacy() for cell means.
Coordinate scaling and anisotropy
Before fitting the GP, X and Y coordinates are each centred and divided by their own standard deviation. This is a conditioning step: easting and northing frequently span very different ranges in a projected CRS, and handing Stan raw metres samples poorly.
Because the axes are scaled independently, a single shared
length-scale in the scaled space corresponds to an anisotropic kernel in the
original CRS, stretched by the ratio sd(X)/sd(Y). That ratio is a
property of how the sampling locations are laid out, not of the process
being modelled.
gp_iso = FALSE (the default) therefore fits one length-scale per
axis, letting the model estimate directional structure from the data instead
of inheriting it from the standardisation. Set gp_iso = TRUE for
one length-scale shared by both standardised axes.
gp_iso does not affect cost: brms::gp() builds a
tensor grid either way, so the model carries gp_k^2 basis functions
regardless. The stored $info$coord_scaling list records the scaling
strategy, and $info$gp_iso records which kernel was used.
Warnings
Every warning this function raises carries a condition class, so a caller can catch or muffle exactly one of them by name:
spatialkit_rows_dropped,spatialkit_constant_predictorFrom
prep_model_data(): incomplete rows were dropped, with the counts; a predictor takes one value in every row kept.spatialkit_response_scaleThe response lies far from zero or its standard deviation far from 1, and
priorsets a prior on a class on the response's scale, so the response is handed to brms as it is; see "The response's centre and scale".spatialkit_gp_basis_sizeFewer than one row per ten basis functions.
spatialkit_gp_resolutionA variogram fitted before compiling puts the response's range below what the basis resolves, and the autocorrelation of the response agrees. An estimate; the check after sampling tests it against the residuals of the fitted model.
spatialkit_convergenceThe sampler's diagnostics fail.
spatialkit_gp_adequacyThe basis is too coarse for the data: the posterior asks for a shorter length-scale than it resolves (
"below_resolution"), or the residuals are autocorrelated at short range ("unresolved_short_range").
A response that takes a single value is an error, raised before anything
is compiled, and so is one whose values differ only by rounding (1e15 and
the next double). A fit that comes back from brms with no posterior
draws, as when Stan rejects every starting value, is an error that names
the response's size as brms was given it. The convergence warning
carries the checks that failed as
failed ("divergent", "ebfmi", "rhat",
"ess"). cv_bayes() fits once per fold; it collects
the last four classes from its folds and raises each once for the run,
naming the folds, and cv_spatial() does the same for a
fit_fn that calls this function.
The response's centre and scale
Stan starts every parameter between -2 and 2, and brms sets its default
priors for the intercept, the residual standard deviation and the
Gaussian process's standard deviation from the response it is given, with
scales of at least 2.5 in its units. A response at 1e8 plus a spread of 1,
or in units of 1e-20, lies far from both, and brms can miss the data by
orders of magnitude. So under the gaussian, student, skew_normal,
exgaussian and asym_laplace families with an identity link, a response
whose centre is more than 1,000 times its spread from zero is handed to
brms less that centre, and one whose standard deviation lies outside
2^{-20} to 2^{20} is divided by the power of two nearest that
standard deviation. Under exgaussian and asym_laplace the rule is
narrower: a centre more than 4 times the spread from zero is taken off,
and a standard deviation outside 2^{-2} to 2^{2} is divided
out, because brms's default prior on exgaussian's beta and Stan's
starting values do not follow the response. Both steps are exact, and the model is the same
model of the response: the shift moves the location only, and the scale
multiplies the location, sigma and the mean beta of
exgaussian's exponential part, and leaves the degrees of freedom of
student, the skewness of skew_normal and the quantile of asym_laplace as
they are. Every other response, and every response under another
family, is handed over as it is.
fitted(), predict() and its draws, residuals(),
coef(), $info$loo, $info$looic and
$info$gp_adequacy$sdgp are put back in the response's units, and
$info$b_prior gives the automatic slope prior in those units. The
same data from another origin or in other units then give the same fit,
up to Monte Carlo error. The centre and scale are in
$info$response_scaling. $engine is the fit of the response
brms was given, so brms's own functions on it (brms::fixef(),
brms::posterior_epred()) answer on that scale.
A prior given in prior on a class on the response's scale
(b, Intercept, sigma, sdgp, and beta
of exgaussian) is read by brms on the response it is given. With such a
prior the response is handed over as it is, and the warning
spatialkit_response_scale says so.
Non-Gaussian responses
Nothing in this function is Gaussian-specific except its default. A numeric count, binary (0/1 or logical) or bounded response passes through to brms under the family you name, with the GP term in the formula and the length-scale prior attached to each distributional parameter's GP.
The response check is family-aware. A factor or character response is
accepted only under brms::categorical() or an ordinal family
(cumulative, sratio, cratio, acat), and refused
under every other family before anything is compiled; under gaussian a
logical response is refused too. The case to watch is a two-level factor
under brms::bernoulli(): brms would fit it, but
residuals(), summary(), model_metrics() and
cv_bayes() could not score a factor, so convert it to 0/1
first.
An ordinal or categorical fit has a probability per response category, not
one expected value per row. predict() with its default
type = "epred", fitted(), residuals(),
summary() and model_metrics() therefore stop with a message
saying so, and cv_bayes() refuses the family before fitting
anything. predict(type = "predict", draws = TRUE) returns the
posterior predicted categories, as category indices, for new rows as well
as the training ones (the share of draws in each category estimates its
probability), and brms::posterior_epred(fit$engine) the
probabilities for the training rows.
For the numeric families two things follow. First, the metrics that come
back from model_metrics() and the cv_*() functions are
not all meaningful for such a response: RMSE and MAE are, MAPE, SMAPE and R-squared
are Gaussian-shaped, and for this backend cv_bayes()'s CRPS
and interval coverage are the proper scores to read. See
model_metrics(), section "Which metrics survive a
non-Gaussian response". Second, estimate_sac_range() fits
a variogram to the raw response (or OLS residuals), whose variance tracks
its mean for a count; the range it reports is then less trustworthy than
for a Gaussian response, and its help page says how.
The response check reads the family's name through brms's own accessor. If brms cannot name the family object, the check is skipped, and a wrong response type surfaces as a Stan error with no message from this function.
Spatial confounding
A fixed-effect coefficient estimated alongside a spatial random effect is a
different quantity from the same coefficient in a non-spatial fit. When a
covariate is itself spatially smooth, the GP term absorbs part of its
effect and the two estimates can disagree sharply; when the response is
smoother than the covariate, the estimate can shrink toward zero regardless
of the true effect (Bolin and Wallin 2026). Under a correctly specified
spatial model this is not a bias but a change of estimand (Zimmerman and
Ver Hoef 2022): the spatial coefficient is the effect net of whatever
the spatial field can explain, and the non-spatial one is not. The right
one depends on the question, so report both side by side, unadjusted: fit
the same formula with stats::lm() or stats::glm() and
compare. Compare like
with like: under standardize_predictors = TRUE the coefficients here
are per standard deviation of each predictor, so either fit the
non-spatial model on the same standardised columns or divide these slopes
by $info$predictor_scaling[[name]]$scale first (see
spatial_fit-coef).
Published work on remedies is unsettled, and this function takes no side. Restricted spatial regression (Hughes and Haran 2013) projects the spatial effect off the covariate space; later work argues it does not deliver what it promises (Hanks et al. 2015; Khan and Calder 2022). Within this backend, modelling the covariate and the spatial field as explicitly correlated (Marques, Kneib and Klein 2022) is expressible in a brms formula with no new code, and a spectral adjustment (Guan et al. 2023) is the principled route that suits a Hilbert-space basis; this function does not implement it.
References
Betancourt, M. (2016). Diagnosing suboptimal cotangent disintegrations in Hamiltonian Monte Carlo. arXiv:1604.00695.
Vehtari, A., Gelman, A., Simpson, D., Carpenter, B. and Burkner, P.-C. (2021). Rank-normalization, folding, and localization: an improved R-hat for assessing convergence of MCMC (with discussion). Bayesian Analysis 16, 667–718. doi:10.1214/20-BA1221
Riutort-Mayol, G., Burkner, P.-C., Andersen, M. R., Solin, A. and Vehtari, A. (2023). Practical Hilbert space approximate Bayesian Gaussian processes for probabilistic programming. Statistics and Computing 33, 17. doi:10.1007/s11222-022-10167-2
Bolin, D. and Wallin, J. (2026). Spatial self-confounding: smoothness-related estimation bias in spatial regression models. Biometrika 113(1), asaf076. doi:10.1093/biomet/asaf076
Guan, Y., Page, G. L., Reich, B. J., Ventrucci, M. and Yang, S. (2023). Spectral adjustment for spatial confounding. Biometrika 110, 699–719. doi:10.1093/biomet/asac069
Hanks, E. M., Schliep, E. M., Hooten, M. B. and Hoeting, J. A. (2015). Restricted spatial regression in practice: geostatistical models, confounding, and robustness under model misspecification. Environmetrics 26, 243–254. doi:10.1002/env.2331
Hughes, J. and Haran, M. (2013). Dimension reduction and alleviation of confounding for spatial generalized linear mixed models. Journal of the Royal Statistical Society: Series B 75, 139–159. doi:10.1111/j.1467-9868.2012.01041.x
Khan, K. and Calder, C. A. (2022). Restricted spatial regression methods: implications for inference. Journal of the American Statistical Association 117, 482–494. doi:10.1080/01621459.2020.1788949
Marques, I., Kneib, T. and Klein, N. (2022). Mitigating spatial confounding by explicitly correlating Gaussian random fields. Environmetrics 33, e2727. doi:10.1002/env.2727
Zimmerman, D. L. and Ver Hoef, J. M. (2022). On deconfounding spatial confounding in linear models. The American Statistician 76, 159–167. doi:10.1080/00031305.2021.1946149
See Also
cv_bayes() to score the fit on spatial folds;
predict() (spatial_fit-predict) and coef()
(spatial_fit-coef); gp_lengthscale_bounds() for the
length-scale range the prior is set over.
Other model fitting:
fit_gwr_model(),
fit_rf_model(),
gp_lengthscale_bounds(),
new_spatial_fit()
Examples
## Not run:
# Not run: fits with Stan, which needs a working C++ toolchain and takes
# minutes of sampling.
if (requireNamespace("brms", quietly = TRUE)) {
library(sf)
set.seed(1)
n <- 60
dat <- st_as_sf(
data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
elev = rnorm(n)),
coords = c("x", "y"), crs = 32632
)
dat$price <- 10 + 0.01 * (st_coordinates(dat)[, 1] - 5e5) +
2 * dat$elev + rnorm(n)
# Two short chains keep this to a few minutes; Stan may warn about
# effective sample size, which is the cost of that. Use its defaults
# (chains = 4, iter = 2000) for a fit to report.
fit <- fit_bayesian_spatial_model(dat, "price", "elev",
chains = 2, iter = 1000,
compute_loo = FALSE)
print(summary(fit))
head(predict(fit, newdata = dat))
# A zero-inflated count. The family is the only thing that changes.
# summary()'s R2 and MAPE assume a Gaussian response, so for a count
# read the coefficients here and score the model with cv_bayes(), whose
# CRPS and interval coverage are defined for any response.
dat$count <- rpois(n, exp(0.5 + 0.8 * dat$elev)) * rbinom(n, 1, 0.7)
fit_zip <- fit_bayesian_spatial_model(dat, "count", "elev",
family = brms::zero_inflated_poisson(),
chains = 2, iter = 1000,
compute_loo = FALSE)
coef(fit_zip)
}
## End(Not run)
Fit a geographically weighted regression (GWR)
Description
Fits a Gaussian GWR on an sf layer with an adaptive or a fixed bandwidth.
Each location gets its own regression, weighted towards nearby
observations, so the coefficients can vary across the map. Use it when
that variation is the question; fit_bayesian_spatial_model()
fits one global relationship plus a spatial random field.
Usage
fit_gwr_model(
data_sf,
response_var,
predictor_vars,
adaptive = TRUE,
bandwidth = NULL,
kernel = c("bisquare", "gaussian", "tricube", "boxcar", "exponential"),
.already_prepped = FALSE
)
Arguments
data_sf |
An sf object with response, predictors, and geometries. |
response_var |
Response column name. |
predictor_vars |
Predictor column names (numeric columns; a name given
twice counts once). |
adaptive |
Logical; use adaptive bandwidth. Default TRUE. When TRUE, bandwidth is an integer number of nearest neighbours. When FALSE, bandwidth is a fixed distance in CRS units. |
bandwidth |
Optional numeric bandwidth value. For adaptive mode this
is an integer (number of neighbours); for fixed mode a distance in the
units of the projected CRS the fit runs in. |
kernel |
Weighting kernel: one of |
.already_prepped |
Internal; leave at the default. |
Details
The kernels, the bandwidth conventions and the diagnostics are those of GWmodel. This package solves the local regressions itself, each as a weighted least squares by pivoted QR, so a window whose design is rank deficient neither stops the fit nor returns coefficients made of rounding error.
Value
A gwr_fit object (inherits from spatial_fit).
Supports predict(), fitted(), residuals(),
coef(), summary(), and model_metrics().
Model-specific metadata lives in $info: bandwidth, adaptive,
kernel, AICc (NA, with a warning, where AICc is
undefined: its effective number of parameters tr(S) is not below
n - 2, the local regressions all but interpolate the data, and the
large negative value the formula gives would rank the fit above any
other; also where the fit reproduces the mean of the observations at
each location, see Observations that share a location),
bandwidth_is_fallback (TRUE when no bandwidth could
be selected: the search failed and the arbitrary fallback was used, or
no bandwidth has a defined criterion and the widest was used),
condition_index (the global index), local_collinearity
(one row per observation: row, x, y,
n_window, cn and cn_slopes, see
Collinearity diagnostics, then rank, the rank the local
solve found, and leverage, the observation's diagonal of the hat
matrix), n_local_collinear (the
locations whose slopes count as collinear), n_local_singular
(the locations with a local coefficient that is NA),
n_rank_deficient (the windows whose rank is below the number of
parameters), n_saturated (the windows whose fitted value is their
own observation: leverage 1),
nonfinite_coef (a logical matrix, one row per observation and
one column per term, with Intercept first, TRUE where the
local coefficient is NA, so the count in
n_local_singular can be placed), n_dropped (the rows
prep_model_data() removed for missing or non-finite values or a
bad geometry, so $n can be read against nrow(data_sf)),
n_locations (the distinct locations of the rows fitted; see
Observations that share a location),
tr_S, enp, edf and sigma2 (the trace of the
hat matrix, the effective number of parameters
2\,tr(S) - tr(S^\top S), the effective residual degrees of freedom
and the residual variance, as GWmodel defines them),
global_ols (RSS, RMSE and AICc of one
least-squares regression on the same rows, the AICc by the same formula
with the regression's rank as its trace; a GWR whose AICc is no lower
has not shown that its coefficients vary, and summary() prints
the two side by side),
rank_tolerance, max_kernel_width (the widest kernel at any
observation, which predict() measures new locations against) and
bandwidth_search (see Bandwidth selection; NULL
when a bandwidth was supplied).
$engine holds the fit in the layout of the object
GWmodel::gwr.basic() returns, under the same names: SDF (a
SpatialPointsDataFrame of the local coefficients, y,
yhat, residual, CV_Score, Stud_residual, the
standard errors <term>_SE, the t values <term>_TV and
Local_R2), GW.diagnostic, GW.arguments and
lm (the global least-squares fit). It is a plain list, not a
gwrm object. Where a predictor or the response was taken less
its centre (see "The local solve"), lm is solved on the
centred columns and returned as the fit at the data's origin: its
coefficients, fitted values, qr and effects are those of
the raw columns, so summary(), vcov(), confint()
and predict() on it give the intercept at the data's 0 and its
standard error, and the slopes and residuals are those of the centred
fit. With a predictor more than about 1e7 times its spread from 0,
predict(se.fit = TRUE) on it stops with "singular matrix":
qr.solve() reads the triangular factor at the data's origin as
singular. predict() on the fit itself has no such limit.
centres holds what was taken off: predictors, the centre
of each column of the design (Intercept first, 0 for a column
used as it is), NULL where none was, and response, 0
where none was.
The local solve
At every observation the model is a weighted least squares on the
observations whose kernel weight is above zero. It is solved by a
Householder QR with column pivoting of the window's weighted design, never
by inverting X^\top W X. Before the factorisation each row is
multiplied by the square root of its weight over the window's largest
weight, and each predictor is divided by its standard deviation over the
whole data and centred in the window, so nothing below depends on a
predictor's origin or units: an indicator coded 0/1 and one coded
288.7/289.3 give the same fit.
Under the boxcar kernel an observation whose squared distance is within
one part in ten million of the window's edge counts as at the edge, and
inside, so on a regular grid every neighbour tied with the last one is in
the window in any unit and at any origin where the doubles hold the
coordinates to better than about one part in 1e8 of the distances
between neighbours. Farther from the origin the doubles round the
coordinates more coarsely, and where a neighbour lies past the edge by
less than that rounding the call warns, with class
"spatialkit_xy_imprecise" (see "Coordinates far from the origin"
in spatialkit-geometry); the windows are those the coordinates as
stored give.
A predictor whose centre is more than 1000 times its spread (a timestamp
in seconds, a northing, 1e8 plus a spread of 1) is taken less its centre
first. So is a response whose centre is more than 1000 times its spread
(1e8 plus a spread of 1), whose raw values lose their spread to rounding
(1e15 plus a spread of 1, stored to an eighth), or whose least-squares
residuals on the predictors do. The bandwidth search, the
local regressions, the global least-squares fit and the centred condition
indices (info$condition_index, cn_slopes) then work on the
spread and not on the rounding of the offset, and the centres are added
back only to what is returned in the data's units: the fitted values, the
local intercepts, the intercept and fitted values of $engine$lm,
and predict()'s values, which take a new row's predictors about the
same centres. Residuals, slopes and their standard errors, AICc and the
bandwidth are those of the same values at 0, to rounding; the fitted
values and predictions of a response at 1e15 are held to the eighth a
double holds there. model_metrics(), summary() and the
cross-validations score the fit on the response, the fitted values and
the predictions less the response's centre, so their RMSE, MAE and
R-squared are those of the same values at 0 too. Every other predictor
and response is used as it is.
A response whose values, less any centre, reach beyond 1e100, or whose
spread is below 1e-100, is divided by a power of two, which rounds
nothing: the residual sum of squares, AICc and the bandwidth search
square the residuals, and at 1e160 those squares overflow and at 1e-160
they lose their bits. The bandwidth is then that of the same values in
ordinary units, and the fitted values, the residuals, the coefficients,
their standard errors and $engine$lm are those of the same values
times the factor; AICc, the AICc of info$bandwidth_search among
them, gains 2 n \log of the factor, and a cross-validation score
of the search is multiplied by its square. The residual sum of
squares, info$sigma2 and such a score are in the response's units
squared, and are NA, with a warning, where a double cannot hold
them there;
predict(se.fit = TRUE) then takes its standard errors from the
residual standard deviation, which it can hold.
One tolerance, 1e-7, decides what a window can estimate:
Rank. A predictor is aliased in a window when the part of it that the terms entered before it do not explain varies there by less than
1e-7of its standard deviation over the study area (the length of that part over the weighted rows). A predictor that is constant among the weighted observations, two predictors that are exactly collinear there, and a window with fewer weighted observations than parameters are the cases. No weight is cut off: under a Gaussian or exponential kernel every observation enters, and distant ones stop counting only through this rule.Coefficients. A coefficient is returned when it has one value over all least-squares solutions of the window, and is
NAotherwise. The slope of an aliased predictor isNA. So is the intercept when a predictor is constant in the window at a value other than 0, because it would absorb that value times the slope; when the constant is 0 the intercept is identified and returned. The slopes of the other predictors are returned.Fitted values. The fitted value at an observation is always estimable (its own row is in its window) and is returned, also where a coefficient is
NA.
A window of deficient rank does not stop the fit. A warning of class
"spatialkit_gwr_rank_deficient" says how many windows are affected
and how many coefficients of each term are NA;
info$n_rank_deficient, info$n_local_singular,
info$nonfinite_coef and the rank column of
info$local_collinearity locate them. When many windows hold a
predictor constant, a local coefficient is the wrong model for it: its
effect is identified only as one global coefficient (a mixed GWR, as
GWmodel::gwr.mixed() fits).
The leverage of each observation, the trace of the hat matrix, the
residual sum of squares, AICc and the coefficients' standard errors come
from the same decomposition. On a window of full rank every one of them
equals what GWmodel::gwr.basic() returns, to rounding error: the
largest relative difference in any cell of the six fits the package's
tests compare is 3e-12. They are not bit-identical, since GWmodel
inverts the normal equations.
Bandwidth selection
With bandwidth = NULL the AICc is scored on 16 bandwidths spaced
evenly in the logarithm over the whole range, and then refined by a
golden-section search between the grid points either side of the best
(and, for a count of neighbours, at the counts next to the one it ends
on). That is about 20 to 35 fits of the model in all.
The range runs, for an adaptive bandwidth, from the smallest count the
model's parameters allow to every observation; for a fixed one, from the
distance at which half of the windows hold one observation more than the
model has parameters (a third of it for the Gaussian and exponential
kernels) to the largest distance between two observations. The bandwidth
returned is the best of all those scored.
A golden-section search over the whole range, which
GWmodel::bw.gwr() runs, assumes the criterion has one minimum. It
has several when the coefficients vary at a range that only a few dozen
observations resolve, and that search then returns a bandwidth near the
top of the range, a nearly global regression, as the selected one.
A candidate bandwidth with windows of deficient rank is scored on its
fitted values, which those windows do estimate. One at which AICc is
undefined (tr(S) not below n - 2) cannot be selected, and
neither can one at which a term of the model is estimable at no location:
the fit would have no coefficient for it anywhere.
The criterion at a candidate comes from the local solve. Under a Gaussian
or an exponential kernel, which weight every observation at every
location, the fitted value and leverage of a window that is far from rank
deficient are computed from its centred cross-products, many windows to
one matrix product, and the windows that are not are left to the QR; the
two routes agree to rounding error (1e-9 relative in the package's
tests) and take the same rank decisions. With several strongly
correlated predictors more windows are left to the QR and the search is
slower. The fit at the selected bandwidth is always the QR's.
Everything scored is kept in info$bandwidth_search:
approach (the criterion minimised, "AICc" or "CV"),
by_location and n_locations (see Observations
that share a location), curve
(bandwidth, criterion, trace of the hat matrix, windows of deficient rank,
and whether the point belongs to the grid or the refinement),
undefined (how many of the bandwidths scored have no criterion,
by reason),
n_local_minima and multimodal (local minima on the grid),
within and flat (the range of bandwidths whose AICc is
within 2 of the minimum, and whether half the grid is),
near_global (the widest bandwidth of the range is within 2 of the
minimum), at_upper and at_lower (the minimum is at an end
of the range). When any of these holds, one logged line says so (on the
console, unless spatialkit_quiet() is on; in the trace only
for the folds of a cross-validation); it is a
message, not a warning, because a minimum at or near the top of the range
is the ordinary outcome for a process whose coefficients do not vary.
Read near_global as "AICc does not tell this fit from one global
regression".
AICc is an in-sample criterion and rewards interpolation between
neighbours. The bandwidth it selects can score worse than a wider one on
held-out spatial blocks; cv_gwr with a supplied
bandwidth is the check.
Observations that share a location
Rows with the same coordinates (several years at one station, replicate
samples of one plot, records geocoded to one address) get one kernel
weight at every regression point. info$n_locations is the number
of distinct locations, and when it is below n a warning of class
"spatialkit_gwr_repeated_locations" gives the counts.
The bandwidth is then not selected by AICc. AICc counts the rows at one
location as independent observations. When a location has an effect of
its own, a window that holds little but the location reproduces its
mean, the residual sum of squares falls to the spread within locations,
and AICc is lowest where the windows interpolate, which is where the
error of predicting new sites is largest. A floor on the bandwidth does
not repair that, because the criterion keeps falling towards the floor.
With bandwidth = NULL the search therefore minimises the
leave-one-location-out sum of squares: each location's
observations are predicted by the local regression there without any of
them, the kernel keeping its width, and the squared errors are summed.
It is computed from the hat matrix of the fit at each bandwidth, without
refitting. A bandwidth at which some location cannot be predicted from
the others cannot be selected. info$bandwidth_search$approach is
then "CV" and by_location is TRUE. On a layer
without repeat locations nothing changes: the criterion is AICc.
The range of the search counts locations. For an adaptive bandwidth it starts at the smallest count that gives every window one location more than the model has parameters, and for a fixed bandwidth at the distance at which half the windows hold that many locations.
AICc and the standard errors still assume independence.
info$AICc, the comparison with the global regression in
summary() and the standard errors of coef(se = TRUE) and
predict(se.fit = TRUE) treat every row as an independent
observation. With an effect shared by the rows of a location the standard
errors are too small, and AICc compared across bandwidths favours the
small ones. info$AICc is NA, with a warning, when the fit
(nearly) reproduces the mean of the observations at each location:
tr(S) is then not below the number of rows that differ in location
or in a predictor, minus 2, and the value the formula gives measures only
the spread among observations that share a location. If the repeats are
replicates of one measurement, fit their means, one row per location.
Collinearity diagnostics
The function computes scaled condition indices of the design and
warns when one exceeds 30, the conventional threshold, which Wheeler &
Tiefelsdorf (2005) carry over to the local designs of GWR. An index is
the ratio of the largest to the smallest singular value (from an SVD) after
each column is scaled (Belsley, Kuh & Welsch 1980); an exactly singular
design gives Inf, which counts as the worst case, not an exempt one.
Scaling makes the index independent of the predictors' units;
kappa() on the raw matrix is not, and a threshold on it is a
threshold on nothing in particular.
A global index is computed on the predictors centred at their means
(with the intercept, which centring makes orthogonal to them), and kept as
info$condition_index. It measures how nearly the predictors are
collinear with one another over the whole study area; it is 1 for a single
predictor, and a change of origin (degrees C or kelvin, a year or years
since 2000) does not move it.
Local indices are then computed at every location, on the weighted
design of the local regression there: each row weighted by the square root
of its kernel weight at the bandwidth the model is fitted with (supplied or
selected), with rows of negligible weight (below 1e-8) dropped. A window
left with fewer rows than columns counts as singular. Two indices are
kept for each window, as columns of info$local_collinearity:
cnBelsley's index of the intercept plus the predictors, scaled to unit length but not centred. A predictor whose values in the window are far from 0 against their spread (a year, a temperature in kelvin) is collinear with the intercept and raises it: the local intercept is then an extrapolation to 0 and is ill-determined, but the slopes are not.
cn_slopesThe index for the slopes: the predictors centred at their weighted mean in the window and each divided by its standard deviation over the whole study area. It is 1 when the predictors vary as much, and as independently, inside the window as they do across the study area; it grows as a predictor becomes nearly constant inside the window (a regional covariate) or two predictors move together there. It does not depend on the predictors' origin or units.
A window's slopes count as collinear when cn_slopes is above 30 or
singular. Those windows are counted in info$n_local_collinear. A
predictor that is constant, or nearly so, inside a window is caught this
way whether it is alone or has company, so a single predictor is surveyed
too. cn does not enter: the local solve centres each predictor in its
window, so a predictor far from zero (a year, a temperature in kelvin, a
coordinate) has the slopes it would have at any other origin, and is not
flagged, however large cn is. The one exception is a cn that is
singular to machine precision, where the predictor's spread is lost in the
rounding of its own values.
A warning is issued whenever any location has collinear slopes; the
wording reports a percentage when more than 25% of locations are affected
and a count otherwise. Both are real R warnings, not log lines.
Coefficients at a near-singular window are least-squares estimates with
little to rest on, and can be implausibly large. An exactly singular
window (an indicator that is constant inside it, or fewer observations
than parameters) is of deficient rank: the coefficients it cannot estimate
are NA and the fit is returned (see "The local solve").
A window with only cn above 30 raises no warning:
plot(fit, type = "coefficients", term = "Intercept") masks it, and slope
maps do not. Centre such a predictor if you want an interpretable local
intercept. The survey is a caution about how well a coefficient is
determined, on rows whose weight is not negligible; the solve's rank is
the statement about whether it is determined at all.
A further warning counts local regressions that have no fitted value.
That happens where the kernel weights are undefined: with an adaptive
bandwidth of k, a location where k or more observations share the same
coordinates has a kernel of zero width, and every kernel but the boxcar
divides 0 by 0 there. The warning names that cause when it applies.
fitted(), residuals(), summary() and model_metrics() all drop those
rows, so when this warning fires the metrics describe only the part of the
study area that fitted.
See Also
cv_gwr() to score the fit on spatial folds;
predict() (spatial_fit-predict) and coef()
(spatial_fit-coef) for predictions and local coefficients;
gwr_model_selection() and
select_features_forward() to choose the predictors;
plot.spatial_fit() to map the coefficients.
Other model fitting:
fit_bayesian_spatial_model(),
fit_rf_model(),
gp_lengthscale_bounds(),
new_spatial_fit()
Examples
library(sf)
set.seed(1)
n <- 80
dat <- st_as_sf(
data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
elev = rnorm(n)),
coords = c("x", "y"), crs = 32632
)
# The slope on elev rises from 1 in the west to 3 in the east.
east <- (st_coordinates(dat)[, 1] - 5e5) / 1000
dat$price <- 10 + (1 + 2 * east) * dat$elev + rnorm(n, 0, 0.3)
fit <- fit_gwr_model(dat, "price", "elev", bandwidth = 30)
summary(fit)
# The local slopes follow the west-east change.
summary(coef(fit)$elev)
head(coef(fit, se = TRUE)$se) # their standard errors
head(predict(fit, newdata = dat))
Fit a random forest with ranger
Description
Fits a regression random forest on an sf layer and returns it as a
spatial_fit, so it works with cv_spatial(),
predict_surface(), area_of_applicability()
and the plot() method like any other backend. A forest suits a
response that is non-linear in its predictors when predictive accuracy
matters more than an interpretable model.
Usage
fit_rf_model(
data_sf,
response_var,
predictor_vars,
num_trees = 500L,
mtry = NULL,
min_node_size = NULL,
importance = c("permutation", "impurity", "none"),
include_coords = FALSE,
replace = TRUE,
sample_fraction = NULL,
seed = 123L,
num_threads = NULL,
.already_prepped = FALSE,
...
)
Arguments
data_sf |
An sf object with response, predictors and geometry. |
response_var |
Response column name. |
predictor_vars |
Predictor column names. |
num_trees |
Number of trees. Default 500. |
mtry |
Predictors sampled per split. |
min_node_size |
Minimum node size. |
importance |
|
include_coords |
Add the coordinates as predictors. Default
|
replace |
Logical; grow each tree on a bootstrap sample drawn
with replacement ( |
sample_fraction |
Fraction of rows drawn for each tree. |
seed |
Seed passed to ranger. Default 123. |
num_threads |
Threads for ranger. Default |
.already_prepped |
Internal; leave at the default. |
... |
Passed to |
Value
An rf_fit object (inherits from spatial_fit).
$info carries num_trees, mtry, min_node_size,
importance_type, importance (a named numeric, or
NULL when importance = "none"), include_coords,
categorical_predictors (the unordered factor and character
predictors, possibly none) and respect_unordered_factors (how
ranger was told to split them: "order" unless overridden through
..., and NA when there is none and nothing was passed),
replace and sample_fraction (the sampling each tree was
grown on, with sample_fraction resolved to the number ranger
used), oob_rmse and oob_r_squared (each NA_real_ when
ranger did not compute it; forwarding oob.error = FALSE through
... is one way to get there), fitted_are_oob (always
TRUE; summary() reads it to label its metrics),
seed and n_dropped (the rows prep_model_data()
removed for missing or non-finite values or a bad geometry, so $n
can be read against nrow(data_sf)), and response_centre
and response_scale (below). The raw forest is in
$engine.
The forest is grown on the response taken about its centre where that
centre is more than 1000 times the response's spread (as at 1e8 plus
a spread of 1), and divided by a power of two where the response is so
large or its spread so small that its squares overflow or lose their
bits (beyond about 1e100 or 1e-100). The splits of a forest do not
change under a shift or a scale of the response, and ranger's split
scores, formed from squares of the response, read the rounding of the
offset otherwise. $info$response_centre (0 where none is taken)
and $info$response_scale (1 where none is applied) record them,
and they are put back on fitted(), predict(),
residuals(), oob_rmse and importance (squared
units, so multiplied by the scale twice; beyond the range of doubles it
is Inf or loses its bits, and a WARN line says so). The
permutation importance under scale.permutation.importance = TRUE
and the impurity importance under splitrule = "maxstat" have no
units and are left as ranger reports them. The forest
in $engine predicts (y - response_centre) /
response_scale, and its own predictions and
prediction.error are in those units. Every other response is
passed to ranger as it is.
Coordinates as predictors
include_coords = TRUE adds the x and y coordinates to the
predictors. They are the only spatial information a forest can be given:
without them it sees the covariates alone, and print() says "no
spatial information used". The default is FALSE.
The gain from the coordinates depends on where the predictions are wanted. A forest splits on location as on any column, so it follows the training surface closely between sampled points, and has only the nearest edge of the data to go on beyond them. Between sampled points the coordinates can lower the error, most where the covariates carry little of the spatial structure themselves, and the gain fades with distance from the training data. Beyond the autocorrelation range, or in an area the data never visited, the coordinates can make predictions worse (Meyer et al. 2019). With covariates that carry the spatial structure themselves, expect less from the coordinates.
Score the forests with and without coordinates on the same folds, at the
distances the map will be used at (see "Fold methods" in
make_folds(); "Out-of-bag error" below says why the
out-of-bag error does not serve). Build the folds once and pass them to
cv_rf() with and without the coordinates:
folds <- make_folds(dat, k = 5, method = "block_kfold")
plain <- cv_rf(dat, "z", c("a", "b"), folds = folds)
with_xy <- cv_rf(dat, "z", c("a", "b"), folds = folds,
include_coords = TRUE)
c(plain = plain$overall$RMSE, with_xy = with_xy$overall$RMSE)
The example on cv_rf() runs this comparison and reads it
fold by fold. Setting include_coords = TRUE logs this advice once
per session, as a log line rather than an R warning, and not once for
every fold of a cross-validation.
Categorical predictors
A predictor that is an unordered factor or a character column is split
with respect.unordered.factors = "order": ranger orders its levels
by mean response once, before growing, and splits on that order, the
handling ranger's own help recommends. ranger's default for a regression
forest, "ignore", splits on the order the levels are stored in
(alphabetical, for most data), which for a nominal variable is arbitrary.
Pass respect.unordered.factors through ... to choose
otherwise ("ignore", or "partition" for every two-way split
of the levels, which is slow beyond a few levels). Ordered factors are
left alone and split on their own order, and with
splitrule = "extratrees" ranger's own default for that rule,
"partition", is kept. The setting is recorded in
$info$respect_unordered_factors and printed with the fit.
Out-of-bag error
ranger's out-of-bag (OOB) error holds each observation out of the
trees that did not sample it. That is a random hold-out: the trees that
did not see a point almost always saw its neighbours, so under spatial
autocorrelation it is the error of predicting among the samples, as
random k-fold is, and reads low for predictions made farther from the
data than the samples sit from each other (see make_folds()).
It is reported as $info$oob_rmse and $info$oob_r_squared
and labelled as OOB wherever it appears. Use cv_rf() for a
spatial estimate.
Fitted values are out-of-bag
fitted() on an rf_fit returns out-of-bag predictions, as the
random forest packages themselves do. In-sample predictions from a forest
come close to reproducing the training data, and their R^2 says
little about new data. summary() therefore reports out-of-bag
metrics for a forest and in-sample metrics for a GWR or a Bayesian GP
fit, and the two
do not compare; compare_models_cv() scores every backend on
the same folds.
A row that every tree sampled has no out-of-bag prediction, and ranger
reports NaN for it. That is every row under replace = FALSE
with sample_fraction = 1, and a few under a small
num_trees. The fit warns with the count; fitted() and
residuals() are NaN on those rows, and summary()
says how many rows its metrics were computed on. With no row out of bag
at all, the OOB error (NA in $info$oob_rmse and
$info$oob_r_squared) and the permutation importance (NaN)
are undefined too, and print() says so. cv_rf()
scores its fold forests on the held-out rows, never out of bag, so it
warns once with the number of folds affected rather than once per fold.
References
Meyer, H., Reudenbach, C., Wöllauer, S. and Nauss, T. (2019). Importance of spatial predictor variable selection in machine learning applications – moving from data reproduction to spatial prediction. Ecological Modelling 411, 108815. doi:10.1016/j.ecolmodel.2019.108815
Strobl, C., Boulesteix, A.-L., Zeileis, A. and Hothorn, T. (2007). Bias in random forest variable importance measures: illustrations, sources and a solution. BMC Bioinformatics 8, 25. doi:10.1186/1471-2105-8-25
See Also
cv_rf() to score the forest on spatial folds;
predict() (spatial_fit-predict) and
predict_surface() to predict;
area_of_applicability() to mark where the predictions
apply (it weights the predictors by this forest's importance).
Other model fitting:
fit_bayesian_spatial_model(),
fit_gwr_model(),
gp_lengthscale_bounds(),
new_spatial_fit()
Examples
library(sf)
set.seed(1)
n <- 150
dat <- st_as_sf(
data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
a = rnorm(n), b = rnorm(n)),
coords = c("x", "y"), crs = 32632
)
dat$z <- 2 * dat$a - dat$b + rnorm(n, 0, 0.3)
fit <- fit_rf_model(dat, "z", c("a", "b"))
fit
fit$info$importance # permutation importance of a and b
Measure how far the held-out points sit from their training data
Description
Returns, for each fold, how far the held-out points sit from their nearest
training point. make_folds() only compares the block size with the
estimated autocorrelation range; this measures the folds that were built.
Nothing is estimated: the distances come from the geometry, and the range,
when one is shown, is the one the folds carry (make_folds(auto_range = TRUE) records it) or the one you pass as sac.
Usage
fold_separation(folds, data_sf, sac = NULL, prediction_points = NULL)
Arguments
folds |
A |
data_sf |
The layer the folds were built on. Row identifiers are
matched through |
sac |
Optional: an |
prediction_points |
Optional sf or sfc layer of the locations the
model will predict at: the grid from |
Details
The distances do not say by themselves which way a score errs. A
cross-validated error reads low when the held-out points sit closer to
their training data than the locations the model will predict at, and high
when they sit farther, so the same held-out distances can go with either,
depending on the target. Random folds on evenly sited data, scored for a
map of the sampled area, are close to unbiased although nearly every
held-out point has a training neighbour inside the range; range-sized
blocks on the same data read high; random folds on clustered data scored
for a map of the whole region read low. So without a prediction target
the function reports the distances and draws no conclusion. Give it
prediction_points and it sets the held-out distances beside the
distances from those points to the same training data, and words its
reading by the signed gap between the two.
cv_block_size_sweep() gives the cross-validated error at each block
size, but not which size matches a map. This function does, read on the
folds of each size (the $folds of each element of
attr(sweep, "results")) with the map's locations as
prediction_points.
Value
A data.frame of class fold_separation, one row per fold:
fold (the fold's number: for the $folds of a
cv_*() result, the fold_id its fold_metrics use,
which differs from the list position once a fold has been dropped),
n_train, n_test, n_blocks (NA
for a scheme with no blocks), min_dist and median_dist
(distance from a held-out point to its nearest training point, in the
units of the CRS the crs attribute names), mean_cor,
target_median_dist (the median distance from the prediction
points to the fold's training data) and dist_gap (the fold's mean
held-out distance minus its mean prediction distance); the last two are
NA without a target, and print() shows them under the
headings target and gap.
mean_cor is a mean correlation, NA without a range: the
mean over the fold's held-out points of \rho(d), the
correlation the range leaves between a point and its nearest training
point at distance d. It is 1 for a point on top of training data
and falls towards 0 beyond the range, so a point at a twentieth of the
range counts for more than one at nine tenths of it.
\rho(d) is \exp(-3 d / range),
the exponential model whose effective range is the range given (0.05 at
the range), or the spherical model when the range comes from an
estimate_sac_range() fit that was spherical; the
range_model attribute says which.
Attributes: method, sac_range, range_model,
crs (the CRS the distances were measured in),
n_unknown_ids (the number of distinct rows the folds name that
data_sf does not have, each counted once however many folds
mention it, as in the cv_*() field of the same name),
pooled (a list with the number, minimum, median and mean of the
held-out distances over all folds, and the pooled mean_cor)
and target: NULL without a prediction target, otherwise a
list with n_prediction_points, source, basis
("each fold's training data" or "all sites"),
held_out_mean, held_out_median, target_mean,
target_median, target_all_mean, target_all_median
(the prediction distances to all sites), mean_diff, w1,
cor_gap, cor_w1 (NA without a range), scale
("correlation" or "distance"), tolerance,
reading (see the section "Reading the gap") and
nndm_out_of_reach (for NNDM and kNNDM folds, the
params$target_out_of_reach that make_folds() recorded;
NA for other schemes). not_compared is NULL, or,
for NNDM or kNNDM folds whose carried target was not compared because the
distances here are measured in another CRS, one sentence naming the two
CRSs; target is then NULL and print() gives the
sentence where it would otherwise say that no target is given.
Reading the gap
With a target, the held-out distances and the prediction distances are compared as two distributions. Each fold's prediction distances are measured to that fold's own training rows, so that a five-fold design is not read as too far only because each fold trains on four fifths of the sites; the distances to all sites are reported beside them. With more than 50 folds, as in the leave-one-out schemes, every training set is nearly the whole sample, and the prediction points are measured against all sites once. Folds count by their share of the held-out points.
Two numbers summarise the comparison: the signed difference of the means,
held-out minus prediction (the signed area between the two cumulative
distributions), and the Wasserstein distance W_1 (the unsigned
area). When a range is available both are also given on the correlation
scale, after each distance d is replaced by 1 - \rho(d), with \rho the correlation the range implies (see
mean_cor under Value). That scale counts a difference between two
distances well inside the range and ignores one between two distances
beyond it.
The reading is taken on the correlation scale when there is a range, with
a tolerance of 0.1, and otherwise on the mean distance, with a tolerance of
a quarter of the prediction mean. When the prediction points are measured
to all sites and every one lies on a site, as when the sites themselves
are passed as prediction_points to a leave-one-out design, the
prediction mean and with it that tolerance are 0: held-out distances above
0 then read "farther", and held-out distances that are all 0 as well
read "matched". With 50 folds or fewer the points are measured to each
fold's own training rows, which leave out that fold's held-out sites, so
the mean is above 0 and the quarter rule gives the reading.
"closer"The gap is below minus the tolerance and at least half of
W_1in size: the held-out points sit closer to their training data than the prediction points do, and the cross-validated error tends to read low for that target."farther"The gap is above the tolerance and at least half of
W_1: the held-out points sit farther, and the error tends to read high for that target."matched"The gap is within the tolerance and
W_1within twice the tolerance."mixed"The two distributions cross, closer at some distances and farther at others (the gap is under half of
W_1, or it is within the tolerance whileW_1is not), so the distances give no single direction.
The reading is a statement about nearest-neighbour distances, not a measured bias. A learner that draws on several neighbours can still score low on clustered samples whose nearest-neighbour distances match.
See Also
make_folds() for the fold schemes and the block sizing this
measures the outcome of, plot_folds() to map the folds, and
cv_block_size_sweep() for the cross-validated error at each block size.
Other folds:
cv_block_size_sweep(),
make_folds(),
plot_folds()
Examples
library(sf)
set.seed(1)
n <- 200
pts <- st_as_sf(
data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000)),
coords = c("x", "y"), crs = 32632
)
# Random folds put a training point close to every held-out one; blocked
# folds hold out whole neighbourhoods, so the distances grow. The median
# distance from a held-out point to its nearest training point, per fold:
random <- make_folds(pts, k = 4, method = "random_kfold", seed = 1)
blocked <- make_folds(pts, k = 4, method = "block_kfold",
block_size = 250, seed = 1)
round(fold_separation(random, pts, sac = 200)$median_dist)
round(fold_separation(blocked, pts, sac = 200)$median_dist)
# Which of the two suits a map of the sampled square? Compare each with
# the distances from the cells of that map to the training data.
cells <- st_make_grid(pts, n = c(20, 20), what = "centers")
print(fold_separation(random, pts, sac = 200, prediction_points = cells))
print(fold_separation(blocked, pts, sac = 200, prediction_points = cells))
Place seeds for a Voronoi tessellation
Description
Creates an sf POINT layer of seed locations, one per cell of the Voronoi tessellation built on them: k-means centres of a cloud of points, points drawn uniformly inside a boundary, or points you provide.
Usage
get_voronoi_seeds(
boundary = NULL,
method = c("kmeans", "random", "provided"),
n = NULL,
seeds = NULL,
sample_points = NULL,
kmeans_nstart = NULL,
kmeans_iter = 100,
set_seed = NULL,
partition = c("density", "kmeans"),
init = NULL,
density_power = 1,
density_k = 8
)
Arguments
boundary |
Optional polygonal sf object defining the sampling area. Rows without a location, rows the repair leaves without a polygon, vertices at a latitude beyond 90 and mixed dimensions are handled as "Boundaries" in spatialkit-geometry says; "Sampling inside the boundary" gives how points are drawn in it. |
method |
How to place the seeds: |
n |
Integer; number of seeds to return. Required for
For Besides a number, With |
seeds |
sf POINT object of user-provided seeds (method = "provided").
Methods |
sample_points |
Optional sf POINT cloud for k-means clustering.
Method |
kmeans_nstart |
The number of starts, of which the best is kept.
|
kmeans_iter |
Integer; |
set_seed |
Optional integer seed for the random draws. Default
|
partition |
For |
init |
For |
density_power |
For |
density_k |
For |
Details
Seeds lie inside the ground they stand for (k-means seeds inside the
hull of the points they were fitted to, random seeds inside the
boundary), so Voronoi cells clipped to the seeds' own hull would leave
its edge uncovered. The result therefore
carries that ground as attr(, "cover"): the boundary when one was
given, otherwise the convex hull of sample_points (for lon/lat points,
the hull of their coordinates in degrees, with the longitudes of points on
both sides of 180 degrees taken from 0 to 360, -170 as 190), otherwise
(for the scored centres of a resolution_profile() or a
select_resolution() result passed as n) the hull of the points the
profile was computed on.
build_tessellation() and
create_voronoi_polygons() derive their default boundary from it, so
build_tessellation(seeds, method = "voronoi") holds every observation
without a boundary. Seeds with no cover are tessellated over their own
hull unless a boundary or cover is passed then: method = "provided"
seeds given with neither boundary nor sample_points have none, and no
warning is raised for them, since they may be the observation sites
themselves. The attribute survives
sf::st_transform() and row subsetting; rbind() drops it.
A k-means seed is a mean of the points of its cluster, weighted under the
density kind, so it can lie outside a boundary that is not convex, in a
bay or a bend of a coast, even when every point lies inside. Tessellated
within that boundary, its cell is built if any of it lies inside: the part
of the study area nearer the seed than any other seed.
build_tessellation() gives the seed that cell in index, as it gives
every seed the cell it generates, so seeds$cell_id <- tess$index holds
each seed's cell for cell_values_at(). A seed with every part of the
study area nearer another seed has no cell, NA in index, and a
warning of class spatialkit_unassigned gives the number.
Value
An sf POINT object with seed_id and method columns. With
method = "kmeans" it also carries attr(, "kmeans"), the run behind
the seeds: cluster (the seed_id each clustered cloud point was
assigned to), rows (those points' positions in the cloud, since rows
with unusable coordinates are dropped first), size (points per seed),
withinss and tot_withinss (the within-cluster sums of squares),
iter and nstart. For the scored centres of a selection or profile
(see n) it describes sample_points assigned to them, each point to
its nearest seed, with iter NA and nstart the profile's restarts,
and is absent when no sample_points were given. A point the same
distance from two seeds (squared distances within one part in ten
million) goes to the lower seed_id, the rule the profile scores its
cells by, so the record is the same in another unit or with another
origin. Under partition = "density" withinss and tot_withinss
count every point once, about its cell's mean. A run this call makes with partition = "density" or
init = "kmeans++" also records converged, whether the kept start
stopped before kmeans_iter, and under partition = "density"
objective, the weighted sum the seeds minimise; scored centres have
neither. Seeds placed with partition = "density" or init = "kmeans++", and the scored centres of a profile of the density kind or
from random starts, carry attr(, "partition"): a
list with kind, init, density_power and density_k, and for
seeds this call placed iter, iter_max and converged (the
iterations the kept start took, the limit, and whether it stopped
before the limit). build_tessellation() returns the list as
params$partition. Seeds with no such
record are plain k-means: from random starts when this call placed
them, or the scored centres of a k-means profile from k-means++ starts.
Every method also
attaches attr(, "cover") when the call says what ground the seeds stand
for (see "Details"): an sfc holding the boundary's polygons or the hull
of the clustered points, in its own CRS.
When n is a select_resolution() result that carries count_rule,
or a profile built with an estimate or read by cp, the seeds carry
that record as
attr(, "count_rule"): how the count was set, for which cell value, and
what the profile scored at it. Its scored_cells is TRUE for the
scored centres method = "kmeans" hands on, and FALSE for centres
refitted to every point (see n) and for seeds this
call places itself at that count: a k-means of its own when the
selection holds no centres at the count, and every method = "random"
seeding. method = "provided" does not read n and writes no record;
seeds that already carry one (sel$seeds) keep it, marked FALSE when
their number is not the record's count. build_tessellation() and
assign_features_to_polygons() hand the record on, and
summarize_by_cell() checks its result against it. A count given as a
number, or read off a profile without an estimate by cp or elbow,
has no record.
Sampling inside the boundary
Seeds drawn by method = "random", and the cloud method = "kmeans"
draws when no sample_points are given, are sampled inside boundary.
Its rows are repaired with sf::st_make_valid() before they are unioned.
In longitude and latitude the union runs with s2, and a row s2 still
refuses (crossing edges, a vertex listed twice) is repaired again, with
crossing edges split as GEOS splits them in a projected CRS; a row s2
refuses even then stops the call with an error of class
"spatialkit_cells_degenerate" that names it and says to transform
boundary to a projected CRS.
In longitude and latitude, a boundary whose bounding box is over 10,000
times its area (small pieces far apart), which sf does not sample whole,
is sampled piece by piece, the points shared among the pieces in
proportion to their areas; a piece whose own box is over 10,000 times its
area stops the call with an error that says to transform boundary to a
projected CRS. A boundary whose bounding box has no height or no width
(three vertices on one parallel) is refused. In longitude and latitude s2
reads the edges as great circles, which leave the bounding box read from
the coordinates, and sf (without lwgeom) draws in that box: a
boundary whose box has less than half its area on the sphere (three
vertices on or near one parallel) is refused too. That error, and the
error for a box with no height whose vertices lie on one parallel other
than the equator, say to transform boundary to a projected CRS in which
a parallel is a curve, such as the one ensure_projected() picks for it
(a polar one, such as EPSG:3413 or 3031, for a ring around a pole), where
the region has an area and lies in its box.
sf draws the points in the bounding box and keeps those inside, so it
draws the number asked for times the ratio of the box to the area. In any
CRS, a boundary that would take more than 10^6 points drawn in its box,
or 10 times the points asked for if more (small pieces far apart, a thin
strip at a slant), is sampled piece by piece in the same way (or whole,
in draws of at most 10^6 points in its box, where that takes less time),
and a piece that would still take more is drawn in such draws. Where the
points drawn in all would exceed 2e7 (or 10 times the points asked for,
if more), the call stops before any draw with an error that gives the
ratio and says to pass sample_points (method = "kmeans", whose cloud
is max(2000, 50 * n) points) or to ask for fewer seeds.
See Also
Other cell building:
build_tessellation(),
clip_target_for(),
create_grid_polygons(),
create_grid_polygons_cached(),
create_voronoi_polygons(),
ensure_stable_poly_id(),
plot_tessellation_map(),
voronoi_seeds_kmeans(),
voronoi_seeds_random()
Examples
library(sf)
bnd <- st_sf(geometry = st_sfc(st_polygon(list(rbind(
c(0, 0), c(100, 0), c(100, 100), c(0, 100), c(0, 0)
))), crs = 32632))
get_voronoi_seeds(bnd, method = "random", n = 5, set_seed = 1)
# Seeds from a cloud with one dense place: density-weighted k-means (the
# default, 3 starts) against plain k-means. The fewest and most points a
# seed's cell holds under each kind, with more seeds than dense places:
set.seed(2)
cloud <- st_as_sf(data.frame(x = c(rnorm(150, 30, 5), runif(50, 0, 100)),
y = c(rnorm(150, 30, 5), runif(50, 0, 100))),
coords = c("x", "y"), crs = 32632)
dens <- get_voronoi_seeds(bnd, method = "kmeans", n = 20,
sample_points = cloud, set_seed = 1)
km <- get_voronoi_seeds(bnd, method = "kmeans", n = 20,
sample_points = cloud, set_seed = 1,
partition = "kmeans")
sizes <- list(density = attr(dens, "kmeans")$size,
kmeans = attr(km, "kmeans")$size)
sapply(sizes, range) # fewest and most points per seed
Compute length-scale bounds for a squared-exponential GP
Description
Computes lower and upper bounds for the length-scale \ell of a
squared-exponential (exponentiated-quadratic) kernel,
k(h) = \exp(-h^2 / (2\ell^2)), from the
spread of the pairwise distances between the points.
fit_bayesian_spatial_model() calibrates its length-scale
prior over them. The effective range, where the correlation drops to 5
percent, is
\ell \sqrt{2 \ln 20} \approx 2.45\,\ell.
Usage
gp_lengthscale_bounds(coords_xy, q_small = 0.25, max_n = 1000L)
Arguments
coords_xy |
Numeric matrix or data.frame of coordinates with at least
two columns; the first two are used, and replicated rows are collapsed
before the distance quantiles are taken, because |
q_small |
Quantile of the pairwise distances for the lower bound, a
single number in |
max_n |
Maximum number of distinct points to use in the distance
computation. Default 1000. Set to |
Details
The lower bound is the q_small quantile of the pairwise distances
(by default the 25th percentile) taken as an effective range, and the
upper bound is the largest pairwise distance taken as an effective range.
The inverse-gamma prior that fit_bayesian_spatial_model()
calibrates on them puts 1 percent of its mass below the lower bound and
1 percent above the upper. Both are
fixed fractions of the spread of pairwise distances, so they do not
shrink as points are added to the same area: more points help the data
identify a short range, but they make neither these bounds nor the basis
derived from them finer.
These are the bounds a length-scale prior is calibrated over, not the
scales a fitted model can resolve, which depend on the basis size
(gp_k in fit_bayesian_spatial_model(), which reports
it as $info$gp_ell_min, and in CRS units as
$info$gp_resolution). A surface whose range is shorter than the
lower bound needs a basis fine enough to represent it and a prior that
allows it. A larger gp_k under the prior calibrated here changes
almost nothing, because the prior still holds the length-scale above this
bound. fit_bayesian_spatial_model() therefore moves the prior's
lower tail down to the length-scale the basis resolves whenever
gp_resolution or an explicit gp_k asks for a finer basis
than the one derived from these bounds.
Large layers are subsampled (max_n) to bound the cost of the
pairwise distances, which grows with the square of the points.
Value
Named numeric vector c(lower, upper): length-scales in the
units of coords_xy. lower is the q_small quantile
of the distinct pairwise distances divided by \sqrt{2 \ln 20}
(about 2.45); upper is the largest pairwise distance divided by
the same factor, and at least 1.2 times lower.
c(lower = 0.001, upper = 1) when fewer than two distinct located
rows or no positive distances remain.
fit_bayesian_spatial_model() standardises the
coordinates before it calls this function, so its bounds are in those
standardised units.
See Also
Other model fitting:
fit_bayesian_spatial_model(),
fit_gwr_model(),
fit_rf_model(),
new_spatial_fit()
Examples
# 500 points spread evenly over a square of side 100 km, in metres.
set.seed(1)
xy <- cbind(runif(500, 0, 1e5), runif(500, 0, 1e5))
b <- gp_lengthscale_bounds(xy)
b
# The bounds as effective ranges: the 25th percentile of the pairwise
# distances, about a third of the side, and the largest distance.
b * sqrt(2 * log(20))
Select GWR predictors by forward selection on AICc
Description
Grows a GWR model one predictor at a time and scores every intermediate
model with a corrected Akaike information criterion, the sweep
GWmodel::gwr.model.selection() defines, and returns a ranked table
with each model's distance from the best. The model without predictors is
scored too. Every model is fitted by the package's own local solve (see
"The local solve" in fit_gwr_model), so a candidate
that is constant inside some windows, a regional indicator say, is scored
on what those windows do estimate and neither stops the sweep nor scores
as rounding error.
Usage
gwr_model_selection(
data_sf,
response_var,
candidate_vars,
bandwidth = NULL,
adaptive = TRUE,
kernel = c("bisquare", "gaussian", "tricube", "boxcar", "exponential"),
bw_approach = c("AICc", "CV"),
max_models = 200L,
dmat_max_n = 2000L,
quiet = TRUE,
.engine = .gwr_ms_engine
)
## S3 method for class 'gwr_model_selection'
print(x, n = 10L, ...)
Arguments
data_sf |
An |
response_var |
Response column name. |
candidate_vars |
Character vector naming at least two numeric
predictors to choose among. Factor, character and logical candidates are
refused: a factor is several model-matrix columns while this
sweep counts it as one variable, so the criteria would not be comparable,
and |
bandwidth |
Bandwidth held fixed across all candidate models. If
|
adaptive |
Logical; adaptive (nearest-neighbour) bandwidth. Default
|
kernel |
Weighting kernel: one of |
bw_approach |
Criterion for the bandwidth search on the full model:
|
max_models |
Refuse the call if the sweep would exceed this many model fits. Default 200, which admits up to 19 candidates. |
dmat_max_n |
Not used. The sweep takes its distances window by
window and builds no |
quiet |
Print no progress. Default |
.engine |
Internal; leave at the default. |
x |
A |
n |
Number of top-ranked models |
... |
Not used. |
Value
An object of class gwr_model_selection, a list with:
bestCharacter vector of the selected predictors, the model with the lowest criterion;
character(0)when that is the model without predictors.tableRanked data.frame of every model evaluated, with columns
rank,n_vars,variables,criterionanddelta, the criterion minus the best model's. The model without predictors is the row<none>.criterionisNA, and the model is ranked last, where it could not be evaluated or where AICc is undefined because the model's effective number of parameterstr(S)is not belown - 2(with a warning).within_2,smallest_within_2The rows of
tablewhosedeltais at most 2, and the predictors of the smallest model among them.criterion"AICc".criterion_by_name,criterion_column,criterion_verifiedWhere the criterion was read from the diagnostic table:
TRUE, 3 andTRUEwith the built-in engine.response_var,candidate_varsThe response and the full candidate set the sweep ran over, both echoed by
print().bandwidth,bandwidth_source,adaptive,kernelThe smoothing held fixed across the sweep, and where it came from:
"supplied", or the criterion's name followed by"search on the full model", the criterion being"leave-one-location-out CV"when observations share a location.bandwidth_searchWhat the search scored, as
fit_gwr_modelkeeps it;NULLwhen the bandwidth was supplied.n_obs,n_modelsThe number of observations, and the number of rows of
table.used_dmatAlways
FALSE.rawThe forward sweep in the layout
GWmodel::gwr.model.selection()returns: the two-element list of its model list and its diagnostic table, without the model that has no predictors.
Scope of the criterion
AICc penalises the effective number of parameters but is computed on the
data the model was fitted to, and under spatial autocorrelation an
in-sample criterion is optimistic in a way that a spatially blocked
estimate is not. Use this function as a
fast screen and confirm with select_features_forward(),
which runs the same forward search on a spatially blocked cross-validated
score at a higher cost.
Every model is fitted at one bandwidth, as Lu et al. (2014) define the
method: comparing criteria across models needs the smoothing held fixed.
The bandwidth chosen for the full model is not optimal for smaller ones,
so refit the selected model with bandwidth = NULL once the set is
settled.
The model without predictors, and the gaps
The forward sweep starts from one predictor, so by itself it always names
at least one, whether or not any candidate helps. The model without
predictors, a local mean at the sweep's bandwidth, is therefore scored as
well and ranked with the others as <none>. When it ranks first,
best is character(0): no candidate improves on it.
The delta column of table is each model's criterion minus
the best one's. Differences of AICc below about 2 do not separate two
models (Burnham and Anderson 2002), so within_2 lists the models
that close to the best and smallest_within_2 names the one among
them with the fewest predictors, which is the one to prefer when several
are that close. best is still the model with the lowest criterion.
Observations that share a location
When rows of data_sf have the same coordinates, the bandwidth
search leaves out whole locations, for either bw_approach (see
fit_gwr_model, Observations that share a
location); bandwidth_source then reads
"leave-one-location-out CV search on the full model". The models
are still ranked by AICc, which counts the rows at one location as
independent, so the gaps overstate what a predictor adds when a location
has an effect of its own; a warning of class
"spatialkit_gwr_repeated_locations" says so with the counts. A
model whose fit reproduces the mean of the observations at each location
(every such model scores the same, whatever its predictors) has criterion
NA and is listed last, as is one with a term that no local window
can estimate; a warning names them.
Cost
The sweep fits p * (p + 1) / 2 GWR models for p candidates
(55 at p = 10, 210 at p = 20), and the one without predictors, each over
all n locations.
max_models stops the call before it runs for hours.
Using $raw with GWmodel directly
raw has the layout of GWmodel's own list(model.list, GWR.df),
so its two elements have to be unpacked before GWmodel's helpers will take
them: GWmodel::gwr.model.view() takes
(DeVar, InDeVars, model.list), so the call is
GWmodel::gwr.model.view(sel$response_var, sel$candidate_vars, sel$raw[[1]])
Pass sel$raw[[1]], not sel$raw. The diagnostic table is
sel$raw[[2]], a numeric matrix whose columns are
bandwidth, AIC, AICc, RSS in that order (and
are named so); the criterion column of $table is its third
column.
Printing
print() shows the response, the candidate predictors, and the
top-ranked models with their criterion values and, in the delta
column, how far each is from the best. Below the table it lists the
models within 2 of the best, which a difference in AICc does not separate
(Burnham and Anderson 2002), and names the smallest of them. When several
models are that close, treat the choice of predictors as unsettled; when
the model without predictors (<none>) is among them, no candidate
has been shown to help. print() returns x invisibly.
References
Burnham, K. P. and Anderson, D. R. (2002). Model Selection and Multimodel Inference: A Practical Information-Theoretic Approach, 2nd edition. Springer.
Lu, B., Harris, P., Charlton, M. and Brunsdon, C. (2014). The GWmodel R package: further topics for exploring spatial heterogeneity using geographically weighted models. Geo-spatial Information Science 17(2), 85–101. doi:10.1080/10095020.2014.917453
See Also
select_features_forward() for the blocked
cross-validated counterpart, plot.gwr_model_selection() to
draw the models, and fit_gwr_model() to fit the selected
model.
Other predictor selection:
plot.feature_selection(),
plot.gwr_model_selection(),
select_features_forward()
Examples
library(sf)
set.seed(1)
n <- 80
dat <- st_as_sf(
data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
a = rnorm(n), b = rnorm(n), noise = rnorm(n)),
coords = c("x", "y"), crs = 32632
)
# The slope on a rises from 1 in the west to 3 in the east.
east <- (st_coordinates(dat)[, 1] - 5e5) / 1000
dat$z <- (1 + 2 * east) * dat$a - dat$b + rnorm(n, 0, 0.3)
sel <- gwr_model_selection(dat, "z", c("a", "b", "noise"), bandwidth = 30)
sel # every model tried, by AICc, with the gaps
sel$best # the winning predictor set
# Refit with the bandwidth chosen afresh for the selected set.
fit_gwr_model(dat, "z", sel$best)
Bring two spatial objects to one CRS
Description
Brings two sf or sfc objects to one CRS: the CRS of a or b, as
prefer says, or target_crs when it is given. Without target_crs,
two objects that both lack a CRS are returned unchanged.
Usage
harmonize_crs(
a,
b,
prefer = c("a", "b"),
target_crs = NULL,
on_transform_error = c("stop", "set_crs")
)
Arguments
a, b |
Objects of class sf or sfc. |
prefer |
Which object's CRS both are brought to when they differ:
|
target_crs |
Optional target CRS to apply to both: anything
|
on_transform_error |
What to do when |
Details
When one input has no CRS, the lon/lat test that ensure_projected()
uses decides what happens (see spatialkit-geometry, "Layers without a
CRS"), so both functions place the same data in the same place:
coordinates the test takes for degrees are read as EPSG:4326 and
reprojected to the other object's CRS (or target_crs); other
coordinates are stamped with that CRS by sf::st_set_crs(), which
relabels them without moving them. Either way a warning says so. A CRS
in longitude and latitude is not stamped on coordinates that cannot be
in it: a layer with an x outside -180 to 360 or a y beyond 90 north or
south, read on the coordinates that have a location, stops the call with
an error that names a or b, its box and the target CRS.
A layer that is transformed is read as spatialkit-geometry describes:
a layer that mixes XY and XYZ (or XYM) geometries comes back in XY, with
a warning of class spatialkit_zm_dropped, and a row without a location
comes back empty, in its own geometry type. So does a row of a projected
layer moved to a CRS in degrees with a coordinate beyond 1e10 in its
CRS's own unit, further out than any projected CRS places a point of the
Earth. A row that has a location and that the target CRS cannot place
in full, such as a point far outside a UTM zone or a ring with a vertex
at a latitude beyond 90, comes back empty, or without the vertices the
CRS cannot place, and a warning of class spatialkit_rows_unplaced names
such rows of a or b (rows on the condition).
Value
A named list with components a and b, each of the class it
came in. A layer that is not transformed is returned as it came.
See Also
spatialkit-geometry for how input geometry and CRSs are read.
Other data preparation:
[.spatialkit_rows(),
coerce_to_points(),
ensure_projected(),
prep_model_data(),
spatialkit-geometry
Examples
library(sf)
a <- st_as_sf(data.frame(x = c(500000, 500100), y = c(4000000, 4000100)),
coords = c("x", "y"), crs = 32632)
b <- st_transform(a, 4326) # same points, lon/lat
h <- harmonize_crs(a, b) # b is brought into a's CRS
c(a = st_crs(h$a)$epsg, b = st_crs(h$b)$epsg)
st_crs(h$a) == st_crs(h$b)
Check whether block kriging would improve cell means
Description
summarize_by_cell() aggregates by plain means inside cell
boundaries. A block-kriging aggregator would instead weight observations
by their spatial correlation with the cell, and would return an estimate
and a variance for every cell, thin or empty. This function measures what
block kriging would add on a given layer, without changing any cell
value. For every cell it reports the block-kriging estimate and variance
implied by a fitted variogram (kr_pred, kr_var), that
variance as a share of the variance the cell's mean would have with no
data at all (kr_ratio), and, where the cell has points, the error
variance of its plain mean under the same variogram (plain_var)
and the share of that variance kriging removes (kr_gain). It also
scores the variogram itself by blocked cross-validation.
Usage
kriging_adequacy(
assigned_points_sf,
response_var,
cells_sf,
id_col = "poly_id",
sac = NULL,
folds = NULL,
k = 5L,
seed = 123L,
nmax = 50L,
max_neighbours = 2000L,
max_box_ratio = 1000,
quiet = TRUE
)
Arguments
assigned_points_sf |
Points with a cell identifier column, as
|
response_var |
The response column: numeric or logical. A logical
column is kriged as 0/1, so its cell mean is a share. Any other class
(a factor, an ordered factor, character, a date) is an error naming the
column and its class, and is never converted: a factor's level codes are
an arbitrary relabelling, and kriging them gave a variogram, kriged
estimates and plain means that all changed with the order of the
levels. For a category, pass an indicator ( |
cells_sf |
The cell polygons, with the matching ID column. A layer with no CRS is taken to be in the points' CRS (and points with none in the cells'), with a warning. Cells that do not all have the same dimensions are read in x and y, without their Z and M. So are cells whose geometries carry M (XYM or XYZM), which GEOS does not read. |
id_col |
Name of the ID column, found as
|
sac |
Optional |
folds |
Optional |
k, seed |
The number of blocked folds built when |
nmax |
The number of neighbours each kriging system uses
(gstat's |
max_neighbours |
The largest kriging system a cell is given when its
neighbourhood has to grow to hold all its own locations; a cell that
would need more is left out ( |
max_box_ratio |
A cell whose bounding box is more than this many
times its area is left out ( |
quiet |
Logical; suppress this function's progress |
Value
An sf object of class "kriging_adequacy", one row
per cell with the cell geometry and: the ID column, n (points in
the cell), mean (the plain mean), se (its naive standard
error), plain_var (the plain mean's error variance under the
variogram), kr_pred, kr_var, kr_ratio,
kr_gain, kr_shift and kr_n_used (how many
locations the cell was kriged from; NA for a cell left out).
Attributes:
variogram (the model frame), sill, nugget,
range, range_identified, rejected_reason (why the
range was refused, from sac; NA when it was identified),
cv (a list:
zscore_var, zscore_mean, rmse, n_pred,
k, method), nmax, n_points (the points
used), n_locations (the distinct locations among them, which
the kriging used), cells_left_out (counts of cells left out,
named shape for max_box_ratio and size for
max_neighbours) and replicates (NULL when no two
points share a location; otherwise a list with n_points, the
points that share one, within_var, their pooled within-location
variance, df, its degrees of freedom, nugget, the
variogram's, nugget_used, the larger of the two, which is the
error variance a location seen once is kriged with, and
above_nugget, TRUE when the replicate variance exceeds
the variogram's nugget).
Reading the columns
kr_ratioThe block-kriging variance over the cell's prior variance, in
[0, 1]. The prior variance is the variance the cell's mean would have with no data at all,\bar C(B,B): the covariance averaged over pairs of points in the cell, on the discretisation gstat block-kriges with, and without the nugget, which averages out over a block (gstat leaves it out of the block variance too). Each cell has its own: a cell's mean varies less than a single point does, and far less once the cell is wider than the range, so the point sill is not the scale. It is the coverage score, and it needs no hand-set threshold in metres or point counts: as it approaches 1 the estimate carries almost no information from the data about the cell and is reverting to the estimated mean. Ordinary kriging adds the variance of that estimated mean, so a cell the data do not reach comes out at or above its prior variance and reads 1. A cell at 0.05 is well determined; a cell at 0.8 is mostly prior.NAwhen the model is a pure nugget, where a cell mean has no prior variance to be a share of.plain_varThe error variance of the cell's plain mean as an estimate of the cell's average, under the same variogram and the same discretisation of the cell as
kr_var:a' C a - 2 a' \bar c(B) + \bar C(B,B), withathe plain mean's weights on the cell's observations,Ctheir covariances (the nugget on the diagonal),\bar c(B)their covariances with the cell and\bar C(B,B)the covariance within it. It is the model's counterpart ofse^2.s^2/nis the variance the plain mean would have if the cell's points were independent draws; under spatial correlation it understates the error, most where a cell's points sit close together, sose^2 / plain_varbelow 1 says the naive standard error is too small if the variogram is right. Defined from one point up.NAfor a cell with no point and for a cell left out of the kriging.kr_gain1 - kr_var / plain_var: the share of the plain mean's error variance that kriging removes in the cell. Both variances come from the one variogram, so the gain does not move when sill and nugget are multiplied by a constant (unless locations are repeated, whose replicate variance is read off the data and does not scale with the model). It is at least 0: the kriging neighbourhood always holds the cell's own points, the plain mean is one unbiased combination of them, and kriging is the best such combination. The exception is a cell with rows at a location whose rows name more than one cell: that location is no cell's own (see "The kriging neighbourhood"), and the neighbourhood need not hold it. It is what the variogram expects, not what happened: read it besideattr(, "cv")$zscore_var, which says whether the variogram's variances are the right size.NAwhereplain_varis.kr_varis not compared withs^2/n. That comparison sets a variance from the model against one from the cell's own spread, so it moves with the fitted sill, and it does not mark the cells where kriging fails to pay.kr_shiftThe kriged estimate minus the plain mean, over the standard deviation the variogram gives that difference,
sqrt(plain_var - kr_var)(the kriging error is uncorrelated with the difference, so the two variances subtract). Under the right variogram it has variance 1: about 32 percent of cells beyond 1 and 5 percent beyond 2. More than that says the plain means and the variogram disagree, so the countsprint()gives are a check of the variogram on the cells themselves, beside the cross-validation statistic. In units of the naive standard errors/\sqrt{n}the same shift does not have variance 1 under the right variogram, so counts beyond 1 and 2 in that unit are not this check.NAfor a cell with no point, and where the two variances agree to within a ten-thousandth, which is where kriging returns the plain mean.
The cross-validation statistic
The kriging variance is only as good as the variogram. With blocked
folds, each held-out point is kriged from the training folds and the
standardised error (z - \hat z) / \sqrt{kv} is recorded; the
variance of those over all held-out points should be about 1. Its
departure from 1 measures how badly the kriging variance is understated
(or overstated): 1.4 means the variances are roughly 40 percent too
small. Under blocked folds every held-out point is far from the training
data, where the kriging variance is close to the sill whatever the
nugget, so the blocked statistic checks the sill and range and says little
about the nugget. To check the nugget, pass random folds
(make_folds(method = "random_kfold")) as folds: the
held-out points are then close to their neighbours, where the nugget
decides the variance. The statistic is computed fold by fold with
gstat::krige() on the splits make_folds() built, each
held-out point kriged from that split's own training set, so the folds
carry the same separation the package uses everywhere else:
"buffered_loo" and "nndm" keep the points they exclude
around each held-out one out of its kriging, and print() names the
scheme that ran. A vector of fold labels is run as k-fold, each fold
kriged from all the others.
What this needs
A variogram model. sac is a estimate_sac_range()
result carrying one (attr(, "variogram_model")); when NULL
it is estimated here from the response. The model families are the ones
the package interprets elsewhere: exponential, spherical and Gaussian
components with a nugget. Anything else is refused by name. A
model whose range was not identified (an NA estimate with the
model attached) is used with a warning that says why it was refused, and
the reason is kept as attr(, "rejected_reason"): a range past the
fitted lags means the sill was never reached and the ratios rest on an
extrapolation; a variogram that falls with distance, or a range below the
shortest lag, describes the data poorly at some lags; and a response in
which estimate_sac_range() found no spatial structure comes with a
pure-nugget model, which gives kriging no correlation to use.
The model has to be of the response itself. A variogram of residuals
(estimate_sac_range(predictor_vars = ...), attr(,
"detrended") TRUE) leaves out the variance the predictors
explain, while the response is kriged here without them, so
kr_var, kr_ratio and the cross-validation statistic come out
too small; it is used with a warning. The points are put in
the CRS the variogram was fitted in (attr(sac, "crs")), because
its range is a length in that CRS's units. Requires gstat.
The kriging neighbourhood
gstat kriges a cell from the nmax locations nearest its
centre. On gridded locations several of them are often the same distance
away, and which of those the last bits of the coordinates make nearer
moves with the unit and the origin. So the nmax are chosen by the
package's tie rule: squared distances within one part in ten million of
each other count as equal, and a tie goes to the location of lower first
coordinate, then lower second, coordinates within that part of the
distance counting as equal. Where the nmax-th nearest location
ties with the next, the cell is kriged from the locations the rule
picks; elsewhere the nmax nearest are one set and gstat's
own search finds it. Each held-out location of the cross-validation is
kriged from its nmax nearest training locations the same way.
The kriged figures, and the cross-validation statistic on the same folds,
are then the same in another unit or with another origin, to rounding,
as long as no coordinate moves by more than about a two-hundred-millionth
of the distance between neighbouring locations. The
rows are put in order by their coordinates, then their cell ID, then
their response before any of this, so the result does not depend on the
order of the rows either.
A cell holding more locations than nmax would be estimated from
its middle alone, which describes the middle rather than the cell. So
wherever the nmax locations nearest a cell's centre
leave out any of the cell's own locations (more than nmax
locations are as near as its furthest own one, under the same tolerance),
the cell is kriged from all of its own locations plus the nmax
nearest outside it, chosen by the same rule;
kr_n_used says how many locations each cell was kriged from. The
cost of a kriging system grows with the cube of its size, so a cell that
would need more than
max_neighbours is left out with a warning, its kr_ columns
NA. A cell's own locations are those whose rows name it. A
location whose rows name more than one cell (rows at one place carrying
different IDs) is no cell's own, with a warning that gives the count of
such locations: it is kriged from as any other location, and each of its
rows still counts in n, mean, se and
plain_var of the cell it names.
gstat also discretises each cell into 500 points on a regular grid
laid over the cell's whole bounding box, keeping those inside, so the
memory a cell takes grows with the ratio of that box to its area. A cell
whose bounding box exceeds its area more than
max_box_ratio times (a sliver, parts far apart, a cell that is
mostly hole) is left out the same way. attr(, "cells_left_out")
counts both kinds, and print() says how many cells have no
estimate and why. An empty cell, or one with a coordinate that is not
finite or lies beyond 1e150 (read as given), has no location and is left
out as well, with a warning of its own, and comes back with an empty
geometry; it is counted with the cells of the second kind
(shape).
Repeat measurements at one location
Two observations at the same coordinates (visits to a station, records
geocoded to one address) make a kriging system singular, because
gstat gives them the full sill, nugget included, as their
covariance, as if they were one observation. The kriging and its
cross-validation therefore use one observation per location, the mean of
its replicates, with a warning; n and mean still count every
point. How much of the nugget c_0 a mean of m replicates
keeps is read off the replicates: their pooled within-location variance
s_w^2 is the part that differs from visit to visit and averages
down, and what the nugget holds beyond it is micro-scale variation the
visits share, so the mean carries error variance
\max(c_0 - s_w^2, 0) + s_w^2/m. That goes to gstat as a known
measurement error (its weights) on the model with the nugget set
to zero. For replicates that differ only by measurement error this is
exactly the kriging of every observation, and for identical replicates it
is the kriging of one. plain_var uses the same error variances:
the observations a cell has at one location share the micro-scale part
and average the rest.
When s_w^2 is above c_0 the replicates show more variation
between visits than the model has room for (with a zero nugget, any at
all). The replicate variance is then used as it is: a mean of m is
kriged with error variance s_w^2/m, and a location seen once with
s_w^2 where the model gives it c_0. Capping it at
c_0 would krige the means as more exact than their replicates show
them to be. The warning then carries the class
"spatialkit_replicate_var_above_nugget" and both numbers, which
attr(, "replicates") records and print() repeats. The
replicate variance is an estimate (its degrees of freedom are in the
warning and the record), and the variogram still says c_0: refit
it with a nugget of at least s_w^2.
In the cross-validation a location is held out whole, under the fold of
its first row, and its error variance is part of its standardised error.
A cell or held-out location gstat still cannot krige is reported
NA with a warning, and print() says how many.
References
Cressie, N. (1993). Statistics for Spatial Data, revised edition. Wiley. (Block kriging, chapter 3; cross-validation of the kriging variance, section 2.6.4.)
See Also
Other assign and summarise:
assign_features_to_polygons(),
cell_values_at(),
summarize_by_cell()
Examples
library(sf)
set.seed(1)
n <- 200
x <- 5e5 + runif(n, 0, 1000); y <- 5e6 + runif(n, 0, 1000)
d <- as.matrix(dist(cbind(x, y)))
z <- as.numeric(t(chol(0.8 * exp(-d / 100) + diag(0.2, n))) %*% rnorm(n))
pts <- st_as_sf(data.frame(x = x, y = y, z = z), coords = c("x", "y"), crs = 32632)
bnd <- st_sf(geometry = st_as_sfc(st_bbox(pts)))
cells <- create_grid_polygons(bnd, target_cells = 16, type = "square")
asg <- assign_features_to_polygons(pts, cells)
ka <- kriging_adequacy(asg, "z", cells, k = 4)
print(ka) # the report
# Variance of the standardised errors: about 1 when the variogram is right
attr(ka, "cv")$zscore_var
Create spatial cross-validation folds
Description
Builds train and test splits of a layer for cross-validation, by one of six
methods: random k-fold, spatial block k-fold, buffered leave-one-out,
leave-location-out, nearest-neighbour distance matching (NNDM)
leave-one-out, or its k-fold version (kNNDM). It returns the splits
(folds), one row per observation naming the fold that holds it out
(assignment), and the settings and diagnostics of the build (params).
Pass the result as folds to cv_spatial() or another cv_*() function,
map it with plot_folds(), and measure how far the held-out points sit
from their training data with fold_separation().
Usage
make_folds(
points_sf,
k,
method = c("random_kfold", "block_kfold", "buffered_loo", "leave_location_out", "nndm",
"knndm"),
seed = NULL,
block_nx = NULL,
block_ny = NULL,
block_multiplier = 3,
block_size = NULL,
auto_range = FALSE,
range_frac = 1,
response_var = NULL,
group_var = NULL,
prediction_points = NULL,
predictor_vars = NULL,
boundary = NULL,
buffer = NULL,
min_train = 0.5,
phi = NULL,
drop_empty_blocks = TRUE,
blocks = NULL,
balance_tol = 3,
max_test = NULL
)
Arguments
points_sf |
An sf layer of the observations. Z and M are dropped
before folding, since distances are measured in x and y. A layer
without a CRS is aligned to a |
k |
The number of folds, a single whole number of at least 1; required
except for |
method |
One of the six methods in the section "Fold methods":
|
seed |
Optional integer RNG seed; |
block_nx, block_ny |
Optional grid dimensions for |
block_multiplier |
A single positive number, default 3. When neither
|
block_size |
Optional positive number, the minimum block edge length,
in the units of the CRS the folds are built in ( |
auto_range |
Logical, default |
range_frac |
Passed to |
response_var |
Name of the response column. Required when
|
group_var |
Name of a column of |
prediction_points |
Optional sf layer of the locations the model will
predict at, such as the grid from |
predictor_vars |
Optional character vector of predictor column names,
passed to |
boundary |
Optional polygon layer (sf or sfc) that the block grid of
|
buffer |
For |
min_train |
For |
phi |
For |
drop_empty_blocks |
Logical, default |
blocks |
Optional polygon layer (sf or sfc, POLYGON or MULTIPOLYGON,
at least two features) to use as the blocks of |
balance_tol |
A number of at least 1, default 3. For
|
max_test |
For |
Value
A list with:
methodThe method used.
kThe number of folds built, which can differ from the
kasked for (seek);length(folds)always equals it.foldsA list with one element per fold, each a list of
trainandtestrow IDs: the values of the..row_idcolumn when the input has one, otherwise row positions.assignmentA tibble with one row per observation kept:
row_id(the same IDs) andfold, and for"block_kfold"a third column,block_id, the row ofparams$blocksthe point fell in. Withmax_test,foldisNAfor the rows not held out.paramsThe settings and diagnostics of the build, below.
Every method's params carries seed, k_requested (the k asked
for, NA when none was given) and row_probe, a small sample of row
IDs and coordinates that every cv_*() function compares with the data
it is handed, so folds built from a different layer of the same size are
refused rather than applied. The methods that work in projected space
add crs, the CRS the folds were built in (an "EPSG:code" string
where there is one, otherwise the CRS's input definition). Every length
in params (block_size, sac_range, buffer, median_buffer) is in
that CRS's units, which for lon/lat input is a CRS
ensure_projected() chose, not one you passed.
For "block_kfold" the block design comes with the folds:
-
blocks: an sf layer of the block polygons in the CRS the folds were built in. Its rows are not the rows of the layer the blocks came from:drop_empty_blocks = TRUE(the default) removes the blocks that hold no point and renumbers the rest, so with suppliedblocksa nine-polygon layer of which three are empty comes back as six rows numbered 1 to 6.blocks$source_rowis the row each one came from (a grid cell's index in the fullgrid_nxbygrid_nygrid, or the row of theblocksargument), soblocks[params$blocks$source_row, ]recovers them with their own columns and in their own order. It runs from 1 ton_blocksand is the identity when nothing was dropped. -
n_blocksandblocks_used: for a grid,n_blocksisgrid_nx * grid_ny, the cells aboundaryclips away included, andblocks_usedthe number of blocks returned. -
block_sizes: the number of points in each block, indexed byblock_id(zeros are empty blocks thatdrop_empty_blocks = FALSEkept);fold_blocks: a list with one integer vector per fold naming the blocks packed into it. Between them the folds account for every block once, empty ones included, so a fold's territory on the map is all of its blocks, andtable(assignment$fold)can be traced back to the blocks it is made of.plot_folds()draws the blocks over the data. -
block_widthandblock_height: the width and height of the grid cells built, before any clipping to aboundary(NAfor suppliedblocks). They are whatblock_sizeturned into: at least that size on an axis long enough to hold it, and the whole extent on an axis that is not. -
blocks_suppliedandboundary_supplied: whether the blocks came fromblocks, and whether aboundarywas given. -
block_scale,balance_ratio,balance_tol,block_size,block_multiplier,sac_rangeandauto_range: the length compared with the range (see the section "Supplied blocks"), the balance achieved and allowed, and the sizing settings.
For "nndm", params carries the diagnostics named in the section
"NNDM". For "knndm" it carries chosen ("random" or "clusters"),
n_clusters (the number of clusters packed into the folds; NA for the
random partition), clustering ("ward" or "kmeans+ward"; NA when
no cluster count was tried), candidates (a data frame with one row per
candidate, the random partition first: candidate, n_clusters,
largest_fold, balance_ratio, admissible and W, which is NA for
a candidate set aside), wasserstein, wasserstein_random and
wasserstein_loo (the Wasserstein distance to the target of the folds
returned, of the random partition among the candidates and of plain
leave-one-out, in distance units), fold_sizes, balance_ratio,
target_distances and realised_distances (one per prediction point,
and one per row: its distance to the nearest point of another fold) with
their medians and means, and the diagnostics "nndm" reports under the
same names: max_ecdf_excess, max_ecdf_deficit, loo_ecdf_deficit,
ecdf_deficit_tol, target_separated and target_out_of_reach, with
short_of_target for the opposite case (see the section "kNNDM"). With
max_test, params$max_test records the value.
Rows without a location (an empty point, or a coordinate that is not
finite or lies beyond 1e150) are dropped before folding, with a logged
warning naming the count; they appear in no fold and in no assignment
row. The bound is read on the coordinates as given, and again after the
projection for the methods that measure distance.
Fold methods
| Method | Held out in each fold | Needs | Suits a map that |
"random_kfold" | a random 1/k of the rows | k | predicts among the samples, over an area they cover evenly |
"block_kfold" | whole blocks of a grid, or of blocks | k; block_size or auto_range to size the grid | predicts into unsampled gaps about as wide as the blocks |
"buffered_loo" | one point, with its neighbours within buffer left out of training | buffer | predicts at a known distance from the data |
"leave_location_out" | every row of one or more locations | group_var | predicts at sites with no measurements, from repeated measurements at others |
"nndm" | one point, with neighbours left out to match the prediction distances | prediction_points; at most 5,000 rows | predicts at known locations, with a model cheap enough to refit once per point |
"knndm" | k folds matched to the prediction distances | prediction_points | predicts at known locations, from a large layer or with a costly model |
A cross-validated error is the error at the distances the folds put
between the held-out points and their training data. It reads low for
predictions made farther from the data than the held-out points sit, and
high for predictions made closer, so which folds to use depends on where
the model will predict. fold_separation() with prediction_points
compares the two distances, and method = "nndm" and "knndm" build
folds matched to them.
"random_kfold" ignores geography: a held-out point keeps most of its
neighbours in the training data, so the score is the error of predicting
among the samples. That is the error of a map over an area the samples
cover evenly, and it reads low for predictions made farther from the data,
such as a map of a whole region from clustered samples. "block_kfold"
holds out whole blocks, so the held-out points sit farther from their
training data the wider the blocks are, and the score is the error of
predicting into unsampled gaps of that size; for a map of an area the
samples cover, it reads high. "buffered_loo" holds out one point at a
time and excludes everything within a fixed buffer from its training
set. "leave_location_out" groups by group_var, so all observations
from a location share a fold.
Block size and the autocorrelation range
With block_size, each axis of the extent gets as many blocks as leave
every block at least that long, so on an axis at least as long as
block_size the blocks are from one to just under two times this size.
An axis shorter than block_size is spanned by one row or column of blocks
as long as the extent there: a 39.8 km by 5 km extent with
block_size = 10000 gets three blocks 13.3 km wide and 5 km tall. A size
that leaves fewer than k blocks holding points returns that many folds,
with a warning (see k); one that leaves a single block is an error. Both
name the largest size that still gives k folds. A size in the wrong unit
asks for an enormous grid, so a request above 1,000,000 blocks is refused
with an error naming the grid dimensions, the extent and the CRS's units.
Without block_size or auto_range, the grid is sized from the extent
and block_multiplier (or block_nx and block_ny) alone, with no
regard to the autocorrelation range of the data. The wider the blocks, the
farther the held-out points sit from their training data. When blocks are
smaller than the autocorrelation range, each held-out point still has
training data within the range. The score is then the error of predicting
that close to the data. It reads low for a map whose locations lie farther
from the samples, and is the error of a map whose locations lie as close.
block_size sets a minimum block edge length in CRS units, and
auto_range = TRUE estimates the range with estimate_sac_range() and
uses it as that minimum. When a response is given and the blocks are
smaller than the estimated range, make_folds() warns and gives the block
size of the range. When blocks of that size leave fewer than k folds on
this layout, the warning also names the largest size that still gives k
folds and a method that needs no block size ("nndm", or "knndm" above
5,000 rows).
Sizing blocks from the autocorrelation range is the recommendation of
Roberts et al. (2017) and what blockCV (Valavi et al. 2019)
automates. blockCV takes the fitted variogram's range parameter as
the block size; auto_range takes the effective range that
estimate_sac_range() returns, three times that parameter for an
exponential fit, so its blocks are larger than blockCV's from the
same variogram. The estimate is the omnidirectional range. On a field
known to be anisotropic, pass
block_size = max(attr(r, "directional_fitted"), na.rm = TRUE) yourself
after checking attr(r, "directional_status") (see the section
"Directional ranges and anisotropy" in estimate_sac_range()).
Range-sized blocks do not fit every layout. On a square extent at
k = 5, a range up to a third of the side gives five folds; up to half, a
2 by 2 grid and four folds, returned with the "spatialkit_k_reduced"
warning. Above half the extent in both directions there is room for a
single block, and make_folds() stops with an error naming the size
rather than return one fold with an empty training set. The warning and
the error name the largest block size that still gives k folds on this
layout and how far below the range it is. When no range is identified,
the geometric grid is used instead, with a warning that gives the reason.
When the range is used, a message states the grid and the block size
built.
NNDM
"nndm" implements the distance-matching principle of Milà et al. (2022):
it sizes the exclusion around each held-out point, with no fixed buffer,
so that the distribution of distances from the held-out points to their
training data approaches the distribution of distances from the
prediction locations to the training data.
The procedure is the paper's, and it is deterministic. Let
G_{ij} be the empirical distribution of
prediction-to-nearest-training distances and G_j^* the
distribution of each held-out point's distance to its nearest remaining
training point. Starting from plain leave-one-out, the point with the
smallest G_j^* at which the realised distribution exceeds the
target (G_j^*(r) > G_{ij}(r)) has its nearest
training neighbour removed, and this repeats until no such point remains,
within two limits. A point is matched only while its nearest-neighbour
distance is at most phi (default: the largest prediction distance,
since a training point already farther than every prediction distance has
nothing to match), so the exclusion that takes it past phi is its last
and a realised distance can exceed phi by up to one neighbour step. And
no fold's training set is stripped below min_train of the data.
It differs from CAST::nndm() in two details, so the folds agree closely
with CAST's but not exactly. The removal rule is strict: a neighbour is
removed whenever the realised distribution exceeds the target, where CAST
removes one only while the realised distribution, less the point about to
move, is still at or above the target. The rule here therefore removes
up to one point more per distance value, erring towards held-out distances
longer than the target. And ties in G_j^* are broken by the
points' coordinates, not by their row index as in CAST, so the folds do
not depend on the order of the rows (see the section "Numerical
tolerances").
Where neither limit binds, the realised distribution of nearest-neighbour
distances is never shorter than the target:
G_j^*(r) \le G_{ij}(r) up to the granularity of
the neighbour distances, which is the property the method exists to
deliver. It is a statement about the distance to the one nearest
training point. A learner that draws on several neighbours (a forest, a
k-nearest-neighbour mean, a kriging neighbourhood) also depends on how far
the second and later neighbours are, which NNDM does not match, so on
clustered samples its cross-validated error can still read low for the
prediction points with the nearest-neighbour distances matched exactly.
Beyond phi no matching is attempted. min_train is different: when the
prediction locations lie farther from the samples than a fold can be made
to hold out (clustered samples and a prediction domain well beyond them,
the layout NNDM is meant for), it stops the matching early and the
realised distances stay too short. params$n_at_min_train counts the
folds held at the floor while still closer than the target allows, and
make_folds() warns when that leaves more than one point's worth of
excess at or below phi. Lower min_train to match further, or read the
cross-validated score as an upper bound on performance at the prediction
locations. params$max_ecdf_excess reports the largest remaining excess;
compare params$target_median with params$realised_median as well.
The match has a second side. params$max_ecdf_deficit is the largest
amount by which the target distribution runs above the realised one, the
mirror of params$max_ecdf_excess: the share of prediction points within
some distance of the data that the folds do not reproduce. Part of it is
the granularity of the matching. Excluding a neighbour moves a held-out
point out to its next remaining neighbour, and on clustered samples that
can be the next cluster, well past the prediction distances.
The other part no setting reaches. Excluding neighbours can only lengthen
a held-out distance, so when the prediction points sit nearer to the data
than the samples sit to each other (prediction points among the samples,
or a regular sample predicted between its nodes) the folds returned are
plain leave-one-out and are still farther from their training data than
the prediction points are. The cross-validated error is then pessimistic
for those prediction points: an upper bound on the error there.
params$loo_ecdf_deficit is the largest amount by which the target
distribution runs above that of plain leave-one-out. When it exceeds
params$ecdf_deficit_tol, three times \sqrt{1/n + 1/m} for n folds and m prediction points (about three times
the chance difference between two samples of one distribution),
make_folds() raises a warning of class "spatialkit_nndm_out_of_reach"
and sets params$target_out_of_reach to TRUE.
On small samples no deficit can exceed that tolerance. A deficit is a
difference of two shares, so it is at most 1, and the tolerance is 1 or
more whenever nm/(n+m) \le 9: for nine folds or fewer
whatever the number of prediction points, and for up to eighteen folds with
as many prediction points. There the same warning is raised in one case
only, complete separation: every prediction point nearer to the data than
any sample is to its nearest other sample, by more than one part in ten
million (a deficit of 1), provided the two sets are large enough for that
ordering to mean something, taken as choose(n + m, n) >= 1000 ways of
interleaving them (17 prediction points for 3 folds, 7 for 6 folds, 4 for
12 folds). params$target_separated records the ordering whether or not
it was enough to warn, and the warning's condition carries it as
separated. With very few samples it can hold for a grid over the
samples' own extent, because a few points hug the box they span; the folds
are then farther than the grid all the same. A partial shortfall on such a
sample (most prediction points nearer than leave-one-out reaches, not all)
is not warned about, since no difference of shares exceeds a tolerance of 1
or more. Compare params$target_median with params$realised_median.
params$wasserstein is the Wasserstein distance between the target and
realised distributions, in distance units, and params$wasserstein_loo
the same for plain leave-one-out: equal when nothing was excluded, smaller
when the matching helped.
kNNDM
"knndm" is the k-fold version of NNDM (Linnenbrink et al. 2024): k
folds, and so k model fits, whose held-out distances are as close to the
same target as a set of candidates allows. It has no row limit, and is
the method to use above the 5,000 rows "nndm" takes or when a model is
too costly to refit once per point. Below that it matches less closely
than NNDM, since a fold design has far fewer degrees of freedom than one
exclusion set per point.
The candidates are a random k-fold partition (the one "random_kfold"
builds with the same seed) and, for each of up to 50 cluster counts
spaced evenly on the log scale from k to one fewer than the number of
distinct locations, the samples clustered on their coordinates and the
clusters merged into k folds. Few large clusters give folds that are
whole areas, far from their training data; many small ones approach the
random partition. Up to 4,000 points the clustering is Ward's
(stats::hclust(method = "ward.D2")), cut at each count. Above that,
where the n by n distance matrix it needs is too large, k-means first
reduces the samples to 4,000 groups (Lloyd's algorithm from random sample
locations, at most ten passes) and Ward's method is continued from those
groups; a count above 4,000 is a k-means run of its own.
params$clustering says which ("ward" or "kmeans+ward"). Clusters are
merged by the packing "block_kfold" uses for its blocks, largest first
and each to the fold with the fewest points so far (see the section "Fold
balance"). CAST::knndm() merges clusters by a rule of its own, which
this was not checked against, so the folds are not expected to equal
CAST's.
Each candidate is scored by the Wasserstein distance W between its
held-out distances (each point's distance to the nearest point of another
fold) and the target distances, in the unit of the layer, and the smallest
W is returned; of the candidates within one part in ten million of
the smallest, the earliest in params$candidates. A candidate is set
aside without being scored when its largest fold leaves less than
min_train of the rows for training or holds more than balance_tol
times the points of its smallest; the random partition is always kept. So
params$wasserstein is never above params$wasserstein_random, the
W of that random partition, and params$candidates lists every
candidate with its cluster count, fold sizes and W.
params$chosen is "random" when no clustering came closer, as for
samples spread evenly over the prediction area. Read W against the
mean target distance; it has no sign, so it measures the mismatch in either
direction. With few folds a random partition can itself be farther than
the target, since each fold trains on 1 - 1/k of the points.
Construction time grows with the number of points and of folds.
Two cases are warned about, each with a condition class. When the
prediction points sit nearer to the data than a sample is to its nearest
other sample, no fold design reaches them, since a held-out point is never
nearer to its training data than that; the test is the one "nndm"
applies, the warning has the same class, "spatialkit_nndm_out_of_reach",
and what comes back is the random partition or a candidate as fine as one.
In the other direction, the closest candidate can still be short of the
target: prediction points well beyond the samples lie farther from the
data than k folds of those samples can be held apart. When the mean
held-out distance of the folds returned is below the mean target distance
by more than a quarter of it and by at least half of W (the test
fold_separation() words as "closer"), make_folds() raises a warning
of class "spatialkit_knndm_short_of_target" and sets
params$short_of_target: the cross-validated error then tends to read low
for the prediction points. Fewer folds hold out larger areas. Short of
either warning the folds can still differ from the target at some
distances; params$max_ecdf_excess and params$max_ecdf_deficit give the
largest difference each way, and fold_separation() reads the folds
against the same prediction points fold by fold.
Supplied blocks
A polygon layer passed as blocks is aligned to the points the way
boundary is, and then brought into the CRS the folds are built in (see
spatialkit-geometry). A point inside more than one block is given the
first (lowest row) that contains it, as for a point on the shared edge of
two grid cells, and a point within the margin of a block's edge (see the
section "Numerical tolerances") counts as inside it. When the blocks that
caught such a point share area instead of an edge, the layer overlaps and
is not a partition, and make_folds() warns. A point inside no block is
assigned to the nearest one, by distance to the polygon itself; a point the
same distance from two blocks, to one part in ten million or that margin,
goes to the lower row. The count of such points is warned about, unless
they sit within a millionth of the extent of a block, an edge that
reprojection or clipping moved by a rounding error. Blocks that hold no
point are dropped when drop_empty_blocks = TRUE, and k is lowered to
the number of blocks that hold points when that is smaller.
params$n_blocks is the number of blocks before empties were dropped and
params$blocks_used the number after (so with drop_empty_blocks = FALSE
the two are equal, and sum(params$block_sizes > 0) is how many hold
points); params$grid_nx and params$grid_ny are NA.
params$block_scale is the median, over the blocks that hold points, of
the side of the square with the block's area. A polygon has no single
edge length, so that is the length compared with the autocorrelation range
for the warning on blocks smaller than the range.
Every set of cells build_tessellation() builds can be a block design
here, including Voronoi cells around get_voronoi_seeds(method = "kmeans")
seeds, which adapt to the density of the points.
Fold balance
"block_kfold" and "knndm" balance the number of points per fold by
packing: blocks (for "knndm", clusters of the samples) are taken largest
first and each goes to the fold with the fewest points so far, ties broken
at random. This is the longest-processing-time rule for multiway
partitioning, and make_folds() offers no search over other packings.
The remedy for an imbalance past balance_tol is the block design:
smaller blocks, or blocks that adapt to the density of the points, passed
through blocks. Density-adaptive blocks are smaller where points are
dense, so check params$block_scale against the autocorrelation range as
you would a grid.
"knndm" chooses its clusters, so for it balance_tol is a limit: a
clustering whose packing exceeds it is not a candidate, and the folds
returned are within it (params$fold_sizes, params$balance_ratio).
The other methods do not balance point counts. "random_kfold" is
balanced by construction (fold sizes differ by at most one);
"buffered_loo" and "nndm" hold out one point per fold;
"leave_location_out" gives each fold the same number of locations (to
within one), so folds differ by as much as the locations' sizes do.
Numerical tolerances
A point on the edge two grid cells share goes to the lower one, the cell
with the lower index in the full grid (params$blocks$source_row; the grid
is numbered along each row from the bottom left, so the cell to the left or
below). A point is on an edge while it lies within one part in 1e10 of the
largest coordinate of the points and the blocks from it (0.44 mm at a UTM
northing of 4,400 km), at most a millionth of the diagonal of their
bounding box and at least four times the spacing of doubles at that
coordinate, so points on the grid lines of a lattice are blocked alike in
any unit or origin. A point in no cell of a clipped grid goes to the cell
with the nearest centroid, and to the lower of two whose centroids are as
near to one part in ten million or that margin. The same margin decides
whether a point lies on a boundary or inside a supplied block.
A block shorter than block_size by no more than one part in ten million
counts as that long, so a size of exactly the axis over a whole number
gives that number of blocks in any unit. A neighbour of a
"buffered_loo" point at the buffer distance is excluded, and so is one
over it by rounding: a squared distance within one part in ten million of
the buffer's square (a distance about one part in twenty million over the
buffer) counts as at it, so a lattice whose spacing divides the buffer
gives the same folds in any unit or origin.
NNDM counts distances within one part in ten million of each other as
equal, when the held-out distances are counted, compared with the target
and phi, and put in order. Equal ones are taken by the column of the
point (first coordinates within that part of the extent of the points count
as one), then its second coordinate, counted the same way, then its row.
Each point's neighbours are put in order by the same rule, so of
neighbours that are equally far away the same one is excluded first. The
folds are then the same in another unit or with another origin as long as
no coordinate moves by more than about a two-hundred-millionth of the
distance between neighbouring locations.
The clusterings of kNNDM read the coordinates centred on the middle of
their bounding box, divided by its diagonal and rounded to
2^-30 of it (about a billionth), as the "kmeans" partition
hands them to stats::kmeans(); on a lattice many merges and many
assignments tie exactly, and the last bits of the coordinates, which move
with the unit and the origin, would settle them. A point as near two
k-means centres to one part in ten million goes to the lower-numbered one:
a squared distance ties with the least when it is no more than the square
of the least distance lengthened by a margin, plus one part in ten million
of the least squared distance, the margin one part in 1e10 of the largest
coordinate of the centres in that frame, at most a millionth of the
diagonal of their bounding box and at least four times the spacing of
doubles at that coordinate. The clusters are then the same in another unit
or with another origin, but for a location within its own rounding noise of
the middle of a step.
Points so far from the origin of their coordinates that doubles there are
spaced more than a millionth of the points' extent apart are held to that
spacing, and so are the edges of the blocks laid over them (see the
section "Coordinates far from the origin" in spatialkit-geometry). With
method = "block_kfold" or "buffered_loo" the folds are made, and a
warning of class "spatialkit_xy_imprecise" gives the spacing and the
extent.
References
Linnenbrink, J., Mila, C., Ludwig, M. and Meyer, H. (2024). kNNDM CV: k-fold nearest-neighbour distance matching cross-validation for map accuracy estimation. Geoscientific Model Development 17, 5897-5912. doi:10.5194/gmd-17-5897-2024
Mila, C., Mateu, J., Pebesma, E. and Meyer, H. (2022). Nearest neighbour distance matching Leave-One-Out Cross-Validation for map validation. Methods in Ecology and Evolution 13, 1304-1316. doi:10.1111/2041-210X.13851
Roberts, D. R., Bahn, V., Ciuti, S., Boyce, M. S., Elith, J., Guillera-Arroita, G., Hauenstein, S., Lahoz-Monfort, J. J., Schroder, B., Thuiller, W., Warton, D. I., Wintle, B. A., Hartig, F. and Dormann, C. F. (2017). Cross-validation strategies for data with temporal, spatial, hierarchical, or phylogenetic structure. Ecography 40, 913-929. doi:10.1111/ecog.02881
Valavi, R., Elith, J., Lahoz-Monfort, J. J. and Guillera-Arroita, G. (2019). blockCV: An R package for generating spatially or environmentally separated folds for k-fold cross-validation of species distribution models. Methods in Ecology and Evolution 10, 225-232. doi:10.1111/2041-210X.13107
See Also
plot_folds() to map the folds, fold_separation() to measure
how far the held-out points sit from their training data,
cv_spatial() to score a model on them, and cv_block_size_sweep() to
cross-validate at a ladder of block sizes.
Other folds:
cv_block_size_sweep(),
fold_separation(),
plot_folds()
Examples
library(sf)
set.seed(1)
pts <- st_as_sf(
data.frame(x = 5e5 + runif(30, 0, 1000), y = 5e6 + runif(30, 0, 1000)),
coords = c("x", "y"), crs = 32632
)
folds <- make_folds(pts, k = 3, method = "block_kfold", seed = 42)
folds$assignment # fold and block of each row
lengths(folds$folds[[1]]) # the train and test row IDs of fold 1
folds$params$block_sizes # points per block
folds$params$fold_blocks # the blocks each fold holds
# Buffered leave-one-out: neighbours within 100 m left out of training.
loo <- make_folds(pts, method = "buffered_loo", buffer = 100)
loo$k # one fold per point
# Three folds matched to the distances from a prediction grid to
# clustered samples.
set.seed(2)
cx <- runif(6, 0, 1e4); cy <- runif(6, 0, 1e4)
xy <- do.call(rbind, lapply(1:6, function(i)
cbind(cx[i] + rnorm(15, 0, 200), cy[i] + rnorm(15, 0, 200))))
cl <- st_as_sf(data.frame(x = 5e5 + xy[, 1], y = 5e6 + xy[, 2]),
coords = c("x", "y"), crs = 32632)
grid <- st_make_grid(cl, n = c(20, 20), what = "centers")
km <- make_folds(cl, k = 3, method = "knndm", prediction_points = grid,
seed = 42)
km$params[c("chosen", "n_clusters", "wasserstein", "wasserstein_random")]
Compute goodness-of-fit metrics for a fitted model
Description
Reports RMSE, MAE, MAPE, SMAPE, R^2 and adjusted R^2 for any
spatial_fit as a one-row data frame. With newdata it scores
rows you held out yourself. Without it, it reads the fit's own fitted
values: in-sample for a GWR or a Bayesian GP fit, out-of-bag for a random
forest. Those numbers do not compare across backends, and the data frame
carries no label saying which kind it holds.
Usage
model_metrics(object, ...)
## S3 method for class 'spatial_fit'
model_metrics(object, newdata = NULL, ...)
Arguments
object |
A |
... |
Passed to |
newdata |
Optional sf object of held-out rows, carrying the response
and the predictors. If |
Details
Use this function for one fit. evaluate_insample() runs it
over a list of fits and labels each row with its basis, and
compare_models() adds information criteria and residual
Moran's I to that table. None of the three refits a model. An in-sample
score is not a cross-validation score: a GWR can reach a near-perfect
in-sample R^2 at a small bandwidth without predicting anything. For
a figure you can report, use cv_gwr(),
cv_bayes(), cv_rf() or
compare_models_cv().
Value
A one-row data.frame with n, RMSE, MAE,
MAPE, SMAPE, R2, Adj_R2, n_MAPE and
n_SMAPE (the last two are the rows each percentage error was
averaged over). Adj_R2 is always NA: a GWR's effective
number of parameters far exceeds the global predictor count and a GP
model has no simple p. A character or factor response is an
error; a logical response is scored as 0/1.
What the metrics are computed on
With newdata = NULL the metrics come from fitted(object).
That is in-sample for a GWR or a Bayesian GP fit, and out-of-bag for a
random forest, whose fitted() method returns out-of-bag predictions
(see fit_rf_model()). Check
object$info$fitted_are_oob before comparing numbers across
backends; evaluate_insample() and
compare_models() record it per model in a
metric_basis column, and compare_models_cv() scores
every backend the same way.
R^2 is 1 - RSS/TSS with the total sum of squares taken about
the mean of the response the model was fitted to. In sample that is the
ordinary R^2. With newdata it is the out-of-sample
R^2 every cv_*() function uses: the model is measured against
the training mean, the prediction it had to beat, and not against the new
rows' own mean, which it could not have known. It is below 0 when the
model predicts the new rows worse than the training mean does, and
NA when the response does not vary about that mean beyond the
rounding of its values, whatever its units and origin.
A GWR fit whose response fit_gwr_model() took about a centre
(fit$engine$centres$response, a response at a large offset) is
scored on the response and the fitted values or predictions less that
centre, which keep digits that rounding at the response's size would
lose: RMSE, MAE and R^2 are those of the same values
at 0, and MAPE and SMAPE divide the same errors by the
values in the response's units. fitted() and predict()
still return values in the response's units.
Percentage errors on responses with zeros
MAPE divides by the observed value and SMAPE by
|y| + |\hat{y}|, so neither is defined where its denominator is zero.
Neither returns Inf or NaN. Both are averaged over the rows
whose denominator is non-zero, and are NA when no row qualifies.
Non-zero is judged at the scale of the data: a denominator no larger
than 100 machine epsilons times the largest one counts as zero, so the
rule does not depend on the units of the response.
The n_MAPE and n_SMAPE columns record how many rows that was;
the n column (n_pred in a cross-validation result) counts
finite observation/prediction pairs. Read a percentage error next to that
count: when n_MAPE is smaller, MAPE is an average over a
subset of the data, whatever its value.
Any response taking exact zeros is affected: counts, rainfall, abundance,
claim amounts. On a zero-inflated response with 62 zeros out of 120,
MAPE averages the 58 non-zero rows and n_MAPE is 58.
SMAPE drops the rows where observation and prediction are both
near zero, which on a well-fitted zero-inflated model are the rows it got
right, so it averages the harder rows only and reads worse than the fit
deserves. n_SMAPE shows how many rows it kept; it does not correct
the average.
RMSE, MAE and R^2 use every finite row; prefer them
whenever the response can be zero. For a Bayesian GP fit,
cv_bayes() also reports CRPS and interval coverage, which
are proper scoring rules and are defined at zero.
Which metrics survive a non-Gaussian response
RMSE and MAE are defined for any numeric response and are what to read for
a count, a rate or a bounded outcome. MAPE and SMAPE assume a response
that is rarely zero (see "Percentage errors on responses with zeros"), and
R^2 and adjusted R^2 compare residual variance to total
variance, which suits a Gaussian response and fits loosely anything whose
variance tracks its mean. On a Poisson or zero-inflated response read the
four as a rough summary rather than a score.
For the Bayesian GP, cv_bayes() also reports CRPS and
interval coverage at its coverage_levels (50, 80 and 95 percent by
default). Both are proper scoring rules computed from posterior draws, so
they are meaningful for any family that predicts one number per row
(a count, a rate, a binary or bounded outcome), and they are the numbers
to compare when the response is not Gaussian. A categorical or ordinal
family predicts a probability per response category instead, so
cv_bayes() refuses one before fitting anything. When every fold
fails, the fold_metrics frame cv_bayes() returns carries
the CRPS column but not the coverage_* columns, so code that
reads those columns must allow for their absence.
See Also
Other in-sample checks:
compare_models(),
evaluate_insample(),
print.morans_i(),
residual_morans_i()
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
)
# An offset keeps the response away from zero, where MAPE is undefined.
pts$z <- 10 + 2 * pts$a + rnorm(60, 0, 0.3)
# Fit on 40 rows and keep 20 back, so the second call is out of sample.
fit <- fit_rf_model(pts[1:40, ], "z", "a", num_trees = 50, seed = 1)
model_metrics(fit) # out-of-bag for a forest
model_metrics(fit, newdata = pts[41:60, ]) # on the 20 held-out rows
Build a spatial_fit object for a backend of your own
Description
The constructor for the spatial_fit class, and the way to plug a
model backend of your own into this package. The three built-in fitters
(fit_rf_model(), fit_gwr_model() and
fit_bayesian_spatial_model()) all end by calling it, and so
should a custom fit_fn written for cv_spatial(). A
model wrapped in a spatial_fit works with the package's folds,
metrics, comparisons and area of applicability unchanged.
Usage
new_spatial_fit(
subclass,
engine,
formula,
response_var,
predictor_vars,
data_sf,
info = list()
)
Arguments
subclass |
Character scalar naming the class to stamp on the object:
one of the built-ins |
engine |
The raw model object your backend produced (an |
formula |
A formula: the model, as |
response_var |
Character(1): the name of the response column of
|
predictor_vars |
Character vector of attribute column names of
|
data_sf |
An sf object with its geometry column: the rows the model
was fitted on, with their geometry, in the order |
info |
Named list of model-specific extras ( |
Details
A custom backend needs three things:
a
fit_fnthat returns an object built bynew_spatial_fit();a
predict.<subclass>()method for thesubclassyou chose.cv_spatial()scores each fold by calling thepredict()generic on the fit, so without one every fold fails;a
fitted.<subclass>()method that returns one value per row of the fit'sdata_sf, in the same order.summary()andmodel_metrics()need it, and without one they stop with an error that names the method to define.
residuals() and coef() methods are optional.
The constructor checks the fields the package's functions read from a fit,
and stops with an error that names the argument: subclass must be
one class name, data_sf an sf object with its geometry column,
formula a formula whose left side, when it has one, holds the
response, response_var the name of one attribute column of
data_sf (a column other than its geometry),
predictor_vars a character vector of its attribute columns other
than the response, the columns the right side of formula uses, and
info a list. It does not check the
response's type (a Bayesian fit can have a factor or ordinal response);
summary() and model_metrics() refuse a response
that is not numeric or logical.
Value
An object of class c(subclass, "spatial_fit"): a list with
engine, formula, response_var,
predictor_vars and data_sf as given, n (the number
of rows of data_sf) and info (the list given, with a
private cache environment added as info$.cache, which methods
should not modify).
The coef() contract
coef() on one of the three built-in backends either returns the
coefficients or signals an error. It never returns NULL. A custom
subclass inherits stats::coef.default(), which returns NULL,
so define a coef.<subclass>() that errors when your backend has no
coefficients. coef.rf_fit() always errors, because a forest has no
coefficients; coef.gwr_fit() and coef.bayesian_fit() error
when the backend cannot supply them (a missing package, an engine without
the expected component). A NULL return could not be told from
"this model has no fixed effects", and lapply(fits, coef) would
return a shorter answer than the caller expected. Wrap the call in
try() or tryCatch() when sweeping over a list of fits from
different backends.
See Also
cv_spatial(), which takes a custom fit_fn;
fit_rf_model() for a built-in fitter.
Other model fitting:
fit_bayesian_spatial_model(),
fit_gwr_model(),
fit_rf_model(),
gp_lengthscale_bounds()
Examples
library(sf)
set.seed(1)
n <- 80
site <- st_as_sf(
data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
elev = rnorm(n)),
coords = c("x", "y"), crs = 32632
)
site$price <- 10 + 0.01 * (st_coordinates(site)[, 1] - 5e5) +
2 * site$elev + rnorm(n)
# A custom backend: an ordinary linear model behind the spatial_fit interface.
lm_fit <- function(train_sf) {
new_spatial_fit(
subclass = "lm_fit",
engine = lm(price ~ elev, st_drop_geometry(train_sf)),
formula = price ~ elev,
response_var = "price",
predictor_vars = "elev",
data_sf = train_sf
)
}
# Required: cv_spatial() scores each fold through the predict() generic,
# which dispatches on the subclass named above.
predict.lm_fit <- function(object, newdata = NULL, ...) {
if (is.null(newdata)) newdata <- object$data_sf
as.numeric(stats::predict(object$engine, st_drop_geometry(newdata)))
}
registerS3method("predict", "lm_fit", predict.lm_fit)
# Required by summary() and model_metrics(): one value per training row.
fitted.lm_fit <- function(object, ...) as.numeric(stats::fitted(object$engine))
registerS3method("fitted", "lm_fit", fitted.lm_fit)
summary(lm_fit(site))
cv <- cv_spatial(site, "price", "elev", fit_fn = lm_fit, k = 3, seed = 1)
cv$overall
# Check that these two agree before reading the metrics above.
c(attempted = cv$n_folds_attempted, succeeded = cv$n_folds_succeeded)
Plot the dissimilarity distribution behind an area of applicability
Description
Draws the dissimilarity index of the prediction locations against that of
the training data, with the threshold marked, so you can see whether the
prediction set sits well inside, near the threshold or outside.
n_outside gives only how many prediction locations fall outside
the area of applicability, not how close to the threshold the rest sit or
how far outside the outsiders are. The
training DI is cross-validated over the folds passed to
area_of_applicability(), or without them is each training
point's distance to its nearest other training point; the legend and the
caption say which. The training curve is the reference the threshold was
derived from: the threshold is the largest training DI inside an outlier
fence, so the curve reaches it exactly when no training value was fenced
off and runs past it, by the tail the fence removed, when some were.
A prediction location outside on a predictor dropped for having no
training variance, or under categorical = "indicator" on a level no
training row has, has DI = Inf: it counts in the prediction curve,
which then tops out below 1, and the caption says how many are off the
axis. A location with a missing predictor (DI = NA) is neither
inside nor outside; it is left out of the curve and the caption counts it.
Usage
## S3 method for class 'aoa'
plot(x, type = c("ecdf", "histogram"), ...)
Arguments
x |
An |
type |
|
... |
Not used. |
Details
When location has an index of its own (a gwr_fit, a
bayesian_fit, a forest fitted with include_coords = TRUE,
or coords = "yes"; see area_of_applicability()), the
curves and the dashed line are the predictor index alone (for the forest,
its ..x and ..y columns included). The subtitle then counts
three things: the locations beyond the predictor threshold, those beyond
the location threshold, and those outside the area of applicability, which
is either.
Value
A ggplot object.
See Also
area_of_applicability(), which makes the object, and
print.aoa().
Other prediction:
area_of_applicability(),
predict_surface(),
print.aoa()
Examples
library(sf)
set.seed(2)
n <- 200
train <- st_as_sf(
data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
a = rnorm(n), b = rnorm(n)),
coords = c("x", "y"), crs = 32632)
train$z <- train$a - train$b + rnorm(n, 0, 0.3)
# Prediction locations whose predictor `a` drifts beyond the training range.
new <- st_as_sf(
data.frame(x = 5e5 + runif(100, 0, 1000), y = 5e6 + runif(100, 0, 1000),
a = rnorm(100, mean = 2), b = rnorm(100)),
coords = c("x", "y"), crs = 32632)
aoa <- area_of_applicability(new, train_sf = train, predictor_vars = c("a", "b"))
plot(aoa) # the two ECDFs
plot(aoa, type = "histogram")
Plot the path of a forward feature selection
Description
select_features_forward() scores every candidate at every
step and keeps the best; its history holds all of them. This draws
the accepted variable's score at each step as the path, every other
candidate's score at that step as a faint point, and the step at which the
selection stopped in red. When it stopped because no candidate passed
the acceptance rule (rule in select_features_forward()),
the path runs one step further to the best of the rejected candidates,
drawn hollow and labelled "not added", so the stop reads as a flattening
rather than a cut. The picture then shows whether the last variable was a
clear gain or a marginal one, and whether the runner-up would have done as
well. The scores are the selection's own cross-validated criterion,
optimistically biased by the selection (see "Selection score" in
select_features_forward()); when a hold-out score
was computed (select_on = "split") it is drawn as a separate mark
at the final step and named in the caption.
Usage
## S3 method for class 'feature_selection'
plot(x, ...)
Arguments
x |
The list returned by |
... |
Not used. |
Details
With a learner that cannot fit an empty predictor set the first variable
is added without a test and can be dropped at the end
(baseline$first$dropped). The path drawn is then the one the sweep
walked, with that variable hollow and labelled "dropped at the end", and
the red mark is the selected set, scored without it.
Value
A ggplot object.
See Also
select_features_forward(), which makes the object.
Other predictor selection:
gwr_model_selection(),
plot.gwr_model_selection(),
select_features_forward()
Examples
library(sf)
set.seed(4)
n <- 150
dat <- st_as_sf(
data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
a = rnorm(n), b = rnorm(n), c = rnorm(n)),
coords = c("x", "y"), crs = 32632)
dat$z <- 2 * dat$a - dat$b + rnorm(n, 0, 0.5)
fit_fn <- function(train_sf, vars)
fit_rf_model(train_sf, "z", vars, num_trees = 80, seed = 1)
sel <- select_features_forward(dat, "z", c("a", "b", "c"), fit_fn = fit_fn,
k = 3, quiet = TRUE)
plot(sel)
Plot a GWR model selection
Description
gwr_model_selection() ranks every model it evaluated on
AICc. This draws each model's criterion against its number of
predictors, the winner in red, so the gap between the best model and the
runners-up (which the ranked table shows only as numbers) is read as a
shape. A winner well below the rest is preferred; one within 2
AICc units of others is not separated from them (see "Printing" in
gwr_model_selection()). The criterion is in-sample, and the
caption says so.
Usage
## S3 method for class 'gwr_model_selection'
plot(x, ...)
Arguments
x |
A |
... |
Not used. |
Value
A ggplot object.
See Also
gwr_model_selection(), which makes the object.
Other predictor selection:
gwr_model_selection(),
plot.feature_selection(),
select_features_forward()
Examples
library(sf)
set.seed(1)
n <- 80
dat <- st_as_sf(
data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
a = rnorm(n), b = rnorm(n), noise = rnorm(n)),
coords = c("x", "y"), crs = 32632)
dat$z <- 2 * dat$a - dat$b + rnorm(n, 0, 0.5)
sel <- gwr_model_selection(dat, "z", c("a", "b", "noise"), bandwidth = 30)
# Every model tried, AICc against its size; the winner (a and b) marked.
plot(sel)
Plot a resolution profile
Description
The criteria of a resolution_profile() against the number of
cells, one panel per criterion on a shared x axis, with the level each
criterion selects marked and the region over which it is within tol
of its optimum shaded. The shading marks the flat region
select_resolution() reports. A criterion whose optimum sits
at an end of the levels it was scored at is captioned with which bound that
is (the support ceiling, the range floor, the ladder's own end, or the
first level the criterion is computable at), because there the bound is
choosing, not the criterion. A criterion that is NA at every
level is left out with a log line rather than drawn empty.
Usage
## S3 method for class 'resolution_profile'
plot(x, criteria = NULL, tol = 0.02, ...)
Arguments
x |
A |
criteria |
Character vector of criteria to draw, any of
|
tol |
Passed to |
... |
Not used. |
Details
A profile whose ladder is one size (obs_per_cell set to one
number, or the default profile) has one level, set by the size. Each
criterion that is finite there is drawn as one point in its panel, with
no selected level and no band, and the caption says that the size set
the count.
Value
A ggplot object.
See Also
resolution_profile(), which makes the object, and
select_resolution().
Other resolution:
determine_optimal_levels(),
resolution_profile(),
select_resolution(),
summary.resolution_profile()
Examples
library(sf)
# The same field as ?resolution_profile: an exponential covariance with
# range parameter 200 and a nugget of 0.6 on a unit sill.
set.seed(4)
n <- 400
xy <- data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000))
D <- as.matrix(dist(xy))
xy$z <- as.numeric(t(chol(exp(-D / 200) + diag(0.6, n))) %*% rnorm(n))
pts <- st_as_sf(xy, coords = c("x", "y"), crs = 32632)
prof <- resolution_profile(pts, response_var = "z", n_levels = 12)
# Two of the criteria it scored (plot(prof) draws every one, a panel each)
plot(prof, criteria = c("cp", "reliability"))
plot(prof, criteria = c("cp", "wss")) # Cp beside the raw WSS curve
Plot an estimated spatial autocorrelation range
Description
Draws the empirical variogram that estimate_sac_range() attaches to its
result, as a ggplot2 object, with the fitted model and the effective
range overlaid where a range was identified, and a subtitle that gives the
reason where it was not. A variogram that never reaches a sill, or that
has no spatial structure at the lags resolved, is drawn as well, since the
curve shows why the range came back NA.
Usage
## S3 method for class 'sac_range'
plot(x, ...)
Arguments
x |
A |
... |
Ignored. |
Details
Nothing is recomputed: the plot reads the variogram, variogram_model,
crs and rejected_reason attributes the estimate carries. The
variogram is the one over all point pairs. The distance axis is in the
units of the CRS the variogram was fitted in, which
estimate_sac_range() chooses itself for lon/lat input.
Value
A ggplot object.
See Also
estimate_sac_range(), which makes the object, and
plot.spatial_fit() with type = "variogram", which draws the same
picture for a fitted model's residuals.
Other spatial autocorrelation:
estimate_sac_range(),
sac_nugget()
Examples
library(sf)
# An exponential field with range parameter 150 (effective range about
# 450 m) and a nugget of half the sill, so the fitted model, the nugget and
# the range line all have something to show.
set.seed(3)
n <- 250
xy <- data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000))
D <- as.matrix(dist(xy))
xy$z <- as.numeric(t(chol(exp(-D / 150) + diag(0.5, n))) %*% rnorm(n))
pts <- st_as_sf(xy, coords = c("x", "y"), crs = 32632)
r <- estimate_sac_range(pts, response_var = "z")
plot(r)
# A field whose variogram never reaches a sill: the plot still draws it,
# and the subtitle says why no range is marked.
xy$trend <- sin(xy$x / 400) + rnorm(n, sd = 0.2)
r2 <- estimate_sac_range(st_as_sf(xy, coords = c("x", "y"), crs = 32632),
response_var = "trend")
plot(r2)
Plot a fitted spatial model
Description
Draws one of four diagnostic plots of a spatial_fit, as a ggplot2
object: the residuals mapped at the training locations, observed against
fitted values, the residual variogram beside the response's, or, for a
GWR, the map of one local coefficient. Use it to see whether spatial
structure is left in the residuals, and where.
Usage
## S3 method for class 'spatial_fit'
plot(
x,
type = c("residuals", "observed_predicted", "variogram", "coefficients"),
response = TRUE,
term = NULL,
mask = TRUE,
...
)
Arguments
x |
A |
type |
One of:
|
response |
Logical, default |
term |
For |
mask |
For |
... |
Ignored. |
Value
A ggplot object.
See Also
coef.gwr_fit() for the coefficients themselves.
Other fit methods:
print.spatial_fit(),
spatial_fit-coef,
spatial_fit-fitted,
spatial_fit-predict,
spatial_fit-residuals,
summary.spatial_fit()
Examples
# Works on any spatial_fit; a forest keeps the example free of the optional
# GWR and Stan backends.
library(sf)
# price depends on elevation, which the forest sees, and on a spatially
# correlated field it does not: that field is what the residual plots are
# there to find.
set.seed(2)
n <- 120
xy <- data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
elev = rnorm(n))
D <- as.matrix(dist(xy[, c("x", "y")]))
xy$price <- 10 + 2 * xy$elev +
as.numeric(t(chol(exp(-D / 100) + diag(0.3, n))) %*% rnorm(n))
pts <- st_as_sf(xy, coords = c("x", "y"), crs = 32632)
fit <- fit_rf_model(pts, "price", "elev", num_trees = 100, seed = 1)
plot(fit, type = "residuals") # structure left in the residuals
plot(fit, type = "observed_predicted")
if (requireNamespace("gstat", quietly = TRUE))
plot(fit, type = "variogram") # residual and response variograms
Plot the interval calibration of a Bayesian cross-validation
Description
cv_bayes() scores every fold's posterior predictive intervals
at each of coverage_levels: the share of held-out observations the
interval of that nominal level contained. This draws observed coverage
against nominal with the diagonal, one point per level for the
fold-weighted pooled value (from predictive_coverage) and one faint
point per fold, so you can see systematic over-confidence (points below
the line) or intervals wider than they need to be (above it). Three levels is a thin
curve; pass coverage_levels = seq(0.1, 0.9, by = 0.1) to
cv_bayes() for a full one. Each level is drawn at the nominal value
cv_bayes() records in coverage_levels, so whatever was
computed is drawn where it belongs (0.975 at 0.975, not rounded).
Usage
plot_calibration(cv, ...)
Arguments
cv |
The list returned by |
... |
Not used. |
Value
A ggplot object.
See Also
cv_bayes(), which makes the result.
Other cross-validation:
compare_models_cv(),
cv_bayes(),
cv_gwr(),
cv_rf(),
cv_spatial(),
plot_cv_metrics()
Examples
## Not run:
# Needs brms and a Stan toolchain, and takes minutes: run it, do not check it.
library(sf)
set.seed(1)
n <- 80
dat <- st_as_sf(
data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
a = rnorm(n)),
coords = c("x", "y"), crs = 32632)
dat$z <- 2 * dat$a + rnorm(n)
# Nine coverage levels give a curve rather than three points; chains and
# iterations are kept small to keep this to a few minutes, so the intervals
# will be rough.
cv <- cv_bayes(dat, "z", "a", k = 3, coverage_levels = seq(0.1, 0.9, 0.1),
fit_args = list(chains = 2, iter = 1000))
plot_calibration(cv)
## End(Not run)
Plot one cross-validation metric fold by fold
Description
One pooled RMSE can come from the same error in every fold or from small
errors in most folds and a large one in a single fold (a model that
works, and a model that fails in one block), and the pooled number cannot
tell the two apart. This draws the
metric of each fold as a point, sized by the number of held-out
predictions the fold contributed, with the pooled value from
overall as a horizontal line, so the spread behind the number is
visible. A compare_models_cv() result draws one panel per
model on a shared scale, folds aligned, which is the comparison the shared
fold set was built for.
Usage
plot_cv_metrics(cv, metric = "RMSE", ...)
Arguments
cv |
The list returned by |
metric |
Character(1) naming a column of |
... |
Not used. |
Details
Any column of fold_metrics can be drawn, including a backend's
extras (bandwidth, CRPS, coverage_95) and columns a
metrics function added. A column that is NA in every fold is
refused with a message saying why rather than drawn as an empty panel:
Adj_R2 is NA for every backend unless p was passed to
cv_spatial(), by design. The pooled line is drawn from
overall when it carries the metric, from
predictive_coverage for cv_bayes()'s coverage and CRPS
columns, and not at all for a per-fold extra that has no pooled
counterpart (a bandwidth) or for a count (n_pred,
n_MAPE, n_SMAPE), whose overall value is the
total over the folds; the caption says which. A model with no finite
per-fold value gets no panel and no pooled line, and the caption
names it.
Value
A ggplot object.
See Also
cv_spatial() and compare_models_cv(),
which make the results.
Other cross-validation:
compare_models_cv(),
cv_bayes(),
cv_gwr(),
cv_rf(),
cv_spatial(),
plot_calibration()
Examples
library(sf)
set.seed(1)
n <- 150
dat <- st_as_sf(
data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
a = rnorm(n)),
coords = c("x", "y"), crs = 32632
)
dat$z <- 2 * dat$a + 0.003 * (st_coordinates(dat)[, 1] - 5e5) +
rnorm(n, 0, 0.5)
cv <- cv_rf(dat, "z", "a", k = 5, num_trees = 100)
plot_cv_metrics(cv, "RMSE")
Map a cross-validation fold scheme
Description
Maps the fold each observation belongs to, as a ggplot2 object. Use
it to check that the blocks separate the data, and how wide they are beside
the autocorrelation range when make_folds(auto_range = TRUE) estimated
one. For "block_kfold" folds the block outlines are drawn too, from
folds$params$blocks, so a fold can be seen to be one area or several and
an empty block can be seen to be empty.
Usage
plot_folds(folds, points_sf, boundary = NULL, blocks = TRUE)
Arguments
folds |
A list returned by |
points_sf |
The sf layer the folds were built from. It is drawn in x
and y (spatialkit-geometry), and so are |
boundary |
Optional polygon layer (sf or sfc) to draw underneath. |
blocks |
Logical; draw the block polygons when |
Details
The subtitle states the setting that decides how far the held-out points
sit from their training data, read from folds$params: the size of the
blocks built and the block_size asked for (with the estimated range
when there is one), the buffer, the number of location groups, the median
NNDM exclusion, or, for kNNDM folds, that they are matched to the
prediction distances. Lengths are in the units of the CRS the folds were
built in.
Value
A ggplot object.
See Also
make_folds(), which builds the folds, and fold_separation()
to measure how far the held-out points sit from their training data.
Other folds:
cv_block_size_sweep(),
fold_separation(),
make_folds()
Examples
library(sf)
set.seed(1)
n <- 80
pts <- st_as_sf(
data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000)),
coords = c("x", "y"), crs = 32632
)
f <- make_folds(pts, k = 5, method = "block_kfold", block_size = 300)
plot_folds(f, pts)
Plot a tessellation map with optional boundary, seeds, and features
Description
Builds a layered ggplot2 map of the cells, with optional overlays of a study boundary, seed points and other features. Requires the ggplot2 package.
Usage
plot_tessellation_map(
tessellation_sf,
boundary = NULL,
seeds_sf = NULL,
features_sf = NULL,
fill_col = NULL,
palette = "viridis",
na_fill = "grey90",
tile_alpha = 0.9,
outline_col = "white",
outline_size = 0.2,
features_col = "#333333",
features_size = 0.5,
seeds_col = "#1f77b4",
seeds_size = 1.5,
boundary_col = "#111111",
boundary_size = 0.6,
labels = FALSE,
label_col = NULL,
label_size = 2.7,
legend = TRUE,
legend_title = NULL,
theme = NULL,
target_crs = NULL,
title = NULL,
subtitle = NULL,
caption = NULL,
xlim = NULL,
ylim = NULL,
expand = TRUE
)
Arguments
tessellation_sf |
An sf POLYGON/MULTIPOLYGON layer. Required. |
boundary |
Optional sf/sfc polygon outline layer. |
seeds_sf |
Optional sf/sfc point layer of seed locations. |
features_sf |
Optional sf/sfc layer of additional features. |
fill_col |
Name of the COLUMN in |
palette |
Viridis palette, passed as |
na_fill |
Fill for NA values. Default "grey90". |
tile_alpha |
Alpha for filled polygons. Default 0.9. |
outline_col, outline_size |
Colour and line width of the cell
outlines. Defaults |
features_col, features_size |
Colour and point size of the feature
overlay. Defaults |
seeds_col, seeds_size |
Colour and point size of the seed overlay.
Defaults |
boundary_col, boundary_size |
Colour and line width of the boundary
outline. Defaults |
labels |
Logical; draw per-cell labels. Default FALSE. A cell is labelled when its label is not NA and it has a location; when no cell has both, the labels are skipped with a log line. |
label_col |
Name of the COLUMN holding the label text. Default
|
label_size |
Label text size. Default 2.7. |
legend |
Logical; show fill legend. Default TRUE. |
legend_title |
Optional legend title. |
theme |
A ggplot2 theme. Default |
target_crs |
Optional CRS for plotting. When |
title, subtitle, caption |
Plot annotations. |
xlim, ylim |
Optional numeric vectors of length 2 for coordinate limits (in the plot CRS). Default NULL (auto). |
expand |
Logical; expand plot area slightly beyond data limits. Default TRUE. |
Details
Every layer is drawn in x and y: a layer whose geometries mix XY with XYZ
or XYM (as rbind() of an XY and an XYZ layer gives) is drawn
without its Z and M. The labels are placed in x and y, also on cells
whose geometries carry M (XYM or XYZM).
A row of any layer with a coordinate that is not finite or lies beyond
1e150 has no location: it is left out of the map, with one warning that
says how many rows of which argument were not drawn. A row the plot's
CRS cannot place in full is drawn as the move leaves it (empty, or
without the vertices it cannot place), with a warning of class
spatialkit_rows_unplaced that names it.
Value
A ggplot2 object.
See Also
Other cell building:
build_tessellation(),
clip_target_for(),
create_grid_polygons(),
create_grid_polygons_cached(),
create_voronoi_polygons(),
ensure_stable_poly_id(),
get_voronoi_seeds(),
voronoi_seeds_kmeans(),
voronoi_seeds_random()
Examples
if (requireNamespace("ggplot2", quietly = TRUE)) {
library(sf)
set.seed(1)
n <- 60
pts <- st_as_sf(
data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
z = rnorm(n)),
coords = c("x", "y"), crs = 32632
)
# Cells from the points, the response aggregated onto them, and the map
# shaded by the cell mean rather than by an arbitrary ID. Each cell
# holds one point, so there is nothing to pool: estimate = "mean".
tess <- build_tessellation(pts, method = "voronoi", quiet = TRUE)
asg <- assign_features_to_polygons(pts, tess$cells,
polygon_id_col = "cell_id")
cells <- summarize_by_cell(asg, response_var = "z", id_col = "cell_id",
cells_sf = tess$cells, estimate = "mean")
plot_tessellation_map(cells, features_sf = pts, fill_col = "resp_mean_z",
legend_title = "mean z")
}
Predict a fitted model onto a regular grid
Description
Builds a prediction surface over the extent of the training data (or over a
grid you supply), predicts in chunks, and returns an sf layer.
Usage
predict_surface(
object,
grid = NULL,
cell_size = NULL,
n_cells = 10000L,
boundary = NULL,
covariates = NULL,
chunk_size = 5000L,
se = FALSE,
...
)
Arguments
object |
A |
grid |
Optional |
cell_size |
Grid resolution in CRS units. Ignored when |
n_cells |
Approximate cell count used to derive |
boundary |
Optional polygonal |
covariates |
Optional |
chunk_size |
Rows per prediction call. Default 5000. A
performance setting only: rows do not interact, and for a |
se |
Logical; also return a standard error (or posterior SD) column
where the backend supports it. Default FALSE. For a |
... |
Passed to |
Details
predict_surface() builds the grid, joins the covariates, aligns the
CRSs and calls predict() in chunks of chunk_size rows. Rows
do not interact, so chunking changes memory use and not the predictions.
For a bayesian_fit the draw matrix is n_draws by the number of
rows, which on a fine grid outgrows memory long before the fit does.
Value
An sf POINT layer with a .pred column, and
.pred_se when se = TRUE and the backend gives one. A
.pred_se column that a supplied grid carries from an
earlier surface is removed when this call adds none. For an
auto-generated grid the resolution is attached as attribute
"cell_size". For a user-supplied grid it is only whatever
"cell_size" attribute that object already carried. That is usually
NULL, and NULL for certain if the grid had to be
re-projected, since st_transform() does not preserve custom
attributes.
Coordinate reference systems and geometry
grid, boundary and covariates are brought into the
fit's CRS first. A layer without a CRS is read the way the training data
were (the assumption recorded on the fit), with a warning, and then
reprojected; when that reading is longitude and latitude, a layer with an
x outside -180 to 360 or a y beyond 90 north or south cannot be in it, and
the call stops. Without this a CRS-less grid could land thousands of
kilometres from the covariates, and every cell would take the same nearest
feature. A layer still without a CRS after that is taken as EPSG:4326 and
reprojected when its coordinates look like longitude and latitude, and
otherwise stamped with the fit's CRS, with a warning either way; a fit's
CRS in longitude and latitude is not stamped on coordinates outside
longitude -180 to 360 and latitude -90 to 90, which is refused. See
spatialkit-geometry for these rules in general.
A grid of polygons (create_grid_polygons() output, say) is
reduced to one representative point per cell, as
coerce_to_points() does, so covariates are taken at the
location predicted for; boundary then keeps the cells whose point
falls inside it. All three layers are read in x and y: one whose
geometries mix XY with XYZ or XYM, or carry M (XYM or XYZM), is read
without its Z and M, with no warning for a boundary or covariates. A
POINT grid whose coordinates are not moved (one in
the fit's CRS, or one without a CRS that is stamped with it) is returned
with its rows as given, Z and M included; one that mixes dimensions and is
reprojected into the fit's CRS comes back in XY with a warning of class
"spatialkit_zm_dropped". The points a grid of polygons is reduced
to are in XY when its geometries mix dimensions or carry M.
A grid row without a location (an empty geometry, or a coordinate that is
not finite or lies beyond 1e150) gets an NA prediction; in a grid
that is reprojected, or reduced from polygons, it comes back as an empty
point. A covariate row without a location is never the nearest feature.
Ties between nearest covariate features
A grid point the same distance from several features of
covariates takes one of them by a fixed rule, so a grid laid
between the points of a lattice takes the same covariates in another unit
or with another origin, and with or without the FNN package.
Points. Distances count as equal when the squared distance is no more than the square of the least distance lengthened by a margin, plus one part in ten million of the least squared distance. Among them the point lowest in x is taken, then the one lowest in y, then the first in row order. x values count as one when they lie within one part in ten million of the diagonal of the points' bounding box, or within the margin where that is more; y values are read the same way. A grid point near two points that lie within the margin of each other (two records of one station that differ only in the last bits of their coordinates) takes the same one however near it lies.
Lines and polygons, or a layer that mixes them with points (on the edge two polygons share, say). Distances within one part in ten million of the least, plus the margin, count as the same. Among them the feature whose bounding-box centre is lowest in x is taken, then lowest in y, x values and y values within one part in ten million of the diagonal of the bounding box of
covariatescounting as one, then the first in row order.A layer in degrees. The nearest feature is
sf::st_nearest_feature()'s, which settles a tie in the order its search meets the features (GEOS, or s2 whilesf::sf_use_s2()is on).The margin. It is one part in 1e10 of the largest coordinate of the features that have a location, at most a millionth of the diagonal of their bounding box and at least four times the spacing of doubles at that coordinate. It grows with the largest coordinate: about 0.46 mm at a UTM northing near 4,550 km, about half a micrometre once the origin lies next to data 5 km across. So a grid point whose distances to two features differ by less than the margin with one origin and by more with another takes the one the tie rule picks with the first and the nearer with the second.
See Also
area_of_applicability() to mark where the surface
applies, and spatial_fit-predict for the predictions of each
backend.
Other prediction:
area_of_applicability(),
plot.aoa(),
print.aoa()
Examples
# Any spatial_fit works here; a forest keeps the example free of the
# optional GWR and Stan backends.
library(sf)
set.seed(1)
n <- 120
pts <- st_as_sf(
data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
elev = rnorm(n)),
coords = c("x", "y"), crs = 32632
)
pts$price <- 10 + 0.01 * (st_coordinates(pts)[, 1] - 5e5) +
2 * pts$elev + rnorm(n)
fit <- fit_rf_model(pts, "price", "elev", num_trees = 100, seed = 1)
surf <- predict_surface(fit, n_cells = 500, covariates = pts)
surf[".pred"] # one prediction per grid cell, as an sf layer
# Check where the surface extrapolates before mapping it. The grid took
# its covariates from the nearest observation, so here nothing is
# outside; covariates from another source, such as a raster converted to
# sf points, are where this bites.
area_of_applicability(surf, model = fit)
Prepare an sf layer for model fitting
Description
Reduces the layer to 2-D points in a projected CRS and drops the rows a
model cannot use: rows with a missing or non-finite value in the response
or a predictor, and rows without a location. Every fitter and every
cv_*() function prepares its data here.
Usage
prep_model_data(
data_sf,
response_var,
predictor_vars,
boundary = NULL,
pointize = c("auto", "surface", "point_on_surface", "centroid", "line_midpoint",
"bbox_center"),
require_response = TRUE
)
Arguments
data_sf |
An sf object. Rows without a location are dropped (see Details). |
response_var |
Name of the response column. |
predictor_vars |
Predictor column names. May be |
boundary |
Optional sf/sfc whose CRS the data are projected to. It
is not a clip: rows that fall outside it are kept. Subset
|
pointize |
How non-point geometries become points, passed to
|
require_response |
Logical; if |
Details
Non-POINT geometries (MULTIPOINT included) are reduced to representative
points by coerce_to_points(), so that coordinates line up
one row per observation. Any Z or M coordinate (POINT Z from a GPS, a
GeoPackage or KML) is dropped, because every backend works in 2-D
distance.
A row has no location when its geometry is empty, a coordinate is not finite or lies beyond 1e150, or, in a geographic CRS, a vertex lies at a latitude beyond 90 degrees (see spatialkit-geometry, "Rows without a location"). The 1e150 bound is read on the coordinates as given and again after the projection, because a move between CRSs can bring a coordinate beyond it back finite, and that point is not a place the caller gave.
The CRS is projected whenever one can be established
(ensure_projected()). A layer without a CRS is read by the
lon/lat test of spatialkit-geometry ("Layers without a CRS"):
coordinates the test takes for degrees are read as EPSG:4326 and
projected, with a warning, and others are passed through as they are.
A small planar survey inside the lon/lat envelope is read as degrees, so
set the CRS on data_sf if the data are planar.
The response may not appear in predictor_vars. Using it as its own
predictor is leakage no backend catches (an out-of-bag R^2 near 1 in
the random forest, a silently reduced design matrix in GWR, duplicated
rows and a phantom <none> entry in the GWR selection table), so it
is refused here.
Column names must be syntactically valid R names
(make.names(x) == x). Every backend builds a model formula from
these names, and a name R parses as an expression would fit another model
than the one requested while the fit still recorded the name you asked
for: "B5-B4" is B5 - B4, and "log(a)" is a function
call. Rename the column (for example with make.names()) before
fitting.
The "dropped" record describes the rows this call returned and
does not survive subsetting: clean[i, ], like
dplyr::filter(), slice() or arrange() of it, is a
plain layer with no "dropped" attribute, and a fit given such a
subset with .already_prepped = TRUE reports n_dropped = 0
even when the parent layer dropped rows. sf::st_drop_geometry()
keeps the record, since the rows are the same; see
[.spatialkit_rows for what binding such data frames does.
Value
An sf object with 2-D (XY) POINT geometry, without the rows that
were dropped. The attribute "dropped" records what was removed
and two marks on the rows that were kept, in a list with these fields:
nRows dropped. Every fit stores it as
$info$n_dropped.n_geometryHow many of them were dropped for having no location.
whichTheir positions in
data_sf.row_idTheir
..row_idvalues when the layer carries that column, elseNULL.reasonOne per dropped row:
"geometry","missing"or"non_finite", in that order of precedence when several apply.by_columnFor each modelling column, and for
"(geometry)", how many of the dropped rows it is missing or non-finite in; a row can count under several.response_std_diffThe mean response of the dropped rows minus that of the kept rows, in standard deviations of the response over both;
NAwhen the response is not numeric, is itself missing in every dropped row, or takes one value up to the rounding of its values.n_rowsThe number of rows returned, which the record was made for.
constant_predictorsThe predictors that take one value in every returned row (
character(0)when none does).n_duplicate_locationsThe returned rows whose coordinates repeat those of an earlier row.
Warnings
When preparing data for a fit (require_response = TRUE) three
conditions are raised as R warnings, each with a class so it can be caught
by name with tryCatch() or withCallingHandlers():
spatialkit_rows_droppedRows were dropped. The message gives the number and share of rows, the count by reason and by column, and, for a numeric response, how far the mean response of the dropped rows sits from that of the kept rows. A fit on the rows that remain describes those rows only; when the difference is large the rows are not missing at random and the fit is biased towards the complete ones.
spatialkit_response_impreciseThe response lies so far from zero that doubles there are spaced more than a millionth of its standard deviation apart (a standard deviation of 1 at about 1e10,
2^{33}, or beyond). Its values are rounded to that spacing, and so is every mean and prediction computed at that size: the fit, its scores and any choice made on them read that rounding. The rows are kept; subtract a constant from the response first.spatialkit_constant_predictorA predictor takes a single value in every row that remains. Its coefficient cannot be told from the intercept: a GWR window is rank-deficient, a Bayesian slope is its prior, and a forest ignores it. The predictor is kept; drop it from
predictor_vars.
The fitters and the cv_*() functions pass these warnings on.
compare_models_cv(),
cv_block_size_sweep() and
select_features_forward() run several cross-validations
of one layer, each of which prepares it, and raise
spatialkit_rows_dropped and spatialkit_constant_predictor
once per distinct text for the run and
spatialkit_response_imprecise once per response column;
cv_spatial() raises the last once as well when its
fit_fn prepares each fold's rows again.
With require_response = FALSE (how every predict() method
prepares newdata) none is raised: the dropped rows are written
to the log and to the record, and the prediction for each comes back
NA, so nothing is lost without a trace. Repeated locations are
legitimate (repeat visits to one site) and are counted in the record and
the log, never warned about.
See Also
Other data preparation:
[.spatialkit_rows(),
coerce_to_points(),
ensure_projected(),
harmonize_crs(),
spatialkit-geometry
Examples
library(sf)
dat <- st_as_sf(
data.frame(x = 1:5, y = 5:1,
resp = c(1, 2, NA, 4, 5),
pred = c(1, 2, 3, 4, Inf)),
coords = c("x", "y"), crs = 32632
)
# Drops rows 3 (NA) and 5 (Inf), and warns that it did, with the counts.
clean <- suppressWarnings(prep_model_data(dat, "resp", "pred"))
attr(clean, "dropped")
Print an area-of-applicability result
Description
Prints how many prediction locations fall inside the area of applicability and how many outside, the dissimilarity threshold that separated them, and the predictors the index was computed over (naming any dropped for having no usable variance). It also says where the weights came from (the model's importance, a vector the caller supplied, or equal weights and why), whether location was measured and how, how categorical predictors were handled, and how many training rows repeat another's predictor values. With a location index the rows outside are split into those outside on the predictors and those outside on location. The share of locations outside is the number to report: a map that extrapolates over much of its extent rests on predictions the training data cannot support.
Usage
## S3 method for class 'aoa'
print(x, ...)
Arguments
x |
An |
... |
Not used. |
Value
x, invisibly.
See Also
area_of_applicability(), which makes the object,
and plot.aoa().
Other prediction:
area_of_applicability(),
plot.aoa(),
predict_surface()
Examples
library(sf)
set.seed(1)
train <- 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
)
# 15 new points take values of a seen in training; five lie far above
# its range, and print() counts those five outside.
newpts <- st_as_sf(
data.frame(x = 5e5 + runif(20, 0, 1000), y = 5e6 + runif(20, 0, 1000),
a = c(train$a[1:15], rnorm(5, 8))),
coords = c("x", "y"), crs = 32632
)
res <- area_of_applicability(newpts, train_sf = train, predictor_vars = "a")
print(res)
Print a residual Moran's I result
Description
Prints the statistic, the null its moments come from and the evidence behind them. The weight matrix the result carries is described in one line instead of printed.
Usage
## S3 method for class 'morans_i'
print(x, ...)
Arguments
x |
An object of class |
... |
Not used. |
Value
x, invisibly.
See Also
residual_morans_i(), which makes the object.
Other in-sample checks:
compare_models(),
evaluate_insample(),
model_metrics(),
residual_morans_i()
Examples
library(sf)
set.seed(1)
dat <- st_as_sf(
data.frame(x = 5e5 + runif(80, 0, 1000), y = 5e6 + runif(80, 0, 1000),
elev = rnorm(80)),
coords = c("x", "y"), crs = 32632
)
dat$price <- 10 + 2 * dat$elev + rnorm(80)
fit <- fit_rf_model(dat, "price", "elev", num_trees = 100, seed = 1)
print(residual_morans_i(fit))
Print a fitted model
Description
Prints the backend, the formula, the number of observations and the CRS, then lines for the backend:
a random forest (
rf_fit): the number of trees,mtry, the node size, whether the coordinates were used as predictors, how each tree's rows were sampled, the out-of-bag error and the largest importances. A forest fitted without them prints "no spatial information used": it sees the covariates alone. One fitted withinclude_coords = TRUEprints a note on how to score it (see "Coordinates as predictors" and "Out-of-bag error" infit_rf_model()). When a predictor is an unordered factor or a character column, a line says how ranger was told to split it;a GWR (
gwr_fit): the bandwidth (a count of neighbours, or a distance with the CRS's unit), the kernel, the AICc, the effective number of parameters and, when any local window is of deficient rank, the number of such windows;a Bayesian GP (
bayesian_fit): the GP basis size, the smallest effective range the basis resolves in CRS units, the LOOIC when the fit computed it (compute_loo = TRUE, the default offit_bayesian_spatial_model()), the slope prior, the standardised predictors, and a flagged line when the sampler's diagnostics or the basis check failed.
A custom subclass prints the common lines only. Typing the object's name
calls this method; use it to confirm that a fit used the data, predictors
and CRS you meant. For fit quality use model_metrics() or
summary.spatial_fit(). Apart from a forest's out-of-bag
error and a Bayesian GP's LOOIC, an approximate leave-one-out score of
single rows, nothing printed here is an out-of-sample score, and neither
of those is a spatial one.
Usage
## S3 method for class 'spatial_fit'
print(x, ...)
## S3 method for class 'rf_fit'
print(x, ...)
Arguments
x |
A |
... |
Not used. |
Value
x, invisibly.
See Also
fit_rf_model(), fit_gwr_model() and
fit_bayesian_spatial_model(), which make the objects.
Other fit methods:
plot.spatial_fit(),
spatial_fit-coef,
spatial_fit-fitted,
spatial_fit-predict,
spatial_fit-residuals,
summary.spatial_fit()
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)
fit <- fit_rf_model(pts, "z", "a", num_trees = 50, seed = 1)
fit # print.rf_fit()
if (requireNamespace("sp", quietly = TRUE))
print(fit_gwr_model(pts, "z", "a", bandwidth = 30)) # print.spatial_fit()
Test the residuals of a fitted model for spatial autocorrelation
Description
Takes the residuals and the observation coordinates of a
spatial_fit, builds a spatial weight matrix, and computes Moran's I
with its expectation and variance under a stated null. A z-score and a
p-value say whether spatial autocorrelation remains after fitting. The
default weights are the row-standardised k-nearest-neighbour matrix
described under weights.
Usage
residual_morans_i(
fit,
alternative = c("two.sided", "greater", "less"),
weights = NULL,
k = 8L,
null = c("auto", "randomisation", "residual"),
keep_weights = FALSE
)
Arguments
fit |
A |
alternative |
Character: |
weights |
Optional user-supplied n x n weight matrix: a base
matrix or a Matrix-package matrix (e.g. a sparse dgCMatrix).
When |
k |
Integer number of nearest neighbours used when building the
default weight matrix (ignored when |
null |
Which null distribution the expectation, variance and p-value are computed against. One of:
Both |
keep_weights |
Logical. Return the |
Value
A list with components:
- observed
Numeric scalar, Moran's I statistic.
- expected
Expected I under the null named by
null:-1/(n-1)for"randomisation",(n/S_0)\mathrm{tr}(MW)/(n-p)for"residual".- sd
Standard deviation of I under that same null.
- z
Standardised z-score,
(I - E[I]) / sd(I).- p_value
Two-sided (or one-sided) p-value from the normal approximation.
- n
Number of observations used.
- null
The null actually used,
"randomisation"or"residual". Check it, since"auto"chooses per fit and"residual"can fall back.- df
Residual degrees of freedom behind the moments:
n - pfor"residual"(wherepis the rank of the design matrix),n - 1for"randomisation".- weights
The
n \times nweight matrix the statistic was computed with, either the row-standardised k-nearest-neighbour matrix built here (sparse when Matrix is installed) or the suppliedweightsafter the diagonal was zeroed. It isNULLunlesskeep_weights = TRUE.- kurtosis
The residual kurtosis
m_4 / m_2^2, which the randomisation variance conditions on and which says how far the residuals sit from the Gaussian case the residual moments assume (3 for a normal sample).- p
The rank of the rebuilt design matrix behind the
"residual"moments;NAunder"randomisation".- exact
Logical:
TRUEwhen the moments are exact for these residuals (the residual null on OLS residuals of the response on the rebuilt design),FALSEwhen they are an approximation (the residual null forced onto a non-OLS backend, or the randomisation null, whose exchangeable moments model residuals do not satisfy).- weights_summary
What the weight matrix was, present whether or not the matrix itself was kept:
n,storage(its class),neighbours(the smallest and largest number of neighbours any row has, andNAfor a dense matrix, where counting them would allocate a second one),kept(whetherweightsholds the matrix) anddesc, the one lineprint()shows.
The list is classed "morans_i" and has a print() method,
so the console shows the statistic and its null without printing the
n \times n weights matrix; [ drops the class, and
$, [[ and unlist() are unaffected.
A custom fit whose class has no residuals() method (which
new_spatial_fit calls optional) is scored on the
observed response minus fitted(), as plot() does for it.
Returns NULL with a warning if computation fails, saying why:
residuals() raised an error (its message is quoted), or returned
NULL and the response minus fitted() could not be
formed either (the reason is quoted), fewer than 4 valid
residuals, a residual vector whose length does not match the fit's
data_sf, weights that sum to less than
.Machine$double.eps, or residuals that leave I a ratio of
rounding: they do not vary, or vary by no more than the rounding of the
response (a standard deviation of 3 units in the last place of its
largest value, or a root mean square of 10\epsilon times that of
the response about its centre), or are the OLS residuals of an exact fit
of the response on the predictors (a root mean square of
10\epsilon times that of the fit's terms).
The test reads the residuals against the response, so residuals in
any unit are scored or refused alike, and I, z and the p-value do not
depend on the unit.
Which null, and when it is approximate
Two nulls are available, and the one used is reported in the null
element of the return value.
"randomisation" is the classical exchangeable null:
E[I] = -1/(n-1) with the Cliff and Ord randomisation variance,
conditioning on the observed kurtosis. These are the moments of I for a
vector whose elements are equally likely in any order.
Model residuals are not exchangeable. They are orthogonal to the design
matrix, which pushes E[I] below -1/(n-1) whenever the
covariates are spatially smooth, and further the more covariates there
are. Under the exchangeable null the z-score of OLS residuals is then
shifted below 0, and the test loses power.
"residual" therefore uses the Cliff and Ord (1981, section 8.3)
moments for regression residuals, with M = I - X(X'X)^{-1}X' rebuilt
from predictor_vars and data_sf:
E[I] = (n/S_0)\,\mathrm{tr}(MW)/(n-p)
Var[I] = (n/S_0)^2[\mathrm{tr}(MWMW') + \mathrm{tr}((MW)^2) +
(\mathrm{tr}MW)^2]/[(n-p)(n-p+2)] - E[I]^2
These assume normal errors and do not condition on the observed
kurtosis. They agree with spdep::lm.morantest() to machine
precision.
The residual moments are exact for e = My and for nothing else, so
null = "auto" does not guess from the fit's class: it rebuilds
X, regresses the response on it, and uses the residual moments only
when the supplied residuals are those OLS residuals to numerical
tolerance. A GWR wide enough to have collapsed to global OLS passes that
test; the same GWR at a working bandwidth does not. The response, and
each predictor whose centre is more than 1000 times its spread, are taken
about their centres before the regression, which leaves its residuals as
they are, so a timestamp or a response at 1e10 gives the null, moments and
rank p of the same columns at 0. The supplied residuals pass where
none differs from the OLS residuals by more than 1e-7 of the response's
standard deviation, or where the differences are no more than the
rounding a regression of the raw columns leaves: a root mean square of
10\epsilon (\epsilon = .Machine$double.eps) times
that of the fit's terms, among them the offset the fit regressed the
response at (for a GWR that took the response about its centre, the
offset left after that centre). They also
pass where none differs by more than 1e-7 of the response's standard
deviation from the residuals lm() gives on the raw columns, where
the raw design keeps the rank of the centred one: that rounding grows
with the number of rows.
For the flexible backends neither null is exact, and "auto" leaves
them on "randomisation": forcing the OLS moments on them does not
correct them, and for a forest it raises the false-positive rate. A
random forest's residuals here are the out-of-bag ones
(spatial_fit-residuals). The random forest is anticonservative
under both: its residuals are not a linear projection of the response and
they are spatially heteroscedastic, so neither set of moments describes
their null distribution and the variance is understated whichever is
used. GWR is conservative under both, because it removes far more
structure than a rank-p projection does. Treat the p-value from
those backends as a rough indicator, and prefer spatially blocked
cross-validated residuals or an explicit spatial covariance model when the
answer has to carry weight.
A permutation null does not help: permuting the residual vector destroys
the orthogonality that causes the bias, so its mean is the exchangeable
-1/(n-1) by construction and it reproduces the randomisation null.
Reading a large I
A large positive I with a small p-value means the residuals keep spatial
structure the model did not capture (for a forest, read the p-value as
rough; see above): a covariate it lacks, or a scale it cannot represent.
Add the missing covariate if there is one, compare a backend
that models space (fit_gwr_model() or
fit_bayesian_spatial_model()), and score the model with
blocked folds (cv_spatial()). A z near 0 with a large p-value
means the test found no structure left.
References
Cliff, A. D. and Ord, J. K. (1981) Spatial Processes: Models and Applications. Pion, London. Section 8.3.
See Also
compare_models(), which adds the statistic to a
comparison of fits.
Other in-sample checks:
compare_models(),
evaluate_insample(),
model_metrics(),
print.morans_i()
Examples
# Works on any spatial_fit; a forest keeps the example free of the
# optional GWR and Stan backends.
library(sf)
set.seed(1)
n <- 120
dat <- st_as_sf(
data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
elev = rnorm(n)),
coords = c("x", "y"), crs = 32632
)
# An east-west trend the predictor cannot explain.
dat$price <- 10 + 0.02 * (st_coordinates(dat)[, 1] - 5e5) +
2 * dat$elev + rnorm(n)
fit <- fit_rf_model(dat, "price", "elev", num_trees = 100, seed = 1)
# A large positive I and z: the residuals carry the east-west trend the
# forest could not see. A z near 0 with a large p-value would mean no
# structure was left.
residual_morans_i(fit)
Score candidate cell counts on several criteria
Description
Scores candidate numbers of cells (levels) for a layer of points, so that
the count chosen, by select_resolution() or by eye, can be
defended with the whole profile in place of one criterion's optimum.
Usage
resolution_profile(
data_sf,
response_var = NULL,
predictor_vars = NULL,
levels = NULL,
n_levels = 20L,
min_cell_n = 9L,
sample_n = 1500L,
nstart = NULL,
seed = 123L,
sac = "auto",
select_on = c("all", "split"),
range_floor = FALSE,
partition = c("density", "kmeans"),
init = c("kmeans++", "random"),
density_power = 1,
density_k = 8L,
iter_max = NULL,
estimate = "auto",
obs_per_cell = "auto"
)
## S3 method for class 'resolution_profile'
print(x, digits = 3L, ...)
Arguments
data_sf |
An sf object of points (other geometries are reduced to
representative points with |
response_var |
Name of the response column (numeric or logical), or
|
predictor_vars |
Optional predictor column names (numeric or
logical). With them, |
levels |
Optional integer vector of level counts to score, replacing
the ladder; values below 2, above the number of distinct locations, or
at or above the number of points, are dropped (k-means cannot place more
centres than there are distinct points, and |
n_levels |
Number of levels on the ladder. Default 20. The ladder
has fewer when rounding puts two of them on one count, and one more
when the range floor is added as a level (see "The ladder and its
bounds"). Supplying it, or |
min_cell_n |
Minimum average number of rows per cell that a level
must keep (scored rows when |
sample_n |
Points are subsampled to this many before the k-means
fits, as in |
nstart |
Starts per level; the best is kept. They are k-means++
starts unless |
seed |
RNG seed for the subsample and the restarts; restored
afterwards. Default 123. The rows are put in coordinate order before
either, so the profile does not depend on the order they come in. Each
level's restarts run on a stream of their own, seeded from |
sac |
Optional |
select_on |
|
range_floor |
|
partition |
What the centres of the cells minimise, at every level
of the ladder. |
init |
How each start is drawn. |
density_power |
For |
density_k |
For |
iter_max |
The most iterations a start runs for: a single positive
whole number, or |
estimate |
The cell value the profile scores, which is the one
|
obs_per_cell |
Rows per cell: |
x |
A |
digits |
For |
... |
Ignored. |
Details
Called with a numeric response, no predictors and none of
levels, n_levels, min_cell_n, sample_n or
range_floor, the profile is one level: the count that gives 4.5
rows per cell (obs_per_cell = "auto"), scored for pooled values
(estimate = "auto") by the leave-one-out error loo, with
no variogram fitted (sac = "auto"), in cells of the density kind
(partition = "density") kept from 3 k-means++ starts
(nstart = NULL). cp and reliability need the
variogram and elbow needs a curve, so the three are NA
there; moran_z is computed. select_resolution()
reads the count off it by the size.
Any of those five ladder arguments, obs_per_cell = NULL, or a
call with no estimate (no response, predictor_vars, or a logical
or wholly missing response) gives a ladder of counts (see "The ladder
and its bounds"). At every level the profile then scores the
within-cluster sum of squares of the coordinates and its elbow, Mallows'
C_p of the piecewise-constant approximation of the response by
cell means, Moran's z of the cell means and their reliability, and,
with an estimate, the leave-one-out error of the cell value. Mallows
(1973) presents C_p itself as a display of the bias-variance
trade-off across candidates, and the profile is that display, with the
other criteria alongside.
print() gives a header that states the ladder and its bounds, the
variogram (or why none was fitted), what was scored and on how many
starts, what one cell for the whole layer scores, the estimate, whether
the WSS curve has an elbow and, under select_on = "split", the
rows of each half; then the table, one row per level, at digits
significant digits.
Value
A data.frame of class resolution_profile, one row per
level. Columns a missing input leaves undefined are NA.
levelsThe number of cells.
wssThe within-cell sum of squares of the coordinates, every point counted once, under either
partition.wss_spreadThe relative spread of WSS across the restarts; under
partition = "density", of the weighted sum the starts minimise.elbowThe sag of the WSS curve below a power law (see "The criteria").
cell_n_min,cell_n_medianThe fewest and the median points per cell.
cell_diam_medianTwice the median RMS radius of the cells, in coordinate units: about 0.8 of the side of a square cell of the same area, and less for finer cells, so a size to compare levels by rather than a width.
rss,cpThe residual sum of squares of the scored rows about their cell means, and Mallows'
C_p.moran_i,moran_zMoran's I of the cell means and its standardised deviate.
reliabilityThe between-cell signal's share of the spread in the cell means.
cells_respThe cells that hold at least one scored row.
cell_resp_meanThe scored rows per such cell; compare it with
min_cell_n.
Like the other columns read off the fitted cells, cells_resp
and cell_resp_mean count rows of the subsample when the layer is
larger than sample_n: the cells of the layer then hold about
n_response / n_scored times as many scored rows as
cell_resp_mean shows (under select_on = "split",
split$n_response / n_scored: both count the rows of the
selection half).
With an estimate the frame has five more columns, after
cell_resp_mean:
scored_per_cellThe rows
looread over the cells that hold one; the layer's counterpart ofcell_resp_mean, which counts the subsample's rows.looThe leave-one-out mean squared error of the estimate; lower is better.
loo_seThe standard error over rows of that level's mean squared error. It is not the standard error of a difference between two levels, whose errors come from the same rows.
share_aloneThe share of the scored rows that are the only scored row of their cell.
own_weightThe median over cells of the weight a pooled value gives the cell's own mean;
NAunder"mean".
loo, loo_se and own_weight are NA at a level
where no cell holds two scored rows, at every level when the response
is constant over the rows loo reads, and at every level when
those rows' values lie beyond what the arithmetic of the estimate holds
(spatialkit_pool_unavailable). All five are NA at every
level when no row of the selection half has a response
(select_on = "split"; spatialkit_no_scored_rows).
Attributes:
boundsA list:
floor,ceiling,ceiling_from("min_cell_n","min_cell_n (rows with a response)","distinct locations","sample_n","fewer than two supported cells"or"fewer than two distinct locations", whichever bound it),supported,area,range,n(the points in the layer),n_sample(the points the k-means fits ran on),n_distinct,min_cell_n,range_floor(the argument),n_response(the rows of the layer that carry a response and, withpredictor_vars, every predictor, which the support ceiling counts;NAwithout aresponse_var),n_scored(the rows of the subsample the response criteria read;NAwithout aresponse_var),levels_given(whetherlevelsset the ladder),predictors(whetherpredictor_varswere given) and, where rows have a response and none of them every predictor,n_response_only(the rows with a finite response), and, where the range floor lies above the ceiling,floor_applied(FALSE: the floor is above every level and is not applied, whateverrange_flooris). On a ladder thatobs_per_cellsets,boundsdescribes that ladder:ceilingis the finest level;ceiling_fromis"obs_per_cell","distinct locations","fewer than two cells of the size"or"fewer than two distinct locations";supportedisFALSEwhen the finest size gives fewer than two cells or the range floor is above the finest level;levels_givenisTRUE;n_sampleis every point;min_cell_nholds the argument, which is not read; and two fields are added,obs_per_cell(the sizes, largest first) andsize_levels(the level of each, named by size;NAfor a size of"auto"that gives fewer than two cells and was left out).variogramA list with
nugget,psill,range(NAwhen rejected),modelanddetrended(whether the sac says it is a variogram of residuals;NAwhen it does not say);NULLwhen none was usable.variable"response","residuals"orNA.wss_bumps,nstartThe number of rising steps on the WSS curve, and the starts run per level.
sacThe range object used.
splitWith
select_on = "split": aspatialkit_splitwithselectionandestimation(integer row positions indata_sf), themethodandseedthat made them, and with a responsen_response, the rows of the selection half with a finite response and every predictor, counted on the layer before any subsample.cp_noiseA list with
source("variogram nugget","finest-level residual mean square"or"short-lag semivariance"),value(the\tau^2used) andlevel(the level it was read at, orNA). Under the short-lag semivariance it also hascap, that semivariance, anduncapped, a list of thesource,valueandlevelit held. When the finest level whose cells hold two scored rows on average has a residual mean square of 0 to within rounding,sourceandvalueareNA, and the list haslevel(that level),rows_per_cell(its scored rows a cell),rms(its residual mean square: 0, or the rounding it was read as) andreason, whichselect_resolution()gives. On a ladder of sizes undersac = "auto"it is a list whosesourceis"none"and whosereasonsays why.NULLwhencphas no noise variance for another reason; seecpunder "The criteria".one_cellWhat one cell for the whole layer scores, the reference a level has to beat: a list with
n(the scored rows),rss(their total sum of squares),cp(the same formula at one cell, orNAwhencphas no noise variance),constant(whether the scored variable is constant to within rounding),cp_levels(thecpcolumn it belongs to) andf_p(named by level, the p-value of the F test of that level's cell means against one mean,(TSS - RSS) / (L - 1)overRSS / (m - L)on theLcells that hold a scored row and themscored rows).NULLwithout a response.centres,centres_crs,hullA list named by level of the two-column matrices of the scored partitions' centres, the CRS they are in, and the convex hull of the points profiled (an
sfcin that CRS). A k-means partition is the Voronoi partition of its centres, so these seed the cells each level was scored on:select_resolution()returns the chosen level's as$seeds, andget_voronoi_seeds()andvoronoi_seeds_kmeans()use them when given the selection or the profile. The centres carry the hull as their"cover"attribute, which those two functions hand on so that Voronoi cells built on the seeds reach the edge of the points.refit_rowsWhen the centres were fitted to a subsample and the profile has no estimate: a list with
xy, the coordinates of every point in the CRS of the centres, anditer_max, the iteration limit of the fits, from whichselect_resolution()refits the level it chooses to every point. The seeds are then the chosen level's centres refitted to every point, whose cells are not the cells scored (seeselect_resolution, "Value").partitionOn a profile built with
partition = "density"orinit = "random": a list withkind,init,density_poweranddensity_k(bothNAforkind = "kmeans"); forkind = "density",objective, the weighted sum the centres minimise, named by level;iter_max, the iteration limit; anditerandconverged, the iterations each level's kept start took and whether it stopped before the limit, named by level. The selection carries the first four as$partition, its seeds and the seeds the seeding functions return asattr(, "partition"), and a Voronoi tessellation built on them asparams$partition. A profile of the kind"kmeans"from k-means++ starts has no such attribute, and neither has anything made from it.estimateWith an
estimate: a list withvalue("mean"or"pooled"),neighbours(8, orNAunder"mean"),response(the column),n(the rowslooread),rows("all"or"selection half"),features("points", or"other"when the layer held features that were reduced to points),seed,constant,loo_one_cellandloo_one_cell_se(the same error with one mean for all those rows, the reference a level has to beat;NAfor a constant response, for fewer than two rows and for values beyond the arithmetic of the estimate),loo_levels(theloocolumn those references belong to, named by level), and, named by level,sigma2(the spread of the rows about their cell's mean),tau2(the mean squared distance between a cell's level and its target;NAunder"mean"),cells(the cells that hold a scored row) andf_p(the p-value of the F test of those cells' means against one mean).constantsays whether the response is constant over those rows by the estimate's test, which reads the raw values and the values centred on their median and scaled, so that 1e15 plus a spread of 1 is not constant while values that differ only by their rounding, 0.1 beside 0.3 / 3, are; it isFALSEfor fewer than two rows.one_cell$constant, the test forcp, reads the scored rows of the subsample the same way, and residuals against the rounding of the regression and of the response.
The partition
The cells at every level are the Voronoi cells of a set of centres: a
point belongs to the centre nearest to it. partition says what the
centres minimise, and every level of the ladder is built with the same
kind.
"kmeans"The sum, over the points, of the squared distance to the nearest centre. The centres follow the square root of the point density. The cells are compact, smaller where the points are dense and larger where they are sparse, and a cell in a dense place holds several times the points of a cell in a sparse place.
"density"(default)The same sum with each point weighted by its local density to the power
density_power. The local density at a point is the number of points in the disc that reaches itsdensity_k-th nearest neighbour, over the area of that disc. Withdensity_power = 1the centres follow the point density itself. The cells are compact: many small ones where the points are dense, a few large ones where they are sparse. They hold about the same number of points each once there are more cells than dense places (clusters of points). With fewer cells than dense places a cell takes in whole clusters, large and small, and the counts are about as uneven as under"kmeans".density_power = 0weights every point alike, which is the objective of"kmeans"; a power above 1 goes past equal counts and gives the cells of dense places fewer points than those of sparse places.
A ladder starts at 2 cells, so its low levels are usually below the
number of dense places, and the columns cell_n_min and
cell_n_median show where the two kinds part.
The density kind is the default. The default size, 4.5 rows per cell,
puts the count above the number of dense places on a layer whose
clusters hold more than a few observations each, so the default kind and
the default count go together. A coarse ladder the caller sets (with
levels, large sizes, or the low levels of the automatic ladder)
may not, and at those levels the density kind does not even the counts.
partition = "kmeans" gives plain k-means cells, from 25 k-means++
starts unless nstart says otherwise.
init says how each of the nstart starts is drawn before it
is refined; the best start is kept. "kmeans++" draws the centres
one at a time, each a point taken in proportion to its squared distance
from the centres already drawn (times its weight, under
"density"), which spreads the start over the points.
"random" draws k distinct locations at random, as
kmeans() does.
A start of the kind "kmeans" is refined by
kmeans() (Hartigan and Wong), for at most 50
iterations from a k-means++ start and 100 from a random one. A start of
the kind "density" is refined by Lloyd's iteration, for at most 100
steps: each point goes to its nearest centre, each centre moves to the
weighted mean of its points, and a centre left without a point stays
where it is. iter_max sets another limit. The start with the
lowest sum is kept (under the density kind a later start replaces an
earlier one only when its sum is lower by more than one part in ten
million, so of starts whose sums agree to rounding the first is kept), and
a kept start that was cut off at the limit is reported (see
"Conditions"): its centres are those of the last step. A large layer can
need more steps than the default limit.
The density kind depends on the points alone. It works on the distinct
locations in coordinate order (see below for first coordinates equal but
for their last bits), so the order of the rows does not matter. Its
tolerances do not depend on the unit of the coordinates: the neighbour
distance is not taken below a millionth of the extent of the points (the
diagonal of their bounding box), the iteration stops when no centre moves
by 10^{-12} of it, and the tie rules below are fractions of the
extent or of the quantities they compare. On gridded locations many
points are equally near two neighbours or two centres, and the last bits
of the coordinates, which move with the unit and the origin, would settle
those ties. So squared distances within one part in ten million of each
other count as equal, a tie between neighbours goes to the lower first
coordinate and then the lower second, a tie between centres goes to the
lower-numbered one (between centres a squared distance ties with the least
when it is no more than the square of the least distance lengthened by a
margin, plus one part in ten million of the least squared distance; the
margin is one part in 1e10 of the largest coordinate of the centres, at
most a millionth of the diagonal of their bounding box and at least four
times the spacing of doubles at that coordinate), first coordinates
within that part of the extent count as equal when the rows and the
locations are put in order, and so do weights within that part of each
other when the first k-means++ centre is drawn. The cells are then the
same in another unit or with another origin as long as no coordinate
moves by more than about a two-hundred-millionth of the distance between
neighbouring locations, but for one case: the margin of the centres grows
with their largest coordinate (about 0.46 mm at a UTM northing near
4,550 km, about half a micrometre once the origin lies next to data 5 km
across), and the rows are given to the centres in the layer's own
coordinates, so a row whose distances to two centres differ by less than
the margin with one origin and by more with another goes to the
lower-numbered centre with the first and to the nearer with the second.
The rounding PROJ leaves when it changes the unit or the false origin,
about 10^{-9} m, is below that for locations more than about a
quarter of a metre apart. Coordinates rounded more coarsely can give
other cells: a lattice at 250 m with its coordinates stored in feet to
four decimals does. Points at one location count as that many points at
it and share a cell; the neighbour distance is measured to the
density_k-th nearest other location, so it is not zero
where locations repeat. The neighbour searches use FNN when it is
installed. The result is the same without it; the search then takes
time that grows with the square of the number of points.
The kind "kmeans" meets the same ties inside
kmeans(), which settles them by the last bits of the
coordinates and takes no tolerance. So it is handed the coordinates
centred on the middle of their bounding box, divided by its diagonal and
rounded to 2^{-30} of it (about a billionth); the starts are drawn
from those coordinates and ranked by their sums, and the cells it returns
are read back in the layer's own coordinates, so the centres, wss
and every column are in its unit. The rows are put in order as for the
density kind. The cells are then the same in another unit or with
another origin unless the change moves a coordinate across the middle of
a rounding step, which the rounding PROJ leaves (about 10^{-9} m)
does more often the smaller the extent. Distinct locations that would
round to one point keep their coordinates unrounded, so they stay
distinct. stats::kmeans() also settles such ties by the last bits
of its own compiled arithmetic, which differ between platforms, so on a
layer where ties decide cells the kind "kmeans" can return other
cells on another platform from the same coordinates and seed, and
with them every column read off the cells.
The columns keep their meaning under "density", because each is
read off the cells and not off the way they were drawn. wss is the
within-cell sum of squares of the coordinates with every point counted
once, taken about each cell's mean, so wss and elbow
compare between kinds; the weighted sum the centres minimise is kept in
attr(, "partition")$objective, and wss_spread is its spread
over the starts. cp, moran_z and the test against one cell
need cells drawn without the response, which both kinds give.
reliability is computed for square cells of the level's average
area and count and never reads the cells, so it is the same number under
either kind. The elbow is found more readily under
"density" where the points cluster: once each cluster has its
centres, further centres go into the clusters, the sparse ground between
them keeps its sum of squares, and the curve flattens.
A profile of the density kind, or of either kind from random starts,
carries attr(, "partition"), and
select_resolution(), the seeding functions and
build_tessellation() hand that record on with the cells
(see "Value"). A result with no such record was built by plain k-means:
from k-means++ starts when it comes from a profile, and from random
starts when a seeding function fitted it.
The ladder and its bounds
This is the ladder of a call that sets levels, n_levels,
min_cell_n, sample_n or range_floor, or passes
obs_per_cell = NULL, and of a call with no estimate: one without
a response, with predictor_vars, or with a logical or wholly
missing response. Cells are clusters of the (projected)
coordinates of the kind partition names, fitted at each level as
the best of nstart k-means++ starts (see
determine_optimal_levels for why) unless init says
otherwise (see "The partition"). Levels are spaced
logarithmically, because cell diameter scales as L^{-1/2}: a unit
step wastes fits at large L and starves resolution at small. The
ladder runs from 2 to a ceiling the data impose. The ceiling is
floor(n / min_cell_n): cells with fewer than min_cell_n
rows on average have too little support. With a response_var,
n is the number of rows of the layer (not of the subsample) that
are scored: those with a response and, with predictor_vars, every
predictor, since the cell means the criteria read are built from those
rows alone. ceiling_from is then "min_cell_n (rows with a
response)" when some rows are not scored (the label is the same when it
is a predictor they lack), and a warning of class
spatialkit_response_ceiling gives both counts and names the bound
in force. Without a
response_var, or when no row has a response, n is every
point. The ceiling is also held to the number of distinct locations, one
cell on each, and to one short of the number of points, which
stats::kmeans() needs. The count n / L is the rows per cell
only when the scored rows are spread over the whole extent.
Where they sit in one part of it, the cells elsewhere hold none and the
occupied cells hold more than n / L, so the ceiling is lower than
those cells need: cells_resp and cell_resp_mean give the
cells that hold a scored row and the scored rows per such cell at each
level (of the subsample, when the cells are fitted to one), and
profiling the scored rows alone bounds the ladder by the area they
cover.
When fewer than two cells meet min_cell_n
(floor(n / min_cell_n) < 2), or the layer has one distinct
location, there is no ladder: the profile scores two cells so that level
is still visible (or the levels asked for, as given),
supported is FALSE, ceiling_from
is "fewer than two supported cells" (or "fewer than two
distinct locations") and a warning of class
spatialkit_not_supported names both numbers.
min_cell_n sets the ceiling of this ladder. It is a mean number
of rows per cell and not a minimum: a cell of a level at the ceiling can
hold fewer (cell_n_min). It is floored to a whole number, so 4.5
is read as 4. With levels it does not choose the levels scored,
and it still sets bounds$ceiling, supported and the
spatialkit_not_supported warning.
The range floor is ceiling(area / range^2) when an autocorrelation
range is available: cells wider than the range average over more than one
patch of the field. It is reported in the bounds and the print, and by
default it is not applied: the ladder starts at 2. When the layer
supports the floor and it lies between the ladder's ends, the floor is
one of the ladder's levels all the same (so the ladder can have one more
level than n_levels): select_resolution(criterion =
"reliability") reads from the floor up and returns the floor itself, not
the next level the spacing happened to put above it. The range is an
estimate, and a response with no spatial structure can still be given
one, so a ladder started at the floor can leave out the coarse counts
such a response supports. range_floor = TRUE starts the ladder
at the floor when the layer supports it and it lies below the ceiling.
When
the floor exceeds the ceiling the data cannot support a tessellation
that respects their own correlation structure; that is reported as a
finding (a warning of class spatialkit_not_supported, and
attr(x, "bounds")$supported is FALSE) and the ladder runs
from 2 to the ceiling (or the levels asked for are scored, as
given), so the profile still shows what each level costs.
A floor equal to the ceiling would leave one level and nothing to compare
it with, so that ladder starts at 2 as well. On a layer larger than
sample_n the ceiling is also held to half the subsample's scored
rows (two per cell, the least a fitted cell can be scored on; half the
subsample without a response); ceiling_from is then
"sample_n", a floor above that raises a warning of class
spatialkit_floor_above_ceiling with a request to raise
sample_n, and it does not make supported FALSE.
The floor moves with the range estimate, and the ceiling with n.
To compare profiles of similar data (the folds of a cross-validation,
say), pass the same levels to each. reliability is the one
criterion that still reads the floor: select_resolution()
holds it to the levels at or above the floor by default, so its pick can
differ widely between two such profiles when the floor is supported on
one and not on the other; pass range_floor = FALSE
there to read the whole ladder.
A ladder that obs_per_cell sets is a ladder of sizes (see
"Observations per cell"). It has one level per size s,
max(2, round(n / s)) cells, held to the most centres k-means can
place: the distinct locations, and one short of the points. Its centres
are fitted to every row. No subsample is drawn, and n_levels,
min_cell_n, sample_n and range_floor are not read.
The finest size takes the part min_cell_n has on the ladder above:
bounds$ceiling is the finest level, and supported is
FALSE when the finest size gives fewer than two cells or the range
floor is above the finest level. The range floor is reported and not
applied.
A ladder of sizes under sac = "auto" fits no variogram, so
cp and reliability are NA at every level there, and
attr(, "cp_noise") says why. sac = NULL, or a sac of
the caller's own, gives them. sac = "auto" and
obs_per_cell = "auto" are the defaults, so the default profile
has neither column.
Observations per cell
obs_per_cell sets the ladder by a size: the mean number of rows a
cell is to hold. The level of a size s is
max(2, round(n / s)) cells, with n the rows the size
divides (see the argument). A size says how many observations a cell
value is to stand on, and that is the caller's choice: no criterion makes
it. Under a size neither the cells, which are fitted to the coordinates,
nor their number, which is a count of rows, depend on the values of the
response. Under select_resolution(criterion = "loo") the count
does.
For pooled values the leave-one-out error tends to keep falling as the
cells shrink, so its minimum tends to be the finest size offered, and the
end of the ladder would then choose the count (see "How this was
checked"). select_resolution(criterion = "size") therefore sets
the count of pooled values from a size, 4.5 unless another is given, and
criterion = "loo" reads the lowest error for plain means.
Two columns say what a size leaves a cell value to stand on.
share_alone is the share of the scored rows that are the only
scored row of their cell: the plain mean of such a cell is one
observation, and its pooled value has the smallest own weight a cell can
have. own_weight is the median weight a pooled value gives the
cell's own mean: at 1 the pooled values are the plain means, and at 0
each is the mean of the cell's neighbours.
obs_per_cell = "auto", the default, is resolved against the other
ladder arguments, in this order. Whether the caller supplied an argument
is what counts, so a value a wrapper passes on counts as supplied.
With
levels,"auto"isNULL: the levels are scored as given. A numericobs_per_cellbesidelevelsis an error, since each sets the ladder.With
n_levels,min_cell_n,sample_norrange_floorsupplied,"auto"isNULL: those arguments describe the ladder of "The ladder and its bounds", and the caller gets it, with the estimate's columns when there is an estimate.Otherwise
"auto"is 4.5 when the estimate is"pooled", the seven sizes 18, 12, 9, 6, 4.5, 3 and 2 when it is"mean", andNULLwithout an estimate.A numeric
obs_per_cellbesiden_levels,min_cell_n,sample_norrange_floor = TRUEsets the ladder, with a warning of classspatialkit_ladder_unusedthat names the arguments that are not read.
On a ladder of sizes the centres are fitted to every row and the count of
cells grows with the rows, so a step that compares every point with every
centre grows with the square of the rows. partition = "kmeans"
has such a step in every pass and in a k-means++ start. partition
= "density" has it in a k-means++ start and, without FNN, in every
pass; with FNN and init = "random" it has none. The profile
stops before any fit, with an error of class
spatialkit_work_limit, when the points times the cells of the
finest level times nstart (times iter_max for the density
kind without FNN) is above
getOption("spatialkit.fit_work_max", 1e10). The message names the
ways on: fewer starts, which keep the best of fewer; a coarser size;
partition = "density" with init = "random", which leaves a
cell without a point more often (see spatialkit_empty_cells under
"Conditions") and, where FNN could not be loaded, needs it
reinstalled first; or a higher limit. The work and the limit are written
in full, so that a work just above the limit does not print as the limit.
The limit counts the finest level, and a ladder of several sizes fits
every one of its levels. At the default size the work grows with the
square of the rows, and a call just below the limit runs for a long time
and prints nothing while it runs. spatialkit-options describes
both limits.
Without FNN the density kind also finds its weights by comparing
every pair of distinct locations. A profile on a ladder of sizes stops,
with the same class, when the square of their number is above
getOption("spatialkit.exact_pairs_max", 2e9), which is about
44,700 locations. The result of every search is the same with and
without the package. moran_i and moran_z need FNN
and Matrix at a level where more than 5,000 cells hold a scored
row. Without them a ladder of sizes has NA in both columns
there, with a warning of class spatialkit_moran_skipped, and so
does a ladder set any other way (see "Conditions").
At a level of up to 5,000 such cells, when either package is missing, the
neighbour weights of the cell means are held as a dense matrix of cells
by cells.
The criteria
select_resolution() reads cp by default on a profile
without an estimate; on one with an estimate it reads the size (pooled
values) or loo (plain means). reliability
needs a variogram range and is NA without one; elbow is
NA unless the points cluster; and moran_z is a diagnostic
of the cell means, which no function reads as a count rule by default.
With an estimate the profile has a fifth column, loo, which
is the last entry. Each entry below says what the column measures and
what it returns.
elbowHow far the WSS curve sags below a power law: on log-log axes,
\logWSS below the straight line fromk = 1(the total sum of squares) to the last level, in natural-log units (larger is better). Points with no cluster structure have a WSS close toc/k, which is straight on those axes, so the column isNAat every level unless the largest sag reaches\log 1.25, and the print says there is no elbow (the rule is given indetermine_optimal_levels). The classical chord on linear axes found a "knee" on such a layer anyway, at about\sqrt{L_{first} L_{last}}, where the ladder's ends put it. A level whose WSS is 0 (to within10^{-12}of the total), one cell on every distinct location, which the ladder reaches when locations repeat, is left out of the line; when the other levels have no elbow, that fall to zero is the elbow, and its sag is measured with the WSS floored at10^{-12}of the total, which puts it far above any other level's. Geometry only; it knows nothing of the response. It isNAunless the points cluster, and where they do it names the number of clusters, which is usually the first level or two of the ladder.cpMallows'
C_pof the piecewise-constant approximation of the response (or of its OLS residuals onpredictor_vars) by cell means:RSS(L)/n + 2 \tau^2 L / n, with\tau^2the nugget of the fitted variogram (lower is better). It estimates the error of re-measuring the sampled sites: each scored row observed again at its own location, with fresh noise of variance\tau^2, and predicted by the mean of its cell. For an observation at a new location the penalty needs the spread of the field inside a cell as well, which the nugget leaves out. This\tau^2is the nugget, the noise of one measurement; it is not thetau2of a pooled value, which is the mean squared distance between a cell's level and its target. When the cells are fitted to a subsample ofmof theNpoints with a response, the penalty is split between the two:RSS(L)/m + \tau^2 L_m / m + \tau^2 L / N, where the first two terms estimate the approximation error from the subsample (adding back the optimism of its own cell means, over theL_mcells its scored points fall in) and the last is the variance of cell means built from allN, which is what the tessellation will carry. With no subsample it is the formula above. On a smooth field with little noise the approximation keeps improving as cells shrink and the penalty is too small to stop it, so the minimum ofC_pis the support ceiling andmin_cell_nis what is choosing;select_resolution()says so when that happens.C_phas an interior minimum when the nugget is a large share of the sill. A nugget of 0, or of at most10^{-4}of the sill, whichestimate_sac_range()marks asnugget_at_bound, is the fit's lower bound and not an estimate, and as\tau^2it would leave no penalty, so thatC_pwould descend to the ceiling whatever the field:C_pdoes not take it. When the variogram gives no nugget (none was fitted, its nugget is at that bound, its fit has no minimum inside the ranges searched, its range is below the shortest lag, it found no spatial structure, orsacis a range alone),\tau^2is Mallows' own choice instead: the residual mean squareRSS / (m - L_m)of the finest level whose cells hold at least two scored rows on average. It counts the structure within those cells as noise too, so on average it is no smaller than the nugget and errs towards fewer cells. When no level's cells hold that many, or the finest that does has a residual mean square of 0 to within the rounding of the values scored (as when each of its cells holds one location whose rows carry one value),cpisNAat every level, as it is for a constant response, which the profile warns about. Whatever its source,\tau^2is held to the semivariance of nearest-neighbour pairs the variogram carries (attr(sac, "short_lag_semivariance"), seesac_nugget): a semivariance does not fall as the lag shrinks, so it bounds the nugget from above, and a larger\tau^2is contradicted by the closest pairs and stopsC_pearly. A semivariance of 0 holds nothing. When\tau^2is not the nugget as it stands, a warning of classspatialkit_cp_noisesays where it came from, andattr(, "cp_noise")records the source and, when the semivariance held it, the number it replaced. Its minimum is often a bound, the support ceiling when the nugget is a small share of the sill, andselect_resolution()then names the bound inedge. The same formula at one cell, with the total sum of squares as its RSS, is kept inattr(, "one_cell"), with the p-value at every level of the F test of that level's cell means against one mean. A level has to beat one cell:select_resolution()returnsstructured = FALSEwhenC_pat one cell is withintolof the optimum, or when the cell means at the optimum differ from one mean by no more than chance allows, because one mean for the whole layer then predicts as well as the cells and the count is not identified (seeselect_resolutionfor the rule).moran_zA diagnostic of the cell means: the standardised deviate of Moran's I on the cell means, or with
predictor_varson the residuals of the cell means regressed on the cell-mean predictors, over the 8 nearest neighbours of each cell. It tests whether neighbouring cell means are independent. It does not measure what the cells leave unexplained, and it does not say how well they represent the response. On any autocorrelated response it grows as the cells get finer than the range, because neighbouring cells then resemble each other, and it has almost no power below about 20 cells, where the 8-neighbour graph between cells is close to complete and Moran's I sits near-1/(L - 1)whatever the data. The level with the smallest|z|is therefore among the coarsest it is computed at on a structured response, whatever the layer and its ceiling, and arbitrary on a response with no structure, wherezis calibrated and flat inL.select_resolution()refuses to read it as a criterion unless asked withdiagnostic = TRUE, and neithersummary()nor the functions that take a profile as a cell count read it by default.NAat nine cells or fewer.reliabilityThe between-cell signal's share of the spread in the cell means, from the fitted variogram alone via Krige's additivity relation (Cressie 1996), for square cells of the level's average area holding the level's average share of the layer's points with a response (larger is better). This is the shrinkage factor of Fay and Herriot (1979). The curve has an interior optimum, a broad one, which can lie below the range floor.
select_resolution()reads it at the levels at or above the floor (itsrange_floorargument), and what it returns is then often the floor, which is a level of every ladder the profile builds: the coarsest count the range allows, with the range choosing rather than the curve. Report the flat region with the count. The domain term is taken over the convex hull the area is measured on, so rotating the layer does not move it.NAwithout a usable variogram, and when the variogram's range was rejected (seesac).looWith an
estimate: the leave-one-out mean squared error of that cell value (lower is better). It estimates the squared error of predicting one further observation, at a location drawn the way the data's locations were, by the value of the cell it falls in. That error depends on the cell value, so the column is computed for the estimate the profile is given and for no other. Each scored row of the layer is predicted by the value of its cell computed without it, in the cell of its nearest centre, which is the cell the seeds will build. Under"mean"a row in a cell of two or more is predicted by the mean of the others, and a row alone in its cell by the mean of the cell of its nearest other scored row. Under"pooled"the cell's mean and its own weight are computed again without the row; the spread inside the cells, the spread between a cell and its target and the targets are held; and a cell left empty takes its target. It needs no variogram. It describes locations among the observations and says nothing of a location away from them: it is a criterion for comparing levels where data are near, not an estimate of the error of a map.loo_seis the standard error, over rows, of that level's mean squared error. It is not the standard error of a difference between two levels, whose errors come from the same rows.scored_per_cellcounts the rowslooread, every scored row of the layer, over the cells that hold one;cell_resp_meancounts the rows the other response criteria read, which are the subsample's when the cells are fitted to one. For pooled values its minimum tends to be the finest size offered (see "How this was checked"), so a size sets the count, andselect_resolution(criterion = "size")reads it.
cp and reliability answer different questions: how well the
cells represent the field, and whether the cell values are distinguishable
from noise. They can disagree, and the profile shows both.
Conditions
What changes the meaning of a result is raised as an R warning with a
class, so tryCatch(), withCallingHandlers() and
options(warn = 2) see it without matching message text; the rest
is logged (see spatialkit_quiet). These are the classes
this function raises; spatialkit-conditions lists every class the
package raises.
spatialkit_not_supportedsupportedisFALSE, because the range floor exceeds the ceiling or because fewer than two cells meetmin_cell_n.spatialkit_floor_above_ceilingThe range floor lies above the ceiling that
sample_nsets on a layer that supports it, so the floor is above every level and is not applied;supportedstaysTRUE. The condition carriesreason("sample_n"),floor,ceiling,nandn_sample. Raisesample_n.spatialkit_response_ceilingRows that are not scored (no response, or with
predictor_varsa predictor missing) lowered the ceiling. The message names the bound in force,min_cell_nor, on a subsample,sample_n; the condition carriesn,n_response,ceiling,ceiling_from,n_sampleandn_scored.spatialkit_constant_responseThe scored variable is constant to within rounding (a response the predictors fit exactly leaves such residuals), so
cp,moran_iandmoran_zareNAat every level. On a profile with anestimatewhose rows are constant too, so arelooandloo_se, and for pooled valuesown_weight; the message names them.summary()of such a profile stops with an error that says the response is constant. Both tests read the raw values and, where those show no spread, the values centred on their median and scaled, so 1e15 plus a spread of 1 is not constant while values that differ only by their rounding (0.1 beside 0.3 / 3) are; residuals are read against the rounding of the regression and of the response, and where the residuals of the raw values show no spread, they are those of a fit to the response less its median. The test forcpreads the scored rows of the subsample and the estimate's every row of the layer (of its selection half underselect_on = "split") with a value: where the first finds the response constant and the second does not, the message says thatloois scored, and the print does not call the response a constant.spatialkit_empty_cellsUnder
partition = "density": a centre holds no point, so there are fewer occupied cells than the count. A centre that loses its points stays where it is, and the start that is kept is the one with the lowest sum, whether or not all its centres hold points. It happens at high counts, mostly frominit = "random". The condition carrieslevel, the count, andempty.spatialkit_not_convergedThe start that was kept was cut off at the iteration limit, so its centres are those of the last step and a longer run can still move points between cells. Not raised for the kind
"kmeans"from k-means++ starts underiter_max = NULL. The condition carrieslevel(every level it happened at),iteranditer_max. Raiseiter_max.spatialkit_ladder_unusedA numeric
obs_per_cellsets the ladder, and the caller also suppliedn_levels,min_cell_n,sample_norrange_floor = TRUE, which are then not read. The condition carriesunused(the argument names) andobs_per_cell.spatialkit_size_not_reachedOn a ladder of sizes: a size does not give the count it asks for. Either a size given as a number gives fewer than two cells while a finer one does not, and its level is 2 (
reasonis"fewer than two cells"); or a size asks for more cells than k-means can place, and its level is the most that can (reasonis"more cells than can be placed"). It is raised once for each reason, naming every size held for it. The condition carriesobs_per_cellandwanted(one element for each such size, in the order of the ladder),usedandreason. When the finest size gives fewer than two cells the warning isspatialkit_not_supported, withobs_per_cellamong its fields andmin_cell_nNA; andspatialkit_response_ceilingis not raised on such a ladder, since a size already counts the rows with a response.spatialkit_repeated_locationsWith an
estimate: scored rows share a location. Each row is left out alone and the others at its location stay, soloothen describes a further observation at a place already observed. Raised once, after the levels are scored, and not whenlooisNAat every level. The condition carriesn(the rows that share a location),total(the rowslooread) andcolumn.spatialkit_no_scored_rowsUnder
select_on = "split": no row of the selection half has a response, and the rows of the layer with one are all in the estimation half.rss,cp,moran_iandmoran_z, which read the selection half, areNAat every level. With anestimate, whose check that it has rows to read is made on the layer,looand the estimate's other columns read no row and areNAat every level too. Withpredictor_varsa row counts when it has a response and every predictor. Not raised when no row of the layer has a response. Raised once, after the levels are scored. The condition carriesreason("no response in the selection half"),n(0, the rows of the selection half scored),selection(the rows of the selection half),n_response(the rows of the layer with a response) andcolumn. Raised too, with or without the split, when rows of the layer have a response and none of them every predictor: thenreasonis"no row with a response and every predictor",n_responsethe rows with a finite response, andselectionNAwithout the split.spatialkit_pool_unavailableWith an
estimate: the values of the response lie beyond what the arithmetic of the estimate holds, values so large, or so close to their median, that the squares of many such values can overflow or lose their precision, soloo,loo_seandown_weightareNAat every level. Where the test forcpfinds such a response constant,cp,moran_iandmoran_zareNAfor the same reason, and this message names them in place ofspatialkit_constant_response. The message gives the bounds; the response rescaled by a power of ten is scored. Raised once, after the levels are scored. The condition carriesreason("values out of range") andcolumns, the response, assummarize_by_cell(estimate = "pooled")raises the class for its pooled columns.spatialkit_moran_skippedWith a level of more than 5,000 cells, on any ladder, when FNN cannot be loaded or Matrix is not installed:
moran_iandmoran_zareNAat a level where more than 5,000 cells hold a scored row, and every other column is computed. Raised once, before the first fit, when such a level can occur: the cells that hold a scored row are counted after a level's fit, so where rows without a response leave fewer of them the two columns are computed after all. The condition carrieslimit,levels(the levels above the limit) andmissing.spatialkit_variogram_unusableThe variogram, the one estimated or
sac, gives no usable range (rejected_reasonofestimate_sac_range()), soreliabilityisNA, and the message says whethercpmay still take its nugget. The condition carriesreason,converged(whether the variogram model converged;NAwhen it does not say),nuggetandnugget_used.spatialkit_cp_noisecpdoes not take the variogram's nugget as it stands. Its noise variance is the residual mean square of the finest level (the variogram gives no nugget, or its nugget is at the fit's lower bound), or the semivariance of nearest-neighbour pairs, which holds the nugget or that residual mean square where they are larger; or there is none andcpisNAat every level: the finest level whose cells hold two scored rows on average has a residual mean square of 0 to within rounding, or, with the nugget at its bound, no level's cells hold that many. The condition carriessource,valueandlevel(asattr(, "cp_noise")holds them; with no noise variancesourceandvalueareNA, andlevelis the level whose residual mean square is 0 to within rounding, orNA),cap(the semivariance,NAwhen the variogram carries none),uncapped_sourceanduncapped_value(whatcpwould take without the hold, and with no noise variance what it refused: the nugget at its bound, or that residual mean square).
The other warnings of this function (points dropped, a variogram of another variable) are R warnings without a class; rows left out for a missing response, a rising WSS curve and a subsample too small to reach the floor are logged only.
One refusal is an error with a class, spatialkit_work_limit:
resolution_profile() stops before a step whose count of
comparisons is above a limit. The condition carries work (the
count), limit and what (the step). On a ladder that
obs_per_cell sets, the count of cells grows with the rows, so two
costs are bounded before the variogram is estimated and before any fit.
The fits: the points times the cells of
the finest level times nstart may not pass
getOption("spatialkit.fit_work_max", 1e10)
(what = "partition fit"; the condition also carries kind,
init, nstart and fnn). That product counts the
step in which every point is compared with every centre, which
partition = "kmeans" has in every pass and in a k-means++ start,
and partition = "density" has in a k-means++ start. Without
FNN the density kind compares every point with every centre in
every pass, and the product is multiplied by iter_max; with
FNN and init = "random" it has no such step and nothing is
counted. The density kind's weights: without FNN they come from a
search that compares every pair of distinct locations, and the square of
their number may not pass getOption("spatialkit.exact_pairs_max",
2e9) (what = "density weights"); density_power = 0 has no
weights and no such search. With an estimate and without
FNN, on any ladder, the same limit bounds the three exact searches
the estimate's columns make: each scored row's nearest centre, each cell's
nearest cells, and, under "mean", the nearest other location of a
row alone in its cell. The result of every search is the same with and
without FNN.
The warnings of the pooled values and of the count record, which
summarize_by_cell() raises, are listed on its page.
How this was checked
The sizes for pooled values were compared in a simulation of 200 layers,
each 1,500 clustered observations of a field with covariance
exp(-d / 100) plus noise on a square of side 1,000
(dev/sim-pooled-values.R
in the package's GitHub repository; summarize_by_cell
describes it), profiled at the sizes 18, 12, 9, 6, 4.5, 3 and 2 with
partition = "density". The lowest loo of the pooled value
was at the size 2 on 176 layers, at 3 on 22 and at 4.5 on 2. That of the
plain mean was at 2 on none: it was at 6 on 86 layers, at 4.5 on 51, at 9
on 49, at 12 on 12, and at 18 and at 3 on one each. These figures are of
those seven sizes and say nothing of another ladder.
References
Cressie, N. (1996). Change of support and the modifiable areal unit problem. Geographical Systems, 3(2–3), 159–180.
Fay, R. E. and Herriot, R. A. (1979). Estimates of income for small places: an application of James-Stein procedures to census data. Journal of the American Statistical Association, 74(366), 269–277. doi:10.1080/01621459.1979.10482505
Mallows, C. L. (1973). Some comments on C_p. Technometrics,
15(4), 661–675. doi:10.1080/00401706.1973.10489103
See Also
select_resolution() to read a level and its flat
region off the profile; summary.resolution_profile() for
every criterion's pick side by side;
determine_optimal_levels() for a count from the
coordinates alone; build_tessellation() and
get_voronoi_seeds(), which accept the profile or a
select_resolution() result directly as approx_n_cells
and n.
Other resolution:
determine_optimal_levels(),
plot.resolution_profile(),
select_resolution(),
summary.resolution_profile()
Examples
library(sf)
# An exponential field with range parameter 200 (true effective range
# 600 m) on a 1 km square, with a nugget of 0.6 on a unit sill.
set.seed(4)
n <- 400
xy <- data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000))
D <- as.matrix(dist(xy))
xy$z <- as.numeric(t(chol(exp(-D / 200) + diag(0.6, n))) %*% rnorm(n))
pts <- st_as_sf(xy, coords = c("x", "y"), crs = 32632)
# The default profile: one level at 4.5 rows per cell, scored for
# pooled values, in density-weighted cells, with no variogram.
prof1 <- resolution_profile(pts, response_var = "z")
prof1
select_resolution(prof1) # the count the size gives
# A ladder of counts for plain means: n_levels asks for the ladder and
# estimate = NULL scores no cell value, so cp is the rule that goes
# with it.
prof <- resolution_profile(pts, response_var = "z", n_levels = 12,
estimate = NULL)
prof
# Three of the criteria, one row per level.
as.data.frame(prof)[, c("levels", "cp", "reliability", "moran_z")]
attr(prof, "bounds")$floor # the range floor: reported, not applied
select_resolution(prof, criterion = "cp")
Extract the nugget of an estimated autocorrelation range
Description
The nugget variance of the variogram model behind an
estimate_sac_range() result: the model's semivariance as the separation
shrinks to zero, which is measurement error plus variation at scales
shorter than the first lag of the empirical variogram.
Usage
sac_nugget(x)
Arguments
x |
A |
Details
The nugget is extrapolated to zero from the first lag, not observed, so it
is only as good as that lag is short; attr(x, "first_lag") says where the
extrapolation starts. With lags = "adaptive" (the default) the first
lag is the separation of the closest pairs of points. With
lags = "equal" it is the middle of a bin cutoff * max_dist / n_lags
wide, which on a dense layer can be many times the spacing of close pairs,
and structure shorter than that bin is then counted as nugget. When
attr(x, "lag_fallback") is TRUE the result is the equal-lag one
although adaptive lags were asked for (see the section "The lags" in
estimate_sac_range()), and its nugget is extrapolated from the first
equal bin.
Every classed result, identified or rejected, carries the nugget as its
nugget attribute, since a resolution criterion for a tessellation needs
it: it is the short-lag variance that no cell can average away. On a
result refused for want of spatial structure it is the variance of the
modelled variable, the nugget of the pure-nugget model that the refusal
supports.
Value
A single number, the nugget in the units of the response's
variance, or NA_real_ when x carries no fitted model: a bare NA
from a run that could not fit anything, a rejected result with too few
lag bins to fit, or an object that is not a sac_range.
How far to trust it
Four more attributes of the result bear on the nugget.
-
nugget_at_boundisTRUEwhen the fit put the nugget at its lower bound (0, or at most 1e-4 of the sill). That value is the bound and not an estimate, and a criterion that uses it as a noise variance has no penalty left. A nugget equal to its floor (seenugget_floor) is the variance between visits, a measurement, andnugget_at_boundstaysFALSEfor it unless the floor itself is at most 1e-4 of the sill. -
short_lag_semivarianceis the semivariance of nearest-neighbour pairs of locations, computed with no model;short_lag_pairsandshort_lag_distgive the number of pairs and their median separation. Each location is paired with the nearest other location, and of several whose squared distances agree to one part in ten million, with the one of lower x coordinate, then lower y. On a square lattice that pairs almost every location with its neighbour along x, so the value measures the field along x, and with the axes of the CRS swapped it can differ. A semivariance does not fall as the lag shrinks, so this value bounds the nugget from above, up to its sampling error: a fitted nugget well above it is contradicted by the closest pairs. -
zero_lag_semivarianceexists where locations were visited more than once (zero_lag_pairsis not 0). It is the semivariance of every pair of rows that share a location, the variance between visits to one place. That is the measurement part of the nugget, observed and not extrapolated, without the variation at scales below the spacing of the locations, so it bounds the nugget from below. Such pairs are at no lag and in no bin of the variogram, since the model, and so the nugget, describe positive separations. -
nugget_flooris the value the fit did not let the nugget under:zero_lag_semivariancewhere it rests on 30 degrees of freedom or more (rows less locations), and 0 otherwise. Withdetrend = "reml"the model is built from the REML parameters and takes no floor: its nugget can come out below the variance between visits, andnugget_flooris 0.
See Also
estimate_sac_range(), which produces the object.
Other spatial autocorrelation:
estimate_sac_range(),
plot.sac_range()
Examples
library(sf)
# A field with a nugget: half a unit of white noise on a unit sill.
set.seed(3)
n <- 250
xy <- data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000))
D <- as.matrix(dist(xy))
xy$z <- as.numeric(t(chol(exp(-D / 150) + diag(0.5, n))) %*% rnorm(n))
r <- estimate_sac_range(st_as_sf(xy, coords = c("x", "y"), crs = 32632), "z")
sac_nugget(r) # the fitted nugget, on the sill's scale
attr(r, "nugget_at_bound") # FALSE: an estimate, not the bound
attr(r, "short_lag_semivariance") # what the closest pairs say, no model
attr(r, "zero_lag_pairs") # 0: no location was visited twice
sac_nugget(NA) # nothing fitted: NA
Select predictors by forward selection on spatial folds
Description
Selects predictors by repeatedly adding whichever candidate most improves a
cross-validated score, stopping when the best candidate's improvement is
no larger than the fold-to-fold noise in it (rule = "se", the
default) or no larger than tol (rule = "tol"). The first
variable has a baseline to beat with every learner, so the selection can
be empty.
Usage
select_features_forward(
train_sf,
response_var,
candidate_vars,
fit_fn,
k = 5,
method = c("block_kfold", "random_kfold"),
block_size = NULL,
metric = c("RMSE", "MAE", "R2"),
tol = 0,
max_vars = NULL,
max_fits = 5000L,
seed = 123,
quiet = FALSE,
auto_range = FALSE,
select_on = c("all", "split"),
rule = c("se", "tol"),
se_mult = 1,
null_fn = NULL
)
Arguments
train_sf |
Training data ( |
response_var |
Character(1). |
candidate_vars |
Character vector of predictors to choose among. |
fit_fn |
A function |
k |
Inner fold count. Default 5. |
method |
Inner fold method: |
block_size |
Minimum inner block edge, passed to
|
metric |
Score to optimise: |
tol |
Minimum improvement of the pooled score required to accept a
variable, in the units of |
max_vars |
Optional cap on how many predictors to select;
|
max_fits |
Abort if the sweep would exceed this many model fits. Default 5000. |
seed |
RNG seed, default 123. It governs both the inner fold
construction and the cross-validation itself: it is forwarded to
|
quiet |
Logical; suppress this function's progress |
auto_range |
Logical. If |
select_on |
|
rule |
How a step is judged. |
se_mult |
Number of standard errors the mean per-fold gain must
exceed under |
null_fn |
Optional function |
Details
To get a performance estimate for the selected model, call this function
inside the fit_fn you pass to cv_spatial().
cv_spatial() calls fit_fn(train_sf) on each fold's training
rows only, so a selection run inside fit_fn sees no held-out data.
The cost grows fast: a sweep over p candidates costs roughly
p^2 / 2 * k model fits, and nesting it inside n outer folds
multiplies that by n. max_fits guards against it.
Value
A list of class "feature_selection" (so that
plot.feature_selection() draws the selection path) with
these elements:
selectedThe chosen predictors, in the order they were added; possibly none.
scoreThe winning set's cross-validated
metricat the final step: the optimum inside the selection, optimistically biased because it was chosen as the best of many (see "Selection score"), andNAwhen nothing was selected.score_holdoutNAunlessselect_on = "split", and then the selected set'smetricwhen fitted on the selection half and predicted on the estimation half (R^2against the selection half's mean, the out-of-sample convention);NAwhen nothing was selected or the prediction failed.historyA data.frame with
step,variable,score,n_pred,gain,fold_gainandfold_gain_se, holding every candidate evaluated at every step, and astep = 0row named"<none>"giving the baseline, so the first variable's gain can be read off directly.gainis the candidate set's improvement in the pooled score over the set it was added to (the baseline at step 1),fold_gainthe mean of the per-fold improvements andfold_gain_seits standard error: the three numbers the rule reads.n_predis how many rows the set's cross-validation predicted.fold_scoresA data.frame with
step,variable,foldandscore: the metric of every set in every fold.baselineA list with
type("null model","null_fn"or"fold mean"),score,path(the set the sweep reached),gain,fold_gainandfold_gain_se(that set against the baseline),kept(FALSEwhen the path did not beat a fold-mean baseline andselectedis empty for that reason;NAwhen the path is empty) andfirst.firstisNULLunless the baseline is the fold mean and a path of two or more variables was kept. It is then the test of the first variable, a list with:-
variable; -
gain,fold_gainandfold_gain_se: the path against the path without that variable; -
rest, a list withvars,score,gain,fold_gainandfold_gain_se: the path without it, and that set against the baseline; -
dropped:TRUEwhen the variable was taken out (selectedis thenpath[-1]andscoreisrest$score); -
note, the verdict in words.
The set scored for that test is not a step of the sweep, so it is not in
historyorfold_scores.-
splitNULL, or a list withselectionandestimation, integer row positions intrain_sfas passed; rows the completeness filter above dropped are in neither.paramsThe settings:
metric,method,k,tol,seed,auto_range,select_on,n_candidates,estimated_fits,n_scored,rule,se_multandbaseline(its type).
Every set is scored on the same rows: those the null model's
cross-validation predicted or, when the baseline is the fold mean,
those any step-1 set predicted; params$n_scored counts them (a
warning says so when that is fewer than all). A set that left some of
the scored rows unpredicted, because a fold failed for it, has
score NA, with a warning naming it: scored on the rows it
did predict it would be compared on fewer, usually easier, rows than its
rivals. A factor with a level found in one spatial block only is the
usual case, and cannot be selected.
Inner and outer folds
The inner folds should hold points out as the outer ones do. A
cross-validated score is the error at the distance the folds put between
the held-out points and their training data, so nested selection chooses
the variables that predict best at the inner folds' distance. Random
inner folds inside blocked outer folds choose for predicting among the
samples, where a variable that only tracks nearby values of the response
can win, and the outer loop then scores the chosen set at the blocks'
distance, for which it was not chosen. method therefore defaults
to "block_kfold", as the folds of the cv_*() functions do,
and logs a caution (not an R warning) when set to "random_kfold".
When a variable is accepted
Each candidate set is scored by cross-validation on the same inner folds,
and the candidate with the best pooled score is the one considered. Under
rule = "se" it is accepted when two things hold: the pooled score
improves by more than tol, and the mean of the per-fold
improvements (the metric computed in each fold for the set with and
without the candidate, and differenced) exceeds se_mult times the
standard error of that mean across the folds. This is the
one-standard-error idea of Breiman et al. (1984) applied to a step: a gain
the folds do not agree on is not evidence that the variable predicts. The
fold is the unit because under spatially blocked folds the errors within
a block are correlated, so a standard error over rows would understate
the noise. Against rule = "tol", which accepts any pooled gain
above tol, the rule adds fewer noise variables and costs power on
weak predictors. With few folds the standard error is itself noisy, so
raise k before lowering se_mult. history records each
candidate's pooled gain, mean per-fold gain and its standard error, and
fold_scores the per-fold scores themselves, so every decision can be
checked.
The baseline for the first variable
The first variable is compared with a model that has no predictors,
recorded as step 0 of history. Which model that is depends on the
learner, and baseline$type says which was used:
baseline$type | The baseline | How the first variable is tested |
"null model" | fit_fn(train_sf, character(0)), when the
learner can fit it | at step 1, like any other step |
"null_fn" | the model null_fn(train_sf) returns, for a
learner that cannot fit an empty set | at step 1 |
"fold mean" | the mean response of each fold's training rows,
when neither is available (fit_rf_model() refuses an
empty predictor set) | the whole set at the end of the path, then the set without its first variable |
Under a fold-mean baseline the first variable is provisional: it is added
without a test, the sweep continues by the rule, and the finished set is
kept only if it beats the fold mean by the same rule; otherwise nothing is
selected, and baseline$path holds the set that was reached. The
test is at the end of the path because a forest on a single variable can
lose to the mean when two variables together beat it clearly. A kept
path of two or more variables is then scored once more without its first
variable (one more set, k more fits), and that variable is dropped
from selected when the set is no better with it by the rule and the
rest of the path still beats the fold mean by the rule.
baseline$first records the test, and selected is
baseline$path[-1] after a drop. When the set is no better with the
first variable but the rest of the path does not beat the fold mean
either, the two cannot be told apart: the set is kept whole, a caution is
logged, and baseline$first$note says the variable is unproven. So
in a selection of two or more variables from a learner that falls back to
the fold mean, selected[1] has been shown to improve the set, not
to predict on its own.
For a GWR the fold mean is a weak baseline: every GWR carries a local
intercept and beats a global mean on any smooth response, whatever its
predictors are. The baseline that matters is the kernel-weighted local
mean at the same bandwidth, a GWR with a local intercept and no
predictors, which fit_gwr_model() fits when its
predictor_vars is character(0). A fit_fn that hands
its variables to fit_gwr_model() therefore gets it as the null
model. Give such a fit_fn a fixed bandwidth, so that every
set is fitted under the kernel the baseline has; with
bandwidth = NULL each set, the empty one included, searches for
its own. A GWR fit_fn that refuses an empty set falls back to the
fold mean, and the sweep logs a caution: read a selection of one variable
made that way as unproven, or supply the local mean as null_fn, as
the second half of the example does.
predict() on a GWR warns about held-out locations it cannot
estimate and about those beyond the reach of a fold's fit (classes
"spatialkit_gwr_not_estimable" and
"spatialkit_gwr_extrapolation"; see spatial_fit-predict).
The sweep raises each once, under this function's name, with the totals
over the candidate sets it scored; every set is predicted on the same
rows, so a location can be counted once per set.
Selection with a random forest
A forest confounds selection with tuning: a predictor that carries no
signal still changes how the trees split, and with ranger's default node
size that can regularise the forest and lower the cross-validated error.
No acceptance rule refuses that gain, so a variable in a forest selection
may be there as a tuning effect, wherever in the order it was added.
Setting the node size in fit_fn reduces this without removing it,
and comparing the selected set with a tuned forest on the variables you
have other reasons to believe in shows how much of the gain is tuning:
fit_fn <- function(train_sf, vars) fit_rf_model(train_sf, "z", vars, min_node_size = 20)
Selection score
$score is the cross-validated metric of the winning set at
the final step: the best of every candidate set the sweep scored. A
number optimised over many candidates is optimistically biased by
construction, and Cawley and Talbot (2010) show the bias can exceed the differences between
the models being compared. Quote it as the selection criterion, not as
the performance of the selected model. A performance estimate needs data
the selection never saw. Two ways to get one: run this function inside
the fit_fn of cv_spatial(), so the outer folds score a
model whose predictors were chosen on the inner ones alone; or pass
select_on = "split", which selects on one spatial half of
train_sf and returns the selected set's score on the other as
score_holdout.
References
Breiman, L., Friedman, J. H., Olshen, R. A. and Stone, C. J. (1984). Classification and Regression Trees. Wadsworth.
Cawley, G. C. and Talbot, N. L. C. (2010). On over-fitting in model selection and subsequent selection bias in performance evaluation. Journal of Machine Learning Research, 11, 2079–2107. https://jmlr.org/papers/v11/cawley10a.html
See Also
plot.feature_selection() to draw the selection
path, gwr_model_selection() for a fast in-sample screen for
GWR, and cv_spatial() to nest the selection in outer folds.
Other predictor selection:
gwr_model_selection(),
plot.feature_selection(),
plot.gwr_model_selection()
Examples
library(sf)
set.seed(1)
n <- 120
pts <- st_as_sf(
data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
a = rnorm(n), b = rnorm(n), noise = rnorm(n)),
coords = c("x", "y"), crs = 32632
)
pts$resp <- 3 * pts$a + 2 * pts$b + rnorm(n, 0, 0.3)
# The learner: a GWR with an adaptive bisquare kernel reaching the 30th
# nearest training point. With no variables it is the kernel-weighted
# local mean, which is the baseline: a GWR's local intercept beats a
# global mean on any smooth response, so the first variable has to beat
# the local mean under the same kernel.
fit_fn <- function(tr, vars) fit_gwr_model(tr, "resp", vars, bandwidth = 30)
sel <- select_features_forward(pts, "resp", c("a", "b", "noise"), fit_fn,
k = 3, quiet = TRUE)
sel$selected
sel$baseline$type # "null model": step 1 was tested against it
sel$history[sel$history$step <= 1, c("step", "variable", "score", "gain")]
# A learner that cannot fit an empty set takes its no-predictor model
# through `null_fn`. Here the same local mean, written as a spatial_fit
# of its own with a predict() method, for a learner that insists on a
# variable. Without `null_fn` that sweep would start from the mean of
# each training fold.
needs_one <- function(tr, vars) {
if (!length(vars)) stop("this learner needs a predictor")
fit_gwr_model(tr, "resp", vars, bandwidth = 30)
}
local_mean <- function(tr, bandwidth = 30) {
new_spatial_fit("local_mean_fit",
engine = list(xy = st_coordinates(tr), y = tr$resp,
bandwidth = bandwidth),
formula = resp ~ 1, response_var = "resp",
predictor_vars = character(0), data_sf = tr)
}
predict.local_mean_fit <- function(object, newdata = NULL, ...) {
e <- object$engine
at <- if (is.null(newdata)) e$xy else st_coordinates(newdata)
vapply(seq_len(nrow(at)), function(i) {
d <- sqrt((e$xy[, 1] - at[i, 1])^2 + (e$xy[, 2] - at[i, 2])^2)
h <- sort(d)[min(e$bandwidth, length(d))] # the kernel's reach here
w <- ifelse(d > h, 0, (1 - d^2 / h^2)^2) # bisquare weights
sum(w * e$y) / sum(w)
}, numeric(1))
}
registerS3method("predict", "local_mean_fit", predict.local_mean_fit)
sel2 <- select_features_forward(pts, "resp", c("a", "b", "noise"), needs_one,
k = 3, quiet = TRUE, null_fn = local_mean)
sel2$baseline$type # "null_fn"
all.equal(sel2$baseline$score, sel$baseline$score) # the same baseline
Choose a cell count from a resolution profile
Description
Picks the level a criterion prefers, together with the flat region:
every level whose criterion value is within tol of the optimum.
Report the flat region with the count.
On the default profile, one size scored for pooled values, the default
criterion is that size: it returns the count the size gives, with no
optimum and no flat region (see "A profile built with an estimate"); what
follows is about the criteria read on a ladder of counts. When the
optimum sits at an end of the levels the criterion was scored at,
the result says so and names the bound, because a bound is then doing the
choosing rather than the criterion (see
resolution_profile for what each criterion measures and
what it returns in practice). The functions that take the result as a
cell count raise that as a warning of class
spatialkit_bound_chosen.
Usage
select_resolution(
profile,
criterion = c("auto", "cp", "reliability", "elbow", "moran_z", "loo", "size"),
tol = 0.02,
range_floor = TRUE,
diagnostic = FALSE,
obs_per_cell = NULL
)
Arguments
profile |
A |
criterion |
Which rule sets the count: |
tol |
Width of the flat region. For |
range_floor |
For |
diagnostic |
|
obs_per_cell |
For |
Value
A list of class resolution_selection with these elements:
bestThe level.
flatThe levels in the flat region, ascending: a set, which can skip a rung.
criterionThe criterion applied, never
"auto".valueThe optimum.
at_ceiling,at_floorWhether the optimum is the last or first of the levels this criterion was read at, which for
moran_zstarts above nine cells and forreliabilityat the range floor; bothNAunder"size", which searches for no optimum.edgeWhich bound that is, in words: the support ceiling, the subsample's ceiling, the range floor, the ladder's own end, the finest or the coarsest size offered on a ladder
obs_per_cellset, the only level scored, or the first or last level the criterion is computable at;NAfor an interior optimum and under"size".n_levelsThe levels on the profile.
valuesThe criterion at every level,
NAwhere it could not be computed.structuredFor
cp:FALSEwhencpat one cell is not above the optimum by more thantol(below it included), when the cell means at the optimum differ from one mean by no more than chance allows, or when the variogram found no spatial structure;TRUEwhen the optimum beats one cell on both counts (see "What each criterion returns"). Forlooandsizeon a profile built withestimate:FALSEwhen the leave-one-out error of one mean for all scored rows is withintolof the error atbest, or below it, or when the cell means atbestdiffer from one mean by no more than chance allows;TRUEwhen the cells beat one mean on both counts.TRUEfor anelbow;NAforreliabilityandmoran_z, and for a profile that carries no one-cell value.one_cellcpat one cell undercp; the leave-one-out error of one mean for all scored rows underlooandsize;NAotherwise.structure_pThe p-value of the F test of the cells at
bestagainst one mean, multiplied by the number of levels searched and capped at 1 (a size searches one level);NAwherestructuredis not read offcpor the leave-one-out error.range_floorThe floor
reliabilitywas held to, orNA.noteWhat the flags mean, in words: a character vector, one note an element;
NULLwhen there is nothing to say. The notes written under"loo"and"size", for a profile built withestimateor with one size, and about the range floor, carry names:size(the size that set the count),held(a size the profile held to the most cells k-means can place),structure(why the count is not identified),finest(the lowest error of pooled values is at the finest level scored),estimate(cpscores plain means, on a profile of pooled values),ladder(the ladder is one size) andfloor(underreliabilitywithrange_floor = TRUE: the range floor lies above every level scored, so it was not held;structuredisNAthere). A note ofcpormoran_zabout the criterion itself has no name. The warning of classspatialkit_no_structurethat the functions taking the selection as a count raise carries every note but those namedsize,held,finest,estimateandladder.seedsAn sf POINT layer, with
seed_id, of the centres of the partition the profile scored atbest, in the CRS it was computed in;NULLfor a profile that does not carry them. See "Seeds" below.partitionFor a profile built with
partition = "density"orinit = "random":kind,init,density_poweranddensity_k. The seeds carry it asattr(, "partition"); the cells are those the profile built, whatever kind built them. It stays the last element.
For "loo" and "size", and for any criterion on a profile
built with estimate, the list has these elements after
seeds:
estimateThe profile's,
"mean"or"pooled";NAfor a profile without one.obs_per_cellRows per cell at
best: the rows a size divides overbest;NAfor an object that keeps no row count.obs_per_cell_askedThe size asked for;
NAunless the criterion is"size".scored_per_cellThe profile's column at
best: the rows the leave-one-out error read over the cells that hold one. It is notobs_per_cell: it leaves out rows the error did not read and cells that hold none of them, as underselect_on = "split".loo,loo_one_cellThe leave-one-out error at
bestand that of one mean for all scored rows.share_alone,own_weightThe profile's columns at
best.count_ruleA list of class
spatialkit_count_rulethat records how the count was set:rule(the criterion applied),estimate(the estimate the rule was computed for: the profile's for"size"and"loo","mean"for"cp",NAotherwise),cells,obs_per_cell,obs_per_cell_asked,response,n(the rows the size divides),n_points,n_fit(the rows the centres were fitted to; fewer thann_pointsfor a subsample),seed,features,scored(what the profile scored atbestfor its estimate:estimate,n,cells,loo,loo_se,loo_one_cell,share_alone,own_weight,structured,rowsandcentres, the matrix of the centres the rows were scored in, incrsand in the profile's order;NULLwithout an estimate),partition,crsandscored_cells(NA: the record stands for a count).
A "cp" selection off a profile without an estimate has
count_rule as well, after seeds, and nothing else of
this list: its estimate is "mean", since C_p scores
plain means, and scored is NULL. Under "loo" and
"size" one_cell holds the leave-one-out error of one mean
and range_floor is NA.
seeds carries the same record as attr(, "count_rule")
with scored_cells = TRUE, since they are the centres that were
scored, or FALSE when they were refitted to every point, since
they are then other cells built from the count. The record travels on
with the seeds, the cells and the assigned layer to
summarize_by_cell(), which warns when it reports another
cell value than the count was chosen for (class
spatialkit_estimate_mismatch) and when the cells or rows it is
given are not the ones the count was scored on
(spatialkit_cells_differ).
Seeds: the Voronoi cells of the seeds are the cells that were scored;
get_voronoi_seeds(method = "kmeans", n = <this>) and
voronoi_seeds_kmeans(k = <this>) return them. On a
profile without an estimate whose centres were fitted to a subsample
(n_sample below n in attr(profile, "bounds")) the
seeds are those centres refitted to every point: the kind's own
iteration (Hartigan and Wong's for "kmeans", Lloyd's on every
point's density weights for "density") run from the centres
scored, with the profile's iteration limit and no random draw. Where
Hartigan and Wong's algorithm refuses the centres, Lloyd's iteration
with every weight one runs in its place, and a log line says so. Such
seeds carry attr(, "refit"): rows (the points),
subsample (the points the profile fitted to), kind,
iter, iter_max, converged, wss_scored (the
within-cell sum of squares of every point in the cells of the centres
scored, each cell about its own mean) and wss (the same of the
refitted cells). Their cells are then not the cells scored, and the
count is still the one the subsample gave; the centres scored are
attr(profile, "centres")[[as.character(best)]]. The refit reads
every point's coordinates from attr(profile, "refit_rows"); on a
profile without that attribute the centres scored are the seeds, and a
log line says so. The refit is not run either, and the centres scored
are the seeds, when it would pass the work limits of a profile's own
fits (see "Conditions" in resolution_profile); a log line
says so. A profile with an estimate scores it on every row of the
layer in the cells of the centres fitted to the subsample, so its seeds
are those centres, whose cells are the cells scored. summary()
and plot() of a profile read no seeds and refit nothing.
What each criterion returns
cpThe level that minimises Mallows'
C_p: the count at which re-measuring the sampled sites, each predicted by its cell's mean, has the least estimated error (resolution_profilesays what that leaves out for a new location). On a smooth response with little noise that is the support ceiling. The result also says whether the optimum beats one cell for the whole layer (attr(profile, "one_cell")), instructured. It isTRUEwhen two things hold:C_pat one cell is above the optimum by more thantol, and the cell means at the optimum differ from one mean by more than chance allows. The second is the F test of the cells against one mean,(TSS - RSS) / (L - 1)overRSS / (m - L), at 5 percent after a Bonferroni adjustment for the levels the optimum was searched over (structure_pis the adjusted p-value). The cells are fitted to the coordinates alone, so the test holds its level on a response with no spatial structure whateverC_p's noise variance is, and it is what decides when that variance is 0:C_pis thenRSS / n, which falls with every finer level by chance alone, and the first comparison says nothing. When either fails,structuredisFALSE: one mean for the whole layer predicts as well as any level scored, so the response shows no spatial structure the cells can use and the count is not identified.structuredis alsoFALSEwhen the profile's variogram was refused for showing no spatial structure.bestis still the argmin. The F distribution is exact for a Gaussian response. The test has little power on a small layer, so aFALSEthere is weak evidence that there is no structure.reliabilityThe level of highest reliability at or above the range floor the profile reports (when the layer supports the floor and the profile built its own ladder). The reliability curve often peaks below the floor, and the floor is a level of every such ladder, so the result is often the floor, the coarsest count the range allows, with
edgenaming it (on a profile whose k-means failed at that level, the first level above it).range_floor = FALSEreads every level and returns the curve's own maximum, which can be a count below the floor.elbowThe number of clusters of the points, when they cluster; an error otherwise, because the column is
NAat every level unless the WSS curve bends.moran_zRefused unless
diagnostic = TRUE. It is the level at which neighbouring cell means (or, with predictors, their regression residuals) are least autocorrelated.|z|is near 0 at 10 to 20 cells whatever the data and grows as cells get finer than the range, so its minimum is usually the first level it can be computed at, or one near it, and it says nothing about how well the cells represent the response.looThe level with the lowest leave-one-out error of the estimate the profile was built for (
resolution_profile(estimate = )); of levels with the same error, the one with the fewest cells. The flat region is every level whose error is withintolof the lowest. The column needs no variogram.structuredis read as forcp, with the leave-one-out error in place ofC_p: it isTRUEwhen the error of one mean for all scored rows is above the optimum by more thantoland the F test of the cells at the optimum against one mean, adjusted for the levels searched, hasp < 0.05;one_cellthen holds the error of one mean. Under this criterion the count depends on the values of the response. When the profile's estimate is the pooled value and the lowest error is at the finest level scored, a note says that the end of the ladder chose the count. For pooled values the error tends to keep falling to the finest level (see "How this was checked" inresolution_profile). On a ladderobs_per_cellset, an optimum at an end has theedge"the finest size offered (obs_per_cell)"or"the coarsest size offered (obs_per_cell)"; a finest level the profile held to the most cells k-means can place keeps the label of the support ceiling.sizeThe count a size gives,
max(2, round(n / obs_per_cell)), withnthe rows the size divides: the rows with a response, or every point for a profile without one. No optimum is searched for. The level returned is the first of three that applies: the level the profile built for that size; the count itself, when the profile has a partition at it; otherwise the built level nearest to the count on the log scale (of two as near, the one with fewer cells), with a warning of classspatialkit_size_not_reached, which says so when the count is more than k-means can place on the layer. It reads any profile, one built without a response or without an estimate included, but not a column subset, which has lost the row count.flatis the level,valuethe rows per cell it leaves (n / best), andat_ceiling,at_floorandedgeareNA: no bound chose anything, so the functions that take the selection as a count raise nospatialkit_bound_chosen. Under this rule neither the cells, which are fitted to the coordinates, nor their number, which is a count of rows, depend on the values of the response. A size does not ask whether the response has structure the cells can use, sostructuredasks it separately, on a profile built with anestimate. It isFALSEwhen the leave-one-out error of one mean for all scored rows is withintolof the error at the level, or below it, or when the F test of the cells at the level against one mean hasp \ge 0.05. The count stands either way, since a size set it and no criterion:structured = FALSEsays that the cell values will say little that one mean for the layer does not. The functions that take the selection as a count then raisespatialkit_no_structure. On a profile without an estimatestructuredisNA.autoThe rule that goes with the profile's estimate:
"size"for a profile built withestimate = "pooled","loo"forestimate = "mean", and"cp"for a profile without an estimate. A column subset of a profile has lost the record of its estimate and is read by"cp".criterionin the result is the criterion applied, never"auto".
A profile built with an estimate
This function's default criterion is "auto": "size" for a
profile of pooled values, "loo" for one of plain means and
"cp" for a profile without an estimate. A profile built with
estimate that is passed straight to
get_voronoi_seeds(), voronoi_seeds_kmeans() or
build_tessellation() as the count is read the same way, so
select_resolution(profile) and the profile itself give the same
count. A profile of pooled values built with a ladder argument
(n_levels and the others) is read by the size as well: the
default returns the level nearest the count the size gives, on the
automatic ladder its top level, with spatialkit_size_not_reached.
criterion = "cp" reads C_p on a profile that has it.
cp is computed on such a profile as on any other and scores plain
means; when the profile's estimate is the pooled value the
result's note says so.
"cp" and "reliability" cannot be read off a profile whose
ladder obs_per_cell set under sac = "auto". Such a profile
fits no variogram, both columns are NA at every level, and the
call is an error that names the ways to get them: build the profile with
sac = NULL, with a sac of your own, or with
obs_per_cell = NULL. The default profile is such a profile. On a
ladder of one size that has a
variogram either criterion returns the one level, with edge
"the only level scored".
For a ladder of one size, summary() of the profile lists each
criterion that is finite at the level and says that the size set the
count, and plot() draws each as one point, with no selected level
and no flat region. When none is finite, as on a constant response, where
loo is NA too, or when no row of the selection half has a
response (select_on = "split"), summary() stops with an
error that says so. In that last case "cp" and "moran_z",
and "loo" with an estimate, are errors that give the same
reason, except "cp" on a size ladder that fitted no variogram,
which gives the size ladder's reason, as above.
See Also
Other resolution:
determine_optimal_levels(),
plot.resolution_profile(),
resolution_profile(),
summary.resolution_profile()
Examples
library(sf)
# An exponential field with range parameter 200 (true effective range
# 600 m) on a 1 km square, with a nugget of 0.6 on a unit sill.
set.seed(4)
n <- 400
xy <- data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000))
D <- as.matrix(dist(xy))
xy$z <- as.numeric(t(chol(exp(-D / 200) + diag(0.6, n))) %*% rnorm(n))
pts <- st_as_sf(xy, coords = c("x", "y"), crs = 32632)
# The default profile is one size scored for pooled values, and the
# default criterion, "auto", reads it by that size.
select_resolution(resolution_profile(pts, response_var = "z"))
# A ladder of counts for plain means, read by Mallows' Cp.
prof <- resolution_profile(pts, response_var = "z", n_levels = 12,
estimate = NULL)
sel <- select_resolution(prof, criterion = "cp")
sel # the level, and the flat region around it
sel$flat # every level within `tol` of the optimum
sel$edge # the bound the optimum sits on; NA when interior
sel$structured # FALSE when one cell for the layer does as well
# Reliability prefers coarse cells: it is read at or above the floor the
# autocorrelation range sets, and the result says in words when the
# floor is choosing.
rel <- select_resolution(prof, criterion = "reliability")
rel
rel$at_floor
rel$edge
Extract the coefficients of a fitted model
Description
coef() on a GWR returns the local coefficients, one row per
observation and one column per term. On a Bayesian GP fit it returns the
posterior summary of the global regression terms. A random forest has no
coefficients, so coef() on an rf_fit always stops with an
error rather than returning NULL; a forest's variable importance is
in fit$info$importance (see fit_rf_model()). None of
the three returns NULL (see "The coef() contract" in
new_spatial_fit()).
Usage
## S3 method for class 'gwr_fit'
coef(object, se = FALSE, ...)
## S3 method for class 'bayesian_fit'
coef(object, ...)
## S3 method for class 'rf_fit'
coef(object, ...)
Arguments
object |
A fitted |
se |
GWR only. Logical; also return the standard errors and t
values. Default |
... |
Not used. |
Details
The GWR table shows where, and by how much, a predictor's relationship
with the response changes across the study area: read the spread of its
column, or join the table back to object$data_sf to map it.
plot.spatial_fit() draws that map.
The Bayesian GP summary gives the estimate, error and credible interval of
each predictor, as brms::fixef() reports them. The Gaussian-process
term has already taken up the spatially structured part of the signal, so
these are effects net of location (see "Spatial confounding" in
fit_bayesian_spatial_model()).
Value
For a GWR with se = FALSE, a data.frame of local
coefficient estimates: one row per observation, one column per model
term. With se = TRUE, a list of three such data.frames:
estimate, se and t. An engine without an
SDF component is an error.
For a Bayesian GP fit, a matrix of fixed-effect posterior summaries, as
brms::fixef() returns them, on the fitted scale (per standard
deviation of each predictor under standardize_predictors = TRUE),
in the units of the response: where the response was handed to brms
less a centre or divided by a scale, the intercept has the centre added
back and every column is multiplied by the scale (see "The response's
centre and scale" in fit_bayesian_spatial_model()).
brms::fixef() on object$engine answers on the scale brms
was given. A missing brms or a failing fixef() call is an
error.
For a random forest, nothing: the call is an error.
GWR columns
Only the model terms are returned: the intercept and one column per
predictor. The engine's SDF data slot holds more beside them
(standard errors, t values, the observed response, the fitted values, the
residuals, Local_R2); read object$engine$SDF for those, and
ask for the standard errors and t values with se = TRUE.
A coefficient is NA at a location whose local window cannot
estimate it: a predictor that does not vary among the observations that
carry weight there has no slope, and the intercept is then not identified
either unless the predictor is 0 there. object$info$nonfinite_coef
is the mask, and fit_gwr_model() raises a warning that
counts them.
If the model terms cannot be located in the SDF (an engine that
names its coefficient columns differently), the whole slot is returned,
with a WARN line in the log saying so (a log record, not an R warning;
see spatialkit_quiet()). With se = TRUE the call
stops instead. It never returns a silently short table.
GWR standard errors
With se = TRUE the local standard errors and t values come with the
estimates. A standard error is
\hat\sigma\sqrt{(C C^\top)_{jj}}, with
C = (X^\top W X)^{-1} X^\top W the weights the local regression puts
on the responses and \hat\sigma^2 the residual sum of squares over
the fit's effective degrees of freedom: the definition
GWmodel::gwr.basic() uses, computed from the QR decomposition that
gave the estimate. They treat the bandwidth as known. The t values are
one test per term and location, tens to thousands of them and strongly
dependent, so a map of |t| > 2 overstates what is significant; no
p-value, adjusted or not, is returned. An adjustment for the number of
tests can use the t values here, the effective number of parameters
object$info$enp and the residual degrees of freedom
object$info$edf. When observations share a location the standard
errors are too small as well (see "Observations that share a location" in
fit_gwr_model()).
Bayesian GP standardised predictors
The summaries are on the scale the model was fitted on. A fit made with
standardize_predictors = TRUE was fitted on centred and scaled
numeric predictors, so each slope is the change in the linear predictor
per standard deviation of its predictor and the intercept is its value at
the predictor means, not the raw-unit numbers stats::lm() reports
on the same formula. The returned matrix does not say so;
print() on the fit does, and the centre and scale of each predictor
are in object$info$predictor_scaling. To put a slope back in raw
units divide its Estimate, Est.Error and interval bounds by
that predictor's scale. The intercept's Estimate follows by
linearity (subtract each raw-unit slope times its predictor's
center), but its Est.Error and interval depend on the
posterior covariance of the coefficients: transform the draws from
brms::as_draws_df(object$engine) for those, or refit without
standardising.
See Also
Other fit methods:
plot.spatial_fit(),
print.spatial_fit(),
spatial_fit-fitted,
spatial_fit-predict,
spatial_fit-residuals,
summary.spatial_fit()
Examples
library(sf)
set.seed(1)
n <- 80
pts <- st_as_sf(
data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000),
a = rnorm(n)),
coords = c("x", "y"), crs = 32632
)
# The slope on a rises from west to east.
east <- (st_coordinates(pts)[, 1] - 5e5) / 1000
pts$z <- 10 + (1 + 2 * east) * pts$a + rnorm(n, 0, 0.3)
gw <- fit_gwr_model(pts, "z", "a", bandwidth = 30)
str(coef(gw, se = TRUE))
summary(coef(gw)$a) # the local slopes span the west-east change
Extract the fitted values of a fitted model
Description
fitted() on a random forest, a GWR or a Bayesian GP fit returns one
value per training row, in the order of object$data_sf. What the
value is depends on the backend, and so does what summary() and
model_metrics() without newdata report:
a random forest returns out-of-bag predictions: each row predicted by the trees that did not sample it (see "Fitted values are out-of-bag" in
fit_rf_model()). A row that every tree sampled has no out-of-bag prediction and isNaN;a GWR returns the values
fit_gwr_model()stored on the fit: at each training location, the value of the local regression centred there. These are in-sample values (each observation sits inside its own window), sosummary(), andmodel_metrics()withoutnewdata, report an optimistic fit; usecv_gwr()for a spatially blocked estimate. An engine made elsewhere (a GWmodel result) is read from itsSDFtable instead;a Bayesian GP returns the posterior expectation at the training locations, the column means of
brms::posterior_epred(), in the units of the response (see "The response's centre and scale" infit_bayesian_spatial_model()). These are in-sample values.
Usage
## S3 method for class 'gwr_fit'
fitted(object, ...)
## S3 method for class 'bayesian_fit'
fitted(object, ...)
## S3 method for class 'rf_fit'
fitted(object, ...)
Arguments
object |
A fitted |
... |
Not used. |
Value
A numeric vector of length object$n. For a GWR, NA
where the values cannot be read from the engine. For a Bayesian GP, a
posterior that cannot be drawn is an error, as is a family with a
probability per response category (ordinal, categorical), which has no
single fitted value per row.
The Bayesian GP cache
brms::posterior_epred() takes time in proportion to the number of
draws times the number of rows, and summary(), residuals(),
model_metrics() and compare_models() each call
fitted(), so the values are kept in an environment carried in
object$info$.cache. The cache holds the expected values only, so
predict(object, summary = "median") and
predict(object, type = "predict") recompute from the posterior.
The entry records the n and a digest of the training data it was
computed from, and is recomputed when either differs, so a copy given
other data does not read the original's values. It is also tied to the
sampling run: a refit or update() of the brmsfit recomputes.
A brmsfit edited in place is what clear_fitted_cache()
is for. A copy made with fit2 <- fit shares the environment, so
clear_fitted_cache() on one empties the cache of both (the other
recomputes), and identical() cannot tell two fits apart by their
caches. The entry holds the values and a small identifier of the
sampling run, so a fit saved with saveRDS() after fitted()
is no larger for it.
See Also
residuals() on the same fits
(spatial_fit-residuals), and model_metrics().
Other fit methods:
plot.spatial_fit(),
print.spatial_fit(),
spatial_fit-coef,
spatial_fit-predict,
spatial_fit-residuals,
summary.spatial_fit()
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)
gw <- fit_gwr_model(pts, "z", "a", bandwidth = 30)
# Out-of-bag for the forest, in-sample for the GWR.
head(cbind(z = pts$z, rf = fitted(rf), gwr = fitted(gw)))
Predict from a fitted model
Description
predict() has a method for each backend: a random forest
(rf_fit), a GWR (gwr_fit) and a Bayesian GP
(bayesian_fit) fit. Every method reads newdata the same
way: a layer without a CRS is read the way
the training data were (see "Layers without a CRS" in
spatialkit-geometry), the layer is transformed to the CRS used at
fitting time, a feature that is not a point is reduced to one, and a row
with a missing or non-finite predictor or no location gets NA. A
layer that mixes XY with XYZ or XYM geometries is read in x and y. The
response need not be present. With newdata = NULL each method
returns the fit's own fitted values: out-of-bag predictions for a random
forest, in-sample values for the others.
Usage
## S3 method for class 'gwr_fit'
predict(object, newdata = NULL, se.fit = FALSE, ...)
## S3 method for class 'bayesian_fit'
predict(
object,
newdata = NULL,
summary = c("mean", "median"),
type = c("epred", "predict"),
draws = FALSE,
...
)
## S3 method for class 'rf_fit'
predict(object, newdata = NULL, ...)
Arguments
object |
A fitted |
newdata |
An sf object carrying the predictors, or |
se.fit |
GWR only. Logical; also return standard errors. Default
|
... |
For a random forest, passed to ranger's predict method;
any other name is an error. Arguments that make ranger return a
matrix ( |
summary |
Bayesian GP only. |
type |
Bayesian GP only. |
draws |
Bayesian GP only. |
Details
A random forest predicts with ranger's predict method. A GWR solves
one local regression at each new location, with the fit's kernel and
bandwidth (an adaptive bandwidth counts neighbours among the training
points), and returns x^\top\hat\beta(u). The local
regressions are weighted least squares solved by the pivoted QR
fit_gwr_model() uses: on a window of full rank the values
equal those of GWmodel::gwr.predict() to rounding error, and at a
training location with that row's own predictors they equal
fitted(). Each location stands alone, so one that cannot be
estimated does not affect the others. A Bayesian GP fit applies the
coordinate scaling and predictor standardisation stored at fit time and
then calls brms::posterior_epred() or
brms::posterior_predict().
Value
For a random forest, a numeric vector aligned to
nrow(newdata), with NA for rows dropped as incomplete (all
NA, with a WARN line in the log, when every row is). The forest
in fit$engine predicts (y - fit$info$response_centre) /
fit$info$response_scale (see the Value section of
fit_rf_model()); this method puts the centre and scale
back. A failure inside ranger's predict method is an error.
For a GWR with se.fit = FALSE, a numeric vector aligned to
nrow(newdata), with NA for rows dropped as missing or
non-finite and for locations whose local regression cannot be estimated
(see "When a GWR prediction is NA"). If the design matrix for
newdata cannot be built, every value is NA and a warning
says why. When the training data were read as longitude and latitude,
a CRS-less newdata with an x outside -180 to 360 or a y beyond 90
north or south stops the call. With se.fit = TRUE, a list:
fit (that vector), se.fit (the standard error of the
fitted value, \hat\sigma\sqrt{s^\top s} with s the weights
the local regression puts on the training responses), se.pred
(the standard error of a new observation there,
\hat\sigma\sqrt{1 + s^\top s}, the square root of
GWmodel::gwr.predict()'s prediction variance),
residual.scale (\hat\sigma, from the fit's residual sum of
squares over its effective degrees of freedom) and df (those
degrees of freedom). The standard errors treat the bandwidth as known
and the local model as true at each location; they do not measure the
bias of a local fit and are NA where the prediction is.
For a Bayesian GP fit, a numeric vector of length nrow(newdata),
or an n_draws by nrow(newdata) matrix with
draws = TRUE, in the units of the response (see "The response's
centre and scale" in fit_bayesian_spatial_model()). Rows
with a missing or non-finite predictor or coordinate, and rows carrying
a level the model was not fitted with, are NA (an NA
column with draws = TRUE). If the posterior draw fails the
result is all NA (a one-row matrix for draws = TRUE) with a
warning of class spatialkit_predict_failed that gives the cause.
An ordinal or categorical family is an error under
type = "epred": its expected value is a probability per response
category. Use type = "predict", draws = TRUE for posterior draws
of the predicted category, as category indices; the share of draws in
each category estimates its probability. Without draws = TRUE,
type = "predict" returns the mean (or median) category index, an
expected rank for an ordinal family and an error for
brms::categorical(), whose categories have no order. With
newdata = NULL the cached fitted() values are returned only
for the default summary = "mean", type = "epred",
draws = FALSE; any other combination is recomputed against the
training data, because the cache holds the expected values only.
Random forest predictors
A categorical predictor must not carry a level the forest was grown
without, meaning a level with no training rows, not only one absent from
levels(): an ordinary subset, or a spatial fold that holds out a
whole class, keeps the unused level while the forest has no split for it.
An unseen level is an error. A predictor that was numeric or logical when
the forest was grown must arrive numeric or logical: ranger would
otherwise code a character column as a factor and apply the numeric split
thresholds to the codes, so a character column is refused. (ranger
reads a logical as 0/1, so either form is accepted for one.)
When a GWR prediction is NA
A prediction is returned when it is estimable from the training points
that carry weight at the new location, and is NA otherwise:
no training point carries weight there (a location beyond a fixed bisquare, tricube or boxcar bandwidth);
the training points in the window cannot place the new row: a predictor is constant among them at a value other than the new row's (a regional indicator, at a location whose window lies wholly in another region), or fewer of them carry weight than the new row needs.
Where a predictor is constant in the window at the new row's own value,
its coefficient is not needed and the prediction is returned. The
decision uses the rule and the tolerance of the fit (see "The local
solve" in fit_gwr_model()). A warning of class
"spatialkit_gwr_not_estimable" counts the NA predictions; it
carries n_na, n and n_empty.
GWR locations beyond the reach of the fit
An adaptive bandwidth always finds its neighbours, and a Gaussian or an
exponential kernel weights every training point, so a location far from
the data still gets a number: the local regression of training points
that are all far away, extrapolated. When a new location's nearest
training point is farther than the widest kernel used at any training
location reaches, the prediction is returned and a warning of class
"spatialkit_gwr_extrapolation" counts those locations and gives
the range of their distances. The widest kernel is the largest distance
from a training point to its bandwidth-th nearest neighbour
(object$info$max_kernel_width), or the bandwidth itself when it is
fixed. A bisquare, tricube or boxcar kernel reaches as far as its width;
a Gaussian or exponential kernel has no edge, and its reach is taken as
three widths. The check is on distance alone and is lenient: a location
just outside the data is not flagged. The warning carries n_far,
n, reach and nearest (the smallest and largest
distance to a nearest training point).
Each call raises the warning once, with its own counts.
predict_surface(), cv_gwr(),
cv_spatial(), cv_block_size_sweep() and
select_features_forward() predict in pieces and raise one
warning per call with the totals. A cross-validation gives the smallest
and the largest reach among its folds, and a sweep counts a location once
for each fit that put it out of reach. A loop of your own over
predict() gets one warning per call; the example below totals them
with a handler. To drop the warning where extrapolation is intended, use
suppressWarnings(predict(fit, newdata), classes =
"spatialkit_gwr_extrapolation").
Bayesian GP boundary
brms 2.17 to 2.22 do not store the Hilbert-space boundary L in a
fitted GP basis, and recompute it from whatever rows predict() is
handed. This method therefore appends two rows at the training
coordinate extrema before the posterior draw and drops them from the
result, and when newdata reaches past the training range it scales
down the c of the gp() term by as much as the range grew, so
brms rebuilds the boundary the model was fitted with. A prediction does
not depend on which other rows share the call: chunked, fold-wise and
single-call predictions agree, and predict_surface() does not
depend on chunk_size. brms 2.23.0 and later store L and
reuse it; there c is left alone and the two extra rows change
nothing.
Predictions outside the training coordinate envelope are extrapolation, and
a line in the log says so. A row further than L from the centre of
the training coordinates on either axis is past the edge of the basis,
where the approximate GP is an odd reflection of the fitted surface, so it
is returned as NA (a column of NA with draws = TRUE)
with a warning. The default boundary factor puts that edge well outside
the training data.
Bayesian GP categorical predictors
A factor or character predictor is handed to brms with the levels the
model was fitted with: the values that occur in the training rows
(object$info$predictor_levels). A newdata factor that only
lists an extra level, or a model fitted on a subset whose factor kept an
unused level, is predicted as usual. A row whose value is not among the
fitted levels has no prediction: it is returned as NA, the other
rows are predicted, and one warning of class spatialkit_new_levels
names the predictor, the levels and the number of rows. The result does
not depend on which other rows share the call.
See Also
predict_surface() to predict onto a grid, and
area_of_applicability() to mark where the predictions
apply.
Other fit methods:
plot.spatial_fit(),
print.spatial_fit(),
spatial_fit-coef,
spatial_fit-fitted,
spatial_fit-residuals,
summary.spatial_fit()
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)
new <- pts[1:5, ]
new$z <- NULL # the response is not needed
rf <- fit_rf_model(pts, "z", "a", num_trees = 50, seed = 1)
predict(rf, newdata = new)
gw <- fit_gwr_model(pts, "z", "a", bandwidth = 30)
str(predict(gw, newdata = new, se.fit = TRUE))
# A point 4 km east of the data is beyond the reach of every kernel. A
# handler totals the extrapolation warnings of several calls; the log
# lines still print (spatialkit_quiet() turns them off).
far <- st_as_sf(data.frame(x = 5.05e5, y = 5e6 + 500, a = 0),
coords = c("x", "y"), crs = 32632)
total <- 0
withCallingHandlers(
for (i in 1:2) predict(gw, newdata = far),
spatialkit_gwr_extrapolation = function(w) {
total <<- total + w$n_far
invokeRestart("muffleWarning")
})
total
Extract the residuals of a fitted model
Description
residuals() 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.
Usage
## S3 method for class 'gwr_fit'
residuals(object, ...)
## S3 method for class 'bayesian_fit'
residuals(object, ...)
## S3 method for class 'rf_fit'
residuals(object, ...)
Arguments
object |
A fitted |
... |
Not used. |
Value
A numeric vector of length object$n.
See Also
Other fit methods:
plot.spatial_fit(),
print.spatial_fit(),
spatial_fit-coef,
spatial_fit-fitted,
spatial_fit-predict,
summary.spatial_fit()
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
Warnings and errors the package raises
Description
Every condition class the package raises, with the functions that raise it, what it means, what to do and the fields it carries. Each class can be caught by name.
Catching a condition by class
Each condition below is an R warning or error whose class vector starts
with the class named, followed by "warning" or "error" and
"condition". A handler named after the class catches it without
matching the message, and reads its fields with $:
w <- tryCatch(determine_optimal_levels(pts),
spatialkit_no_elbow = function(w) w)
w$k
withCallingHandlers() with invokeRestart("muffleWarning"), or
suppressWarnings(expr, classes = ), lets the call finish and drops the
warning. options(warn = 2) turns every warning into an error.
Some warnings and errors carry no class of the package's own, such as
the refusal of an argument of the wrong type. Catch those with
warning = or error =.
Warnings and log lines
The package also writes a log through logger: a trace in a
temporary file, and a console echo of every line at the WARN level and
above. A log line is not an R condition. tryCatch(warning = ) does not
catch it, and suppressWarnings() does not silence it. Where a help page
says a function raises a warning, it means an R warning; where it says
the function logs one, it means a log line. spatialkit_quiet() turns
the console echo off.
The package writes a classed warning to the log as well as raising it, so a warning muffled by a handler still prints its log line until the echo is turned off.
Condition classes
Each entry gives the class, the functions that raise it, what it means
and what to do, and then the fields a handler reads with $. Each is a
warning unless marked as an error. An entry without fields is a
condition that carries only its message.
-
spatialkit_aoa_zero_threshold. Raised byarea_of_applicability()withfolds. The dissimilarity threshold is 0: held-out rows have exact copies on the training side of their fold. Use folds that keep copies together, such asmake_folds(method = "leave_location_out", group_var = ). -
spatialkit_bound_chosen. Raised byget_voronoi_seeds(),voronoi_seeds_kmeans()andbuild_tessellation(), given a profile or a selection as the count. The optimum sits on a bound of the ladder, so a bound of the ladder set the count. Readedgein theselect_resolution()result;resolution_profile()describes the bounds. Fields:edge,criterionandn. -
spatialkit_cells_degenerate(error; a warning fromensure_stable_poly_id()). Raised bybuild_tessellation(),create_voronoi_polygons(),create_grid_polygons(),clip_target_for(),get_voronoi_seeds(),voronoi_seeds_random(),make_folds(),assign_features_to_polygons(),summarize_by_cell(),cell_values_at()andensure_stable_poly_id(). s2 refuses a cell or a boundary row in lon/lat even after repair, or a boundary in a geographic CRS has a vertex beyond latitude 90. Fromensure_stable_poly_id(): the repair left a row with no polygon. Transform the layer to a projected CRS; for a latitude beyond 90, check its CRS. Fields:rows,nandreasons; the error also carriesparent,repairedands2_forced, and some steps addsite,causeorfeatures_rows. -
spatialkit_cells_differ. Raised bysummarize_by_cell(). The rows or cells given are not those the count was scored on;whatsays which check differs. Summarise the layer the count was chosen on, assigned to the cells built from that selection. Fields:what,scoredandfound, andfieldfor the count record. -
spatialkit_constant_predictor. Raised byprep_model_data(), and so by every fitter andcv_*()function. A predictor takes one value in every row kept, so its coefficient cannot be told from the intercept. Drop it frompredictor_vars. -
spatialkit_constant_response. Raised byresolution_profile(). The scored variable is constant to within rounding, socp,moran_iandmoran_zareNAat every level. Check the response. Withpredictor_vars, a response the predictors fit exactly leaves constant residuals. Fields:n. -
spatialkit_convergence. Raised byfit_bayesian_spatial_model(),cv_bayes()andcv_spatial(). The sampler's diagnostics fail (divergent transitions, R-hat, effective sample size or E-BFMI), andconvergence_okisFALSE. Raiseadapt_deltafor divergent transitions; run more iterations for R-hat and effective sample size. Fields:failed, and from cross-validation alsofoldsandfold_messages. -
spatialkit_cp_noise. Raised byresolution_profile().cpdoes not take the variogram's nugget as it stands, or has no noise variance and isNAat every level. Readattr(, "cp_noise")for the variancecpused and its source. Fields:source,value,level,cap,uncapped_sourceanduncapped_value. -
spatialkit_deff_fallback. Raised bysummarize_by_cell(). The design effect requested was not the one applied: a"variogram"request fell back to Kish's, or a number given was refused. Read thedeff_methodcolumn;deff_method == "variogram"keeps the rows the variogram corrected. Fields, for a"variogram"request:requestedandused. -
spatialkit_deff_no_structure. Raised bysummarize_by_cell(). The variogram of the response found no spatial structure, so the predictor columns named get a design effect of 1 from a verdict about the response. Usedeff = "kish"to give each predictor its own ICC. Fields:columnsandreason. -
spatialkit_diagnostic_criterion(error). Raised byselect_resolution().criterion = "moran_z"was asked for withoutdiagnostic = TRUE.moran_zis a diagnostic of the cell means, whichselect_resolution()reads only underdiagnostic = TRUE. Passdiagnostic = TRUE, or choose another criterion. -
spatialkit_diagnostic_ranking. Raised bydetermine_optimal_levels()withcriterion = "morans_i". The candidates are ranked by Moran's z of the cell means, a diagnostic of the cells. Usecriterion = "geometric", orresolution_profile()when the response should drive the count. Fields:k,criterion,first_computableandwindow. -
spatialkit_empty_cells. Raised byresolution_profile(),get_voronoi_seeds()andvoronoi_seeds_kmeans()withpartition = "density". A centre holds no point, so fewer cells are occupied than the count. It happens at high counts, mostly from random starts. k-means++ starts (init = "kmeans++") leave a cell empty less often. Fields:levelandempty. -
spatialkit_estimate_mismatch. Raised bysummarize_by_cell(). The summary reports another cell value than the count was chosen for: plain means against pooled values, or the reverse. Report the value the count was chosen for, or choose the count for the value you report. Fields:chosen_for,reported,ruleandcells. -
spatialkit_features_degenerate(error). Raised bycoerce_to_points(),prep_model_data(),assign_features_to_polygons()andcell_values_at(). s2 refuses a polygon of the features in lon/lat, GEOS puts the centroid of an invalid feature outside it, or a temporary projection leaves a line empty. Transform the features to a projected CRS, choose anothermodeincoerce_to_points(), or repair them withsf::st_make_valid(). Fields:rows,n,reasons,parent,repairedands2_forced, and some steps addsite,crsorauto_helps. -
spatialkit_few_residuals. Raised bysummarize_by_cell()withobs_level. Fewer than five residuals are expected beyond each end of the interval (at 0.90, fewer than 100 residuals), so its ends are unstable. Ask for a lowerobs_level, which needs fewer residuals. Fields:columns,needed,levelandn. -
spatialkit_floor_above_ceiling. Raised byresolution_profile(). The range floor lies above the ceiling thatsample_nsets, though the layer supports it, so the floor is above every level and is not applied, andselect_resolution()cannot holdreliabilityto it.supportedstaysTRUE. Raisesample_n. Fields:reason,floor,ceiling,nandn_sample. -
spatialkit_fold_args_ignored. Raised bycv_spatial(),cv_rf(),cv_gwr(),cv_bayes()andcompare_models_cv().block_sizeorauto_range = TRUEwas given besidefolds, which leaves them nothing to size. Drop them, or leave outfoldsso the function builds the blocks. -
spatialkit_gp_adequacy. Raised byfit_bayesian_spatial_model(),cv_bayes()andcv_spatial(). The basis of the Bayesian GP is too coarse: the posterior asks for a shorter length-scale than it resolves, or the residuals are autocorrelated at short range. Follow the message: a finer basis (gp_k,gp_resolution) or, at its cap, kriging or a model of cell means. Fields, from cross-validation:foldsandfold_messages. -
spatialkit_gp_basis_size. Raised byfit_bayesian_spatial_model(),cv_bayes()andcv_spatial(). Fewer than one row per ten basis functions, so most basis weights are set by their prior. A smallergp_kis cheaper and resolves less; with this few rows kriging fits the same kind of model. Fields, from cross-validation:foldsandfold_messages. -
spatialkit_gp_resolution. Raised byfit_bayesian_spatial_model(),cv_bayes()andcv_spatial(). A variogram fitted before compiling puts the response's range below what the basis resolves, and the response's autocorrelation agrees. The check after sampling tests this estimate. The message gives the basis size that would resolve the range. Fields, from cross-validation:foldsandfold_messages. -
spatialkit_gwr_extrapolation. Raised bypredict.gwr_fit(),predict_surface(),cv_gwr(),cv_spatial(),cv_block_size_sweep()andselect_features_forward(). New locations lie beyond the reach of the widest kernel; they are predicted and counted. Where extrapolation is intended, usesuppressWarnings(expr, classes = "spatialkit_gwr_extrapolation"). Fields:n_far,n,reach,reach_text,nearestandcalls. -
spatialkit_gwr_not_estimable. Raised bypredict.gwr_fit(),predict_surface(),cv_gwr(),cv_spatial(),cv_block_size_sweep()andselect_features_forward(). The local regression at a new location cannot be estimated, so its prediction isNA.predict.gwr_fit()says when a window cannot be estimated. Fields:n_na,n,n_empty,bw_textandcalls. -
spatialkit_gwr_rank_deficient. Raised byfit_gwr_model(). Some local windows have deficient rank, and their coefficients areNA; the fitted values are returned. Where many windows hold a predictor constant, fit it as one global coefficient (a mixed GWR, asGWmodel::gwr.mixed()fits). -
spatialkit_gwr_repeated_locations. Raised byfit_gwr_model()andgwr_model_selection(). Rows share coordinates. AICc counts them as independent, so a bandwidth left to the search (bandwidth = NULL) is chosen by leave-one-location-out error, and the AICc gaps between models make what a predictor adds look larger than it is. Read "Observations that share a location" infit_gwr_model(). -
spatialkit_icc_unavailable. Raised bysummarize_by_cell(). A column's Kish ICC cannot be estimated, so its standard errors and intervals areNAin cells of two or more observations.attr(, "icc")$reasonsays why. Fields:columnsandreason. -
spatialkit_k_reduced. Raised bymake_folds(), and the functions that build folds with it. Fewer folds were made than asked for. Readkin the result; the message gives the reason and a setting that works. Fields:k_requestedandk. -
spatialkit_knndm_short_of_target. Raised bymake_folds()withmethod = "knndm". The held-out points sit closer to their training data than the prediction points do, so the cross-validated error tends to read low. Use fewer folds; each then holds out a larger part of the layer. Fields:held_out_meanandtarget_mean. -
spatialkit_ladder_unused. Raised byresolution_profile(). A numericobs_per_cellsets the ladder, so then_levels,min_cell_n,sample_norrange_floor = TRUEalso given are not read. Passobs_per_cellor those arguments, not both. Fields:unusedandobs_per_cell. -
spatialkit_lat_beyond_90. Raised bycoerce_to_points()andensure_stable_poly_id(). Rows of a layer in a geographic CRS have a vertex at a latitude beyond 90, which is no place on the Earth.coerce_to_points()gives them an empty point;ensure_stable_poly_id()keys them as empty polygons and returns them as they came. Check the layer's CRS and the order of its coordinates. Fields:rowsandn. -
spatialkit_moran_skipped. Raised byresolution_profile(). A level has more than 5,000 cells holding a scored row while FNN cannot be loaded or Matrix is not installed, somoran_iandmoran_zareNAthere. Install Matrix, or reinstall FNN. Fields:limit,levelsandmissing. -
spatialkit_new_levels. Raised bypredict.bayesian_fit(). Rows carry a level of a categorical predictor that the model was not fitted with, so their predictions areNA. The warning names the predictor, the levels and the number of rows. -
spatialkit_nndm_out_of_reach. Raised bymake_folds()withmethod = "nndm"or"knndm". The prediction points sit nearer to the data than any fold can hold a point out, so the cross-validated error is pessimistic for them. No fold setting closes the gap; read the score as an upper bound on the error at those points. Fields:deficit,toleranceandseparated. -
spatialkit_no_cover. Raised bybuild_tessellation()andcreate_voronoi_polygons(). Seeds came with neither a boundary nor a cover, so their cells cover only the seeds' own hull. Pass the study area asboundary, or the observations ascover. -
spatialkit_no_default_criterion(error). Raised byget_voronoi_seeds(),voronoi_seeds_kmeans()andbuild_tessellation(). A profile passed as the count hascp, the criterion a profile is read by,NAat every level while another criterion is finite. Passselect_resolution(profile, criterion = )with a finite criterion, or a number. -
spatialkit_no_elbow(an error underon_no_elbow = "error"). Raised bydetermine_optimal_levels(). The WSS curve has no elbow, or the ladder is too short to show one, so the count it gives is set by the ladder. Choose the count on other grounds, such asresolution_profile()with a response. Fields:k,sagandstructured. -
spatialkit_no_scored_rows. Raised byresolution_profile(). No row of the selection half has a response (select_on = "split"), or no row has a response and every predictor, so the columns that read those rows areNAat every level.reasonsays which; check where the rows with a response and every predictor lie. Fields:reason,n,selection,n_responseandcolumn. -
spatialkit_no_structure. Raised byget_voronoi_seeds(),voronoi_seeds_kmeans(),build_tessellation()andsummarize_by_cell()withestimate = "pooled". One cell for the whole layer does as well (structuredisFALSE), so the cell values say little that one mean does not. The call goes on with the count. The message says which test failed, and whether a size set the count; see "Pooled values" insummarize_by_cell(). Fields:criterion,nandone_cell, and fromsummarize_by_cell()alsocolumns,estimate,loo,structure_pandbeats. -
spatialkit_nonfinite. Raised bysummarize_by_cell().Infor-Infin a response or predictor column is treated as missing in every statistic of that column;nstill counts the row. The warning names the columns and gives the rows and cells affected. Fields:nandcolumns. -
spatialkit_not_converged. Raised byresolution_profile(),get_voronoi_seeds()andvoronoi_seeds_kmeans(). The start kept was cut off at the iteration limit, so a longer run could still move points between cells. Raiseiter_max(kmeans_iteringet_voronoi_seeds()). Fields:level,iteranditer_max. -
spatialkit_not_supported. Raised byresolution_profile().supportedisFALSE: the range floor exceeds the ceiling, fewer than two cells meetmin_cell_n, or the points sit on one location.attr(x, "bounds")gives the floor, the ceiling andceiling_from. Fields:reason,nandmin_cell_n, andobs_per_cellfor a ladder of sizes. -
spatialkit_partition_unused. Raised byget_voronoi_seeds()andvoronoi_seeds_kmeans(). Given a profile or a selection, the call also named apartition,initor density setting other than the profile's; the scored centres are returned. Pass the count as a number (n = sel$best) for a fresh k-means. Fields:kindandinit. -
spatialkit_pool_degenerate. Raised bysummarize_by_cell()withestimate = "pooled". The pooled values carry no pooling: one cell, no spread inside any cell, or no signal between cells.reasonsays which case applies. Fields:reasonandcolumns, withn,constantorsigma2by case. -
spatialkit_pool_few_cells. Raised bysummarize_by_cell()withestimate = "pooled". The column has 2 to 9 cells, so each target is the mean of all the other cells, and a pooled value can land on the far side of the overall mean from its plain mean. With 10 cells or more each target is the mean of the observations in the 8 nearest cells. Fields:columns,cellsandown_weight. -
spatialkit_pool_few_df. Raised bysummarize_by_cell()withestimate = "pooled". The spread inside the cells (sigma2), which every own weight rests on, comes from fewer than 30 values beyond one per cell. Fewer cells leave more values beyond one per cell. Fields:columns,needed,df,nandcells. -
spatialkit_pool_rows_skipped. Raised bysummarize_by_cell()withestimate = "pooled". Rows with a value and a cell have no location; they count innand the plain columns and take no part in the pooled ones. See "Rows without a location" in spatialkit-geometry. Fields:n,cellsandcolumns. -
spatialkit_pool_unavailable. Raised bysummarize_by_cell()withestimate = "pooled"andresolution_profile()with anestimate. The pooled columns (in a profile,loo,loo_seandown_weight) areNA;reasonsays why. The plain columns are returned. For"values out of range", divide the column by a power of ten; for"work limit", see spatialkit-options. Fields:reasonandcolumns, withnandcells, orwork,limitandcells, by reason. -
spatialkit_predict_failed. Raised bypredict.bayesian_fit(). The posterior draw failed, and every prediction isNA. The message gives the cause. -
spatialkit_repeated_locations. Raised bysummarize_by_cell()withobs_levelandresolution_profile()with anestimate. Rows share a location, so the interval orloodescribes a further observation at a place already observed. Fields:n, the rows that share a location, andtotal, the rows read, withcolumnsfromsummarize_by_cell()orcolumnfromresolution_profile(). -
spatialkit_replicate_var_above_nugget. Raised bykriging_adequacy(). The replicates at one location vary between visits more than the variogram's nugget allows; their variance is used as it is. Refit the variogram with a nugget of at least the replicate variance. Fields:within_varandnugget. -
spatialkit_response_ceiling. Raised byresolution_profile(). Rows that are not scored (no response, or a predictor missing) lowered the ceiling on the count. The message names the bound in force. Fields:n,n_response,ceiling,ceiling_from,n_sampleandn_scored. -
spatialkit_response_imprecise. Raised byprep_model_data(), and so by every fitter andcv_*()function, and byestimate_sac_range(),kriging_adequacy()andselect_features_forward(). The response lies so far from zero that doubles there are spaced more than a millionth of its standard deviation apart, and every mean is rounded to that spacing. Subtract a constant from the response first. Fields:spacingandspread. -
spatialkit_response_scale. Raised byfit_bayesian_spatial_model().priorsets a prior on the response's scale, so a response far from zero, or with a standard deviation far from 1, is handed to brms as it is. See "The response's centre and scale" infit_bayesian_spatial_model(). -
spatialkit_rows_dropped. Raised byprep_model_data(), and so by every fitter andcv_*()function, and bygp_lengthscale_bounds(). Rows were dropped for a missing or non-finite value or for having no location. The message gives the counts and how far the dropped rows' mean response sits from the kept rows'. When that difference is large, the fit is biased towards the complete rows. Fields, fromgp_lengthscale_bounds():nandwhich. -
spatialkit_rows_unplaced. Raised byensure_projected(),harmonize_crs(),plot_tessellation_map(), and the other functions that move a layer into another CRS. The target CRS cannot place a row in full, so the row comes back empty or without those vertices. Correct or drop those rows. Fields:rowsandn. -
spatialkit_sd_overflow. Raised bysummarize_by_cell(). A cell's standard deviation is beyond the largest double, so its..sd_*isInfand its standard errors and interval areNA. Divide the column by a power of ten. Fields:columnsandcells. -
spatialkit_size_not_reached. Raised byresolution_profile(),select_resolution()andget_voronoi_seeds(). A size does not give the count it asks for (fewer than two cells, or more than k-means can place), and the nearest level is used. Fields:obs_per_cell,wantedandused, the two counts, andreason. -
spatialkit_surface_point_off. Raised bycoerce_to_points(). The point GEOS takes on a lon/lat polygon spanning more than 180 degrees of longitude does not lie on it read on the sphere, and that point is kept. Transform the layer to a projected CRS that holds the polygon, and call again. Fields:rows. -
spatialkit_ties_unresolved. Raised byassign_features_to_polygons(). Thetie_breakrule names no polygon for some features, since the polygons are equal on every key; those features getNA. They are kept or dropped askeep_unassignedsays. Fields:nandtotal. -
spatialkit_unassigned. Raised byassign_features_to_polygons(),build_tessellation()andcreate_voronoi_polygons(). Features fall inside no polygon, or points or seeds lie outside every cell. Give the cells aboundaryorcoverthat reaches the data;keep_unassigned = TRUEkeeps such features withNA. Fields:nandtotal. -
spatialkit_variogram_unusable. Raised byresolution_profile(). The variogram gives no usable range, soreliabilityisNA.reasongives therejected_reasonofestimate_sac_range(). Fields:reason,converged,nuggetandnugget_used. -
spatialkit_work_limit(error). Raised byresolution_profile()andcell_values_at(). A search or a fit would make more comparisons than an option allows. The message says what to change; see spatialkit-options. Fields:work,limitandwhat, and for a fit alsokind,init,nstartandfnn. -
spatialkit_xy_imprecise. Raised byassign_features_to_polygons(),build_tessellation(),create_voronoi_polygons(),create_grid_polygons(),clip_target_for(),make_folds(),estimate_sac_range(),fit_gwr_model()andresidual_morans_i(). The coordinates lie so far from the origin of their CRS that doubles there are spaced more than a millionth of the extent apart, or a distance lies past a tie by less than that rounding. The call runs on the rounded coordinates. Subtract a constant from the coordinates; see "Coordinates far from the origin" in spatialkit-geometry. Fields:spacing, andextentordistance. -
spatialkit_xy_imprecise_error(error). Raised byclip_target_for(). At that rounding the buffer comes back empty or with no area. Shift the points nearer the origin, or passboundary. -
spatialkit_zm_dropped. Raised byensure_projected(),harmonize_crs(),coerce_to_points(),assign_features_to_polygons(),get_voronoi_seeds(),ensure_stable_poly_id(),predict_surface()andarea_of_applicability(). A layer that mixes XY and XYZ (or XYM) geometries came back in XY, orcoerce_to_points()reduced geometries that carry M in x and y. See "Mixed dimensions, Z and M" in spatialkit-geometry. Fields:rows, the rows that carried Z or M.
See Also
spatialkit_quiet() for the console log, spatialkit-options
for the work limits, spatialkit-geometry for the rules behind the
geometry classes, and vignette("troubleshooting", package = "spatialkit") for the messages met most often.
Other options and caches:
clear_fitted_cache(),
clear_grid_cache(),
spatialkit-options,
spatialkit_quiet()
Examples
library(sf)
set.seed(1)
# Points spread evenly have no elbow.
pts <- st_as_sf(data.frame(x = 5e5 + runif(200, 0, 100),
y = 5e6 + runif(200, 0, 100)),
coords = c("x", "y"), crs = 32632)
# Catch the warning by its class and read its fields.
w <- tryCatch(determine_optimal_levels(pts, max_levels = 6),
spatialkit_no_elbow = function(w) w)
class(w)
w$k
# Let the call finish without the warning; the log line still prints
# until the console echo is off.
old <- spatialkit_quiet()
k <- suppressWarnings(determine_optimal_levels(pts, max_levels = 6),
classes = "spatialkit_no_elbow")
spatialkit_quiet(old)
k
How input geometry is read
Description
The rules the package applies to the spatial layers it is given: how two layers are brought into one CRS, how a layer without a CRS is read, how mixed dimensions and rows without a location are handled, what a boundary needs, and what s2 refuses in longitude and latitude. A function's own page says how it applies them: which of its arguments they cover, and whether a row it leaves out is reported by a warning or in the log.
Coordinate reference systems
A function that takes two layers, such as points and a boundary or
features and cells, brings them into one CRS before it reads either.
harmonize_crs() is the rule in its plain form: when both layers have a
CRS, one is transformed into the other's; a layer without one is read by
the test in "Layers without a CRS" and then reprojected or stamped, with
a warning.
A function that measures distances moves a lon/lat layer into the
projected CRS ensure_projected() chooses from the layer's extent: the
UTM zone for a local extent, otherwise the candidate that distorts
distances least (its page gives the cases). A layer that already has a
projected CRS is used as it is. Distances, and arguments given as
distances, are in the units of the CRS the function works in, which its
page names. For a lon/lat layer the function projects, that is the CRS
ensure_projected() chose, whose unit is the metre.
Layers without a CRS
A layer without a CRS is read by a test of its coordinates. When their
bounding box lies within longitude -180 to 180 and latitude -90 to 90,
and they either span more than one unit on some axis or carry the
decimal places of degrees, they are taken as EPSG:4326, with a warning.
Otherwise they are left as they are. A small planar survey inside that
box is read as degrees, so set the CRS of such a layer with
sf::st_crs(x) <- ... before passing it.
Given a CRS to read the layer in (target_crs, or the CRS of a second
layer), coordinates the test takes for degrees are reprojected from
EPSG:4326, and the others are stamped with that CRS and not moved. A
stamp is a relabel: check that the coordinates are in that CRS. A CRS in
longitude and latitude is never stamped on coordinates that cannot be in
it. An x outside -180 to 360, or a y beyond 90 north or south, stops the
call with an error that gives the bounding box of the coordinates.
Mixed dimensions, Z and M
sf reads a layer in the dimension of its first geometry, and GEOS
refuses M. A function that moves a layer into another CRS and returns
it, or reduces it to points, reads a layer that mixes XY and XYZ (or
XYM) geometries, as rbind() of an XY and an XYZ layer gives, in x and
y. It returns that layer in XY, with a warning of class
spatialkit_zm_dropped (its page names any exception). A layer in one
dimension, XYM and XYZM included, is moved with its Z and M, and so is a
layer whose only geometries of another dimension than the first are
empty and not points.
A layer a function only reads for its x and y, such as a boundary or
the points and cover of a builder, is read in x and y when it mixes
dimensions or its geometries carry M (XYM or XYZM). coerce_to_points()
reduces a geometry that carries M in x and y as well, with the same
warning; its page gives the exceptions.
Rows without a location
A row has no location when its geometry is empty, or one of its
coordinates is not finite or lies beyond 1e150. Such a row takes no part
in the choice of a projection, and its coordinates none in the lon/lat
test. Moved into another CRS, it comes back empty, in its own geometry
type. sf::st_transform() alone would drop the vertex it cannot move,
or put a coordinate beyond 1e150 at a finite place, and return the rest
of the feature.
In a geographic CRS a vertex at a latitude beyond 90 is no place on the
Earth. A row with one takes no part in the choice of a projection either.
coerce_to_points(), prep_model_data() and the fits, the points of the
k-means seeders, the features of assign_features_to_polygons(), the
pooled columns of summarize_by_cell() and cell_values_at(), and
ensure_stable_poly_id() read such a row as a row without a location.
coerce_to_points() and ensure_stable_poly_id() say so with a warning
of class spatialkit_lat_beyond_90 that names the rows.
A row that has a location and that the target CRS cannot place in full
comes back empty, or without the vertices that CRS cannot place, with a
warning of class spatialkit_rows_unplaced that names the rows.
What a function does with such a row (drops it, keeps it with NA, or
leaves it out of one step) is on its page.
Boundaries
A boundary is a polygonal sf or sfc layer: the study area that cells are clipped to, that seeds are drawn in, or that fold blocks are cut from.
When exactly one of the data layer and the boundary has a CRS, the other is read in it, with a warning. A boundary without a CRS given with lon/lat points is read as lon/lat when its coordinates fit longitude and latitude, and refused with an error otherwise.
A row that is empty, or has a coordinate that is not finite or lies beyond 1e150, read as given and again after any move into another CRS, covers no ground and is left out. A boundary with no such row left is refused with an error that says so.
A boundary in a geographic CRS with a vertex at a latitude beyond 90 is refused with an error of class
spatialkit_cells_degeneratethat names its rows and says to check its CRS.A row the repair of the boundary leaves without a polygon (a ring with no height: every vertex on one line, or in degrees on one parallel) is left out as well, and a boundary with no polygon left is refused.
A boundary that mixes dimensions or carries M is read in x and y.
get_voronoi_seeds() adds the rules for drawing points inside a
boundary, and make_folds() the rule for a block the boundary only
touches.
Polygons in degrees
With s2 on (sf::sf_use_s2(), sf's default), sf reads polygons in
longitude and latitude on the sphere, and s2 refuses a polygon that is
not valid there: one whose edges cross, or with two corners it reads as
one point. Cells returned in lon/lat can hold two such corners. This
happens where four Voronoi seeds stand the same distance from one point,
and the transform to degrees puts two corners that differ only by
rounding at one point (see crs in create_voronoi_polygons()).
A function that joins, measures or unions such a polygon in degrees
stops with an error that names its rows, quotes s2's reason and says to
transform the layer to a projected CRS, such as the one
ensure_projected() picks for it. The class is
spatialkit_cells_degenerate for cells and boundaries, and
spatialkit_features_degenerate for features being assigned or reduced
to points. Some steps repair the polygons first, such as the
largest-overlap join of assign_features_to_polygons() and the union of
a boundary in get_voronoi_seeds(), and stop only when s2 refuses a
repaired polygon.
A hex or square grid built with a geographic crs is laid in degrees
(create_grid_polygons()). Voronoi cells asked for in a geographic crs
are built in a projected CRS and then transformed.
Coordinates far from the origin
Far from the origin of a CRS, doubles are spaced more widely: 0.125 apart
at 1e15. Where they are spaced more than a millionth of a layer's extent
apart, edges and points are held to that spacing, and a point within it
of an edge can fall on the other side. The functions that build cells,
blocks and joins still run, with a warning of class
spatialkit_xy_imprecise that gives the spacing and the extent;
clip_target_for() stops with an error of class
spatialkit_xy_imprecise_error where its buffer comes back empty or
with no area. Those that search for neighbours (estimate_sac_range(),
fit_gwr_model(), residual_morans_i()) give the same warning where a
distance lies past a tie by less than the rounding. Subtract a constant
from the coordinates to bring them nearer the origin.
See Also
spatialkit-conditions for every condition class named here,
ensure_projected() for the choice of a projected CRS, and
harmonize_crs() for aligning two layers.
Other data preparation:
[.spatialkit_rows(),
coerce_to_points(),
ensure_projected(),
harmonize_crs(),
prep_model_data()
Options that bound the work of a search or a fit
Description
The package reads two options. Each bounds a step whose cost grows with
the square of the rows or of the cells, so that such a step stops, or is
skipped, before it starts. Set them with options().
The options
spatialkit.exact_pairs_maxDefault
2e9pairs. The most pairs a search made without the FNN package may compare. Without FNN, a nearest-neighbour search (each cell's neighbours, each row's nearest centre, each location's nearest other location) compares every pair, and a search over the pairs of about 44,700 cells or locations reaches the default. With FNN, which installs with spatialkit, these searches use a kd-tree and the limit is not read. The result of every search is the same with and without FNN. Above the limit:-
resolution_profile()stops with an error of classspatialkit_work_limitbefore the search: on a ladder of sizes, for the weights ofpartition = "density"; with anestimate, on any ladder, for the estimate's searches. -
cell_values_at()stops with the same error before the search. -
summarize_by_cell()returnsNApooled columns with a warning of classspatialkit_pool_unavailable(reason = "work limit"), and does not run the check of the count record ("not checked: work limit"). -
select_resolution()hands on the centres fitted to the subsample without refitting them to every point, with a logged warning.
-
spatialkit.fit_work_maxDefault
1e10point-to-centre comparisons. The most work the partition fits of a ladder of sizes may do: the points times the cells of the finest level timesnstart, timesiter_maxforpartition = "density"without FNN. With FNN andinit = "random"the density kind has no step that compares every point with every centre, and nothing is counted. Above the limit,resolution_profile()stops with an error of classspatialkit_work_limitbefore any fit. At the default size the work grows with the square of the rows.select_resolution()refits the centres of a profile fitted to a subsample to every point, and counts the points times the cells of the count it selects, timesiter_maxfor the density kind without FNN, whatever the start. Above the limit it hands on the centres fitted to the subsample, with a logged warning.
Setting a limit
Each option takes a single number, 0 or more; Inf removes the limit.
Any other value is an error when the option is read. The error of class
spatialkit_work_limit carries work (the count), limit and what
(the step), and its message says what to change: for a fit, fewer
starts, a coarser obs_per_cell, random starts of the density kind or a
higher limit; for a search, reinstalling FNN. A
profile just below spatialkit.fit_work_max prints nothing while its
fits run.
The console log is set with spatialkit_quiet(), not with an option.
See Also
spatialkit-conditions for the classes named here, and
resolution_profile() for the work its fits do.
Other options and caches:
clear_fitted_cache(),
clear_grid_cache(),
spatialkit-conditions,
spatialkit_quiet()
Examples
getOption("spatialkit.exact_pairs_max", 2e9)
getOption("spatialkit.fit_work_max", 1e10)
# Raise one limit for a session, then put it back.
old <- options(spatialkit.fit_work_max = 2e10)
getOption("spatialkit.fit_work_max")
options(old)
Turn the console log off or on
Description
Turns the package's console log off (quiet = TRUE) or back on. The
package writes a trace of INFO lines and above to
file.path(tempdir(), "spatialkit_model_log.log"), a file that lasts
as long as the R session, and echoes WARN lines and above to the console;
this function changes only the console echo.
logger::log_threshold() changes the log file's threshold by default
(index = 1), not the console echo's, so use this function for the
echo.
Usage
spatialkit_quiet(quiet = TRUE)
Arguments
quiet |
|
Details
These are log records, not R conditions: suppressWarnings()
and tryCatch(warning = ) do not see them. Conditions the package
raises as R warnings are unaffected by this function (see "Warnings and
log lines" in spatialkit-conditions).
While a document is being knitted (R Markdown, Quarto, a pkgdown
article) the console echo is also sent as an R message, because
knitr does not capture what is written to the console's error stream
and the cautions would otherwise be missing from the output. They appear
as ## WARN [...] lines, and the chunk option message = FALSE,
like suppressMessages(), keeps them out of the document. A line the
package also raises as an R warning is not repeated, since the document
shows the warning. Outside knitr nothing changes.
Value
Invisibly, the threshold that was in force before the change, a
logger level that can be passed back as quiet.
See Also
Other options and caches:
clear_fitted_cache(),
clear_grid_cache(),
spatialkit-conditions,
spatialkit-options
Examples
old <- spatialkit_quiet() # console echo off
spatialkit_quiet(old) # back to whatever it was
spatialkit_quiet(FALSE) # or back to the WARN+ default
Summarise assigned points by cell, with standard errors and pooled values
Description
Aggregates an sf point dataset into one row per cell. Each cell gets a
count, the mean of each response and predictor column (or the functions in
agg_funs), and that column's within-cell standard deviation and standard
error. By default each numeric column also gets a pooled value, the cell's
mean pulled toward the mean of the cells around it (estimate = "pooled";
estimate = "mean" leaves it out). On request the frame adds an interval
for each mean (conf_level) and an interval for one further observation
(obs_level).
Usage
summarize_by_cell(
assigned_points_sf,
response_var = NULL,
predictor_vars = NULL,
id_col = "poly_id",
agg_funs = list(mean = function(x) mean(x, na.rm = TRUE)),
cells_sf = NULL,
deff = 1,
sac = NULL,
deff_max_n = 500L,
quiet = TRUE,
conf_level = NULL,
area = FALSE,
estimate = c("pooled", "mean"),
obs_level = NULL
)
Arguments
assigned_points_sf |
An sf object with a cell identifier column. |
response_var |
Optional response column name for per-cell aggregation: a single character string. A name that is not a column, or a column that is not numeric, is skipped with a warning. |
predictor_vars |
Optional predictor column names for per-cell aggregation. Names that are not columns, and columns that are not numeric, are skipped with a warning. |
id_col |
Name of the cell ID column. Default |
agg_funs |
Named list of aggregation functions. Default
|
cells_sf |
Optional polygon sf layer to join cell geometries onto
the output. When supplied, the return value is an sf object with
the polygon geometry from cells_sf, with one row per cell in |
deff |
Design-effect adjustment for standard errors. One of:
|
sac |
Optional |
deff_max_n |
Cells with more than this many points are subsampled
before forming the |
quiet |
Logical; suppress this function's progress |
conf_level |
Optional confidence level in (0, 1), such as |
area |
Logical, default |
estimate |
Which value of a cell the frame reports: |
obs_level |
Optional level in (0, 1), such as |
Details
This is the step after assign_features_to_polygons(), which labels each
observation with its cell. Beside every mean the frame keeps the count and
the standard error, so a cell mean over 2 observations and one over 200 stay
distinguishable in a map or a model, and deff can widen the standard error
for correlation inside a cell.
Value
A tibble/data.frame (or sf if cells_sf given) with per-cell
summaries: the ID column, n (rows in the cell), one column per
agg_funs entry per variable (resp_<name>_<var> for the response and
pred_<name>_<var> for each predictor), ..sd_* / ..se_* for every
numeric response and predictor, ..neff_* / ..df_* / ..ci_lo_* /
..ci_hi_* for the same columns when conf_level is given,
cell_weight (always), deff_applied and deff_method when a design
effect was requested (any deff other than 1), and cell_area /
n_per_area when area = TRUE ("Output columns" gives the order). An input column also called n is not allowed to
shadow the count.
deff_applied is TRUE on every row when a design-effect correction
was applied (exactly when the "deff_applied" attribute below is
attached; under "kish", when any standard-error column was corrected)
and FALSE when none was: a refused deff, or "kish" ICCs of 0 or
NA for every column (the standard errors are then the uncorrected
ones, or NA where an ICC cannot be estimated). It is NA on a
cells_sf row no point fell in. deff_method names the correction
the standard errors carry, since their column names do not change with
it: "variogram", "kish" or "fixed" when the one requested was
applied, "none" when none was, and "kish (variogram fallback)" or
"none (variogram fallback)" when a "variogram" request could not be
met and Kish stood in for it (the second when Kish's ICCs were 0 or
NA too).
So deff_applied is TRUE on a Kish fallback row: test
deff_method == "variogram" to keep only rows the variogram corrected.
Unlike the attribute, both columns survive rbind() and
dplyr::bind_rows() of many results. A fallback is also signalled by a
warning of class "spatialkit_deff_fallback" (a Kish ICC of 0 under a
"kish" request is reported on attr(, "icc") instead), which
tryCatch(spatialkit_deff_fallback = ) catches without matching the
message. It is raised when the correction requested was not the one
applied: a refused number (the standard errors are then the uncorrected
ones) or a "variogram" request that fell back to Kish; the condition
of the second carries requested and used. Two more classes say what
a design effect could not do: "spatialkit_icc_unavailable" names the
columns whose Kish ICC cannot be estimated, and
"spatialkit_deff_no_structure" the predictor columns given a design
effect of 1 by a variogram that found no spatial structure.
When a correction was actually applied, an attribute "deff_applied" is
attached recording it: method plus icc_resp/icc_pred and deff
for "kish" (icc_pred is a vector named by predictor column, one ICC
each; deff is the primary variable's per-cell design effect,
all 1 when only a predictor's ICC was positive, except that it is NA
in each cell of two or more of the primary variable's values when that
variable's ICC cannot be estimated, and its entry in icc_resp or
icc_pred is then NA too; requested and
fallback_reason are added when a "variogram" request fell back to
it),
deff/deff_rows/rbar/crs/max_n for "variogram" (deff is
the design effect at the primary variable's non-missing count per cell,
deff_rows at the cell's row count, which is the vector the log line
summarises as a median and a max), and deff alone for a fixed number.
When cells_sf is supplied, every per-cell vector in that attribute
(deff, deff_rows and rbar alike) is realigned to the joined row
order, so deff[i] and rbar[i] still describe row i; cells with no
observations carry NA. No attribute is attached when no correction was
applied: deff = 1, or a deff = "kish" request (or Kish fallback)
whose ICCs are all 0 or NA. A deff = "kish" request, and a "variogram"
request that fell back to it, always
records the ICCs it estimated on an attribute "icc" (resp, and
pred, a vector named by predictor column; NA for a variable type
with no numeric column and for a column whose ICC cannot be estimated;
reason, a character vector named by column, is then added and says
why), whether or not
they were positive enough to apply, so a result with no "deff_applied"
still says what the ICCs came out as.
The ID column keeps its input type when cells_sf's ID column and the
summarised IDs already have the same class. When the classes differ, both
are coerced to character in order to join (logged as a warning), and the
returned ID column is therefore character. Whole numbers are written out
in full for that ("100000", never "1e+05"), so an integer and a
double ID of the same cell still match.
With estimate = "pooled", each numeric column v with its prefix
(resp_ or pred_) gains ..pooled_<prefix><v> (the pooled value),
..pooled_w_<prefix><v> (the own weight, 0 to 1; it is not a regression
weight) and ..pooled_target_<prefix><v> (the target), and with
obs_level also ..obs_lo_<prefix><v> and ..obs_hi_<prefix><v>.
They follow every column listed above and precede cell_area and
n_per_area, the response's first, then each predictor's. A cell with
no row that has a value, a cell and a location gets NA, never a value
made from its neighbours. Two attributes are attached.
attr(, "pooled"), of class "spatialkit_pooled", records what was
fitted: toward, neighbours, crs (the CRS the centroid distances
were measured in), obs_level, conf_level, intervals and columns,
a list with one entry per pooled column holding column, role
("response" or "predictor"), n (rows used), cells, df (values
beyond one per cell, which sigma2 rests on), neighbours (the cells
in each target), sigma2, tau2, own_weight (the median weight),
share_alone (the share of rows that are the only one in their cell),
loo and loo_se (the leave-one-out mean squared error of the pooled
value, and its standard error over rows), loo_one_cell (the same error
with one mean for all rows), structured and structure_p (whether the
cells predict a left-out observation better than one mean, and the
p-value of the F test of the cell means against one mean, which has to
be below 0.05 as well), offsets (the two offsets of the interval),
repeated, skipped, constant and status. attr(, "intervals") is
the same data frame as attr(, "pooled")$intervals: one row per family
of interval columns in the frame, saying what it covers, what it is
centred on, its level and its method. Away from the observations no
interval here is calibrated.
Where the pooled columns of a column cannot be computed they are NA,
with a warning of class "spatialkit_pool_unavailable" and not an
error, and the plain columns are returned. "Conditions" lists that
class and the other warnings of the pooled columns, with what each
condition carries.
When assigned_points_sf carries attr(, "count_rule"), or cells_sf
does (the assigned layer's is read first), the result carries that
record with one more element, check, whatever estimate is. The
record is the one select_resolution() wrote: rule, estimate (the
cell value the count was chosen for), cells, obs_per_cell,
response, scored (what the profile scored at the count: the rows,
the cells that hold one, the leave-one-out error among them, and the
centres the rows were given to),
partition, crs and scored_cells. It has class
"spatialkit_count_rule" and a print method. check$estimate is
"match" or "mismatch": whether the summary reports the estimate the
count was chosen for (NA for a count chosen for neither). A mismatch
is a warning of class "spatialkit_estimate_mismatch" (fields
chosen_for, reported, rule, cells), and the summary is returned
as asked. check$cells is "match", "differ" or "not checked: <reason>": the response is fitted again on the rows and cells given,
with the estimate the profile scored, and its scored rows, its occupied
cells and its leave-one-out error are compared with the record's, the
error to a relative tolerance of 1e-8. The first that differs is a
warning of class "spatialkit_cells_differ" (fields what: "n",
"cells" or "loo"; scored; found): rows were dropped or moved
between cells, or the layer is another one. The same class with what = "record" (fields field, scored, found) is raised when the
assigned layer and cells_sf carry different records, so the rows were
assigned to other cells than the cells_sf given: the cells of another
selection, or the scored cells of a selection beside other cells built
from its count, such as a lattice sized by it. check$cells is then
"differ", whatever the comparison of the rows finds. The comparison
is not made, and check$cells says why, when the response is another
column or was not summarised, the profile read the selection half
(select_on = "split"), the cells are not the ones the profile scored
(scored_cells is FALSE or NA), the profile scored no estimate, the
input has no coordinates, the features are not points (see
assign_features_to_polygons()), or the fit was stopped by the limit on
an exact search without the FNN package. Cells and rows without a
record, such as polygons the caller brings, are not checked and raise
neither warning.
A row that is the same distance from two centres lies on the boundary
between their cells, which happens on gridded locations.
resolution_profile() scores such a row in the cell of the lower-numbered
centre (a distance counts as the same as the least when its square is no
more than the square of the least distance lengthened by a margin, plus
one part in ten million of the least squared distance; the margin is one
part in 1e10 of the largest coordinate of the centres, at most a
millionth of the diagonal of their bounding box and at least four times
the spacing of doubles at that coordinate), and assign_features_to_polygons(), on cells
built from the centres the profile scored, gives a point on that boundary
the same cell, measured in the CRS the record names, so the comparison
reads "match" on gridded locations too. It does so on cells that carry
the record, for rows that have a CRS exactly when the record names one.
Rows without a CRS beside a record that names one, rows with a CRS beside
a record that names none, rows assigned to the cells after they lost the
record (written to a file and read back, say) and summarised with
cells_sf set to the cells that carry it, and rows given their cells by
another join are placed by the polygons alone, so a row on a boundary can
sit in either cell.
build_tessellation() draws those cells in the CRS the record names,
whatever CRS the seeds arrive in, unless its crs names another
projected CRS. Cells built in another projected CRS are the
nearest-centre cells of that CRS, and cells transformed to another
projected CRS are joined there, so a row near a boundary, on it or not,
can sit in another cell than the profile put it in. So can a row joined
in longitude and latitude, as rows and cells in degrees are when the
cells do not carry the record or carry one in degrees (the Voronoi
cells of the scored centres that build_tessellation() returns in a
geographic crs are joined in the record's CRS while they carry it), a
row in cells that carry the record but are not the Voronoi cells of its
centres (seeds moved, or cells edited, after the selection), and a row
that reached the record's CRS by another transformation than the
profile's, which can settle a tie the other way. Cells returned in a
geographic crs are moved back to the record's CRS for that join, and
for a layer wider than a UTM zone the round trip can move a corner by
more than the margin of assign_features_to_polygons(), so a row on an
edge there can sit in another cell too. The comparison then reports
"differ", with what = "loo" when it finds the same rows in the same
number of cells with another leave-one-out error, and the warning names
these cases. The summary's own numbers describe the cells as assigned.
The comparison uses the fit of the pooled columns when that is a fit of
the estimate the profile scored, and fits the response once more
otherwise. Without the FNN package that fit compares every pair of
cell centroids (pooled values) or, for each row alone in its cell,
every other location (plain means), and above
options(spatialkit.exact_pairs_max = ) pairs it is not made
("not checked: work limit"). A summary is not compared when neither
layer carries the record: attr(x, "count_rule") <- NULL on the
assigned layer and on cells_sf removes it.
Output columns
One row per cell, with these columns in this order:
the ID column (see
id_col);-
n, the rows that fall in the cell; for each variable, the response's first and then each predictor's: one column per
agg_funsentry (resp_<name>_<var>for the response andpred_<name>_<var>for a predictor, soresp_mean_valfor the default mean of a responseval), the within-cell standard deviation (..sd_resp_<var>,..sd_pred_<var>) and standard error (..se_resp_<var>,..se_pred_<var>) of a numeric column, and withconf_levelits..neff_*,..df_*,..ci_lo_*and..ci_hi_*(see "Confidence intervals");-
cell_weight, always; -
deff_appliedanddeff_methodwhen a design effect was requested (anydeffother than 1); with
estimate = "pooled", the pooled columns (see "Pooled values" and "Value");with
cells_sf, the cells' geometry;with
area = TRUE,cell_areaandn_per_area.
cell_weight is the effective sample size of the primary variable: the
response when one was supplied, otherwise the first predictor. It counts
that variable's non-missing rows, not all rows (a cell of 10 rows with 3
finite responses carries 3 observations' worth of information about the
response), and it is divided by that cell's design effect when deff
applied one. With deff = 1 and no missing values it equals n. Pass it
as the weights argument of a downstream regression.
An infinite value (Inf, -Inf) in a response or predictor column is
treated as missing, as NA and NaN are, in every statistic of that
column: the agg_funs results, ..sd_*, ..se_*, the interval columns,
..neff_*, cell_weight and the design effect. n still counts the row.
A warning of class "spatialkit_nonfinite" names the columns and gives the
number of rows and cells affected (the condition carries n and
columns). kriging_adequacy(), resolution_profile(),
estimate_sac_range() and prep_model_data() leave such rows out too, so
the steps of one pipeline agree on a cell's mean. A function in agg_funs
therefore never sees an infinite value: max returns the largest finite
value, and infinities cannot be counted through agg_funs.
..sd_* is the standard deviation of the cell's values in the units of
the column, at any size. Where the raw squares overflow or lose their bits
(a standard deviation that is not finite or is below 1e-150), it is taken
on the values centred on their median and divided by powers of two, which
keeps their spread. A cell whose standard deviation is beyond the largest
double (about 1.8e308) has ..sd_* of Inf and standard errors and
interval of NA, with a warning of class "spatialkit_sd_overflow" (the
condition carries columns and cells, the number of such cells of each
column).
Pooled values
With estimate = "pooled" every numeric column also gets a pooled value.
That is the default; estimate = "mean" leaves the pooled columns out.
A cell's value, plain or pooled, estimates the cell's true mean: the
expected value of one further observation located in the cell the way its
observations were. It is not the average of a surface over the cell's
area, which would give weight to ground that holds no observation.
For one column, write n, S and m = S / n for the count, the sum and
the mean of a cell's rows, N for the rows in all and K for the cells
that hold one. Then
-
sigma2 = sum((y - m)^2) / (N - K)is the spread of the observed values about their cell's mean; the target
tof a cell is the mean of the rows of its neighbours,sum(S) / sum(n)over them. The neighbours are the 8 cells whose centroids are nearest, the centroid of a cell being the mean of the coordinates of its rows. The polygons are not read, so two cells are neighbours whether or not they touch, and a cell is never its own neighbour;-
tau2 = max(0, (sum(n * (m - t)^2) - K * sigma2) / N)is the mean squared distance between a cell's true mean and its target, the target's own error included; the own weight is
w = tau2 / (tau2 + sigma2 / n);the pooled value is
w * m + (1 - w) * t.
The own weight is the share of the pooled value that is the cell's own
mean. It grows with the cell's count and with tau2. At 1 the pooled
value is the plain mean; at 0 it is the target and holds none of the
cell's own values. Pooled values are for maps and for predicting
observations. ..pooled_w_* is not a regression weight. The plain
columns are the same under either estimate, and they are the ones to
use, with cell_weight, in a regression on cell values: each column is
pulled toward its neighbours by its own amount, so a regression of pooled
responses on pooled predictors is not a regression of the true means.
The cells can be any polygons the rows were assigned to, the package's
own or ones the caller brings, with IDs of any type: only each row's cell
and location are read. Each column is pooled on its own rows, those with
a value, a cell and a location, with its own centroids, neighbours,
sigma2 and tau2; a missing value in one column changes nothing in
another. A cell with one such row gets a value. A cell with none gets
NA, never a value made from its neighbours. The pooled columns do not
read agg_funs or deff: the mean that is pooled is the arithmetic mean
whatever agg_funs computes, and no design effect enters sigma2,
tau2, the weights or the interval of obs_level.
Three cases change what the numbers rest on, and each is a warning (see
"Conditions"). With 2 to 9 cells the neighbours of a cell are all the
others, so its target is the mean of every row outside it, and the overall
mean lies between that target and the cell's own mean. A cell whose own
weight is below its share of the rows, n / N, then gets a pooled value
on the far side of the overall mean from its plain mean, and two cells can
change order. When few cells hold two rows, sigma2 is estimated from few
values and every weight rests on it: df in attr(, "pooled") is the
number of values beyond one per cell. And when tau2 comes out at 0,
every own weight is 0 and each pooled value is its target; with two
cells that is the other cell's mean, so the two values change places.
Two candidate neighbours are a tie when their squared distances differ by
no more than one part in ten million. A tie goes to the centroid with the
lower x, then the lower y, coordinates within that part of the distance
counting as equal, and then to the cell whose ID sorts first. The
centroids are summed with the rows in coordinate order, so a cell's
neighbours do not depend on the order of the rows, and on gridded
locations they do not depend on the unit or the origin of the coordinates
either. The values agree to rounding under another order of the rows,
since a cell's sums are taken in the order of its rows, and under another
unit or origin where three to eight cells' centroids coincide, since the
rounding then sets the order in which a cell's neighbours on that point
are summed. A cell whose centroid shares its point with as many other
cells as it has neighbours, or more, takes its neighbours from them, the
first by ID, without a search. Centroids count as one point there when
they are equal, or when they lie within a ten-millionth of the largest
coordinate of one another, in x and in y. Where other centroids that close
to them chain on further than that, the chain is taken again at half that
reach, and so on, until its parts span no more than the reach they were
taken at. So those cells keep their neighbours and their values in another
unit, and with the origin moved by little against the coordinates. On such
a point, cells whose centroids lie that close without coinciding take each
other by ID as well, not by distance. The reach follows the largest
coordinate, so with the origin moved far, to the corner of the data say,
such centroids can lie beyond it, and their cells then take the nearest.
Distances are measured in the CRS named under estimate, so the same
layer in another projection can still give a cell other neighbours, and
so can a lattice whose spacing is below about a ten-millionth of its
coordinates.
structured in attr(, "pooled") says whether these cells predict a
left-out observation better than one mean for all rows. It is FALSE
when the leave-one-out error of one mean (loo_one_cell) is within 2
percent of that of the pooled values (loo) or below it, or when the F
test of the cell means against one mean has p >= 0.05
(structure_p). FALSE raises a warning of class
"spatialkit_no_structure", and the values are returned. On a response
without spatial structure they still make a smooth map: the own weights
are small, so each pooled value lies close to the mean of its neighbours
("How this was checked" gives the figures).
The pooling model implies an error variance for a pooled value as an
estimate of the cell's true mean, (1 - w) * tau2. It is not returned,
and neither is an interval for the true mean, because no check has
confirmed an interval built from it; sigma2, tau2 and ..pooled_w_*
are in the result for a reader who wants to form it. Away from the
observations that variance is too small ("How this was checked").
Beside a sharp boundary the pooled value can be further from a cell's true mean than the plain mean, because its target takes in cells across the boundary.
Intervals: which one answers which question
Two families of interval columns can be in the frame. Each has its own argument, and neither changes the other.
| Family | Columns | Target | Centre | Asked for by |
| observation | ..obs_lo_*, ..obs_hi_* | one further observation in the cell | pooled value | obs_level |
| mean | ..ci_lo_*, ..ci_hi_* | a mean, never one observation | plain mean | conf_level
|
The observation of the first is one located in the cell the way the
data's were. obs_level needs estimate = "pooled": without it the call
is an error, not an interval round the plain mean. The mean the second
covers follows deff: at deff = 1 the cell's own mean, when its
observations are spread through the cell; under deff = "kish",
"variogram" or a number other than 1 the cell mean as an estimate of
the population mean (see "Confidence intervals", which also describes
..neff_* and ..df_*). No interval and no standard error is returned
for a cell's true mean as the pooled value estimates it.
attr(, "intervals") says the same of the frame in hand, one row per
family present.
The interval for one observation is the pooled value plus two quantiles
of the leave-one-out residuals of the pooled values. The residual e of
a row is its value minus the pooled value of its cell computed without
it: the cell's mean and own weight are computed again without the row,
and sigma2, tau2 and the targets are held. With
p = (1 - obs_level) / 2,
..obs_lo = pooled + quantile(e, p) and
..obs_hi = pooled + quantile(e, 1 - p).
It is a statement about observations on average: of further observations located like the data, about
obs_levelof them fall inside the interval of their cell. It does not hold cell by cell.The two offsets are the same in every cell. The interval's centre varies over the map and its width does not. It does not narrow where a cell holds more rows: the offsets are quantiles of the errors of predicting single observations, and the spread of observations inside a cell is in every one of them.
It is wide, because one observation is uncertain.
Only the level 0.90 has been checked. Another level is computed the same way.
Each residual is the error of predicting an observation from the other rows of its cell and from the cells around it, so the interval describes locations among the observations. A cell's value and interval describe the part of the cell where its observations lie, and a Voronoi cell can reach far past them toward the edge of the study area. The interval is too narrow for a cell with no observation, a gap in the layer or ground beyond the layer's edge.
cell_values_at() returns each location's distance from the nearest
observation, and its help gives the coverage by that distance.
Away from the observations no interval here is calibrated.
Standard errors and design effects
What the ..se_* columns estimate follows deff. At the default,
deff = 1, sd / sqrt(n) is the standard error of the cell's own mean,
the mean of the units the cell holds, and it is the right one when the
cell's observations are spread through the cell. Under deff = "kish",
"variogram" or a number other than 1 the columns are the standard error
of the cell mean as an estimate of the population (grand) mean: the
unconditional quantity, in which the cell's own realised deviation is part
of the error, widened for the correlation inside the cell. That is the
right quantity when cells are treated as samples from a common population.
Spatially autocorrelated observations in one cell are positively
correlated: they share the cell's departure from the population mean. As
an estimate of the population mean, a cell mean then has an effective
sample size smaller than n, and the naive standard error is too small. A
downstream weighted regression that uses cell_weight or the ..se_*
columns for population-level inference then gives overconfident standard
errors for cells with strong within-cell correlation.
The corrected standard error is not that of the cell's own mean (the
block average over that cell), which is what a cell-level map or a
regression on cell values usually wants. For that quantity the naive
sd / sqrt(n) is the better of the two on offer. Under exchangeable
within-cell correlation it is exact, and the design-effect-corrected SE is
too wide by the factor sqrt(deff / (1 - rho)) (4.6 at 20 points a cell
and rho = 0.5). Under a spatial covariance model it holds only when the
cell's points are spread through the cell; with clustered sampling inside
a cell it is too small for the block average too, and the right quantity
there is the plain mean's error variance under a variogram, plain_var in
kriging_adequacy(). Use deff when the cell means feed a
population-level inference; leave it at 1 when they are measurements of
the cells themselves and the sampling within cells is close to uniform.
deff = "kish" applies Kish's design effect. An intra-class correlation
(ICC) is estimated for every summarised column on its own, the response
and each predictor, by a one-way random-effects decomposition across all
cells, and each column's ICC is used for that column alone: listing or
removing a predictor leaves every other column's standard error,
effective n and interval as they were. Each cell's effective sample size
is n_i / (1 + (n_i - 1) * rho). This first-order correction needs no
spatial covariance model, but it needs enough cells and observations for
a stable ICC. A column whose ICC cannot be estimated at all gets NA
standard errors (see deff).
deff = "variogram" fits or accepts one correlation function and applies
it to every numeric column, because a variogram is a property of the field
being modelled rather than of a variable type; a predictor whose spatial
structure differs from the response's has its SE corrected by the
response's correlation. When that variogram finds no spatial structure
(the pure nugget estimate_sac_range() returns with that verdict), every
column gets a design effect of 1, the predictors included, and a warning
of class "spatialkit_deff_no_structure" names the predictor columns: the
verdict is about the variable the variogram was fitted to, not about
them. The internally estimated variogram is fitted to the response
itself, never to OLS residuals, whatever predictor_vars holds: the
..se_resp_* columns estimate the grand mean of the response, so the
correlation to correct for is the response's own. A residual variogram
holds only the correlation of the part the predictors do not explain,
which is weaker. Pass sac explicitly for a different variogram, such as
a residual one from estimate_sac_range(..., predictor_vars = ). A sac
whose attr(sac, "detrended") is TRUE is used as given, but when it
corrects response columns a warning says that their standard errors are
understated, as kriging_adequacy() warns about the same mismatch.
A design effect estimated from the data ("kish" or "variogram") comes
with a second, small-sample correction. The within-cell correlation that
inflates the variance of the mean to sigma^2 * deff / n also biases the
within-cell sample variance downward: under exchangeable correlation rho
(Kish's own assumption), with deff = 1 + (n - 1) * rho,
E[s^2] = sigma^2 * (n - deff) / (n - 1), so s^2 understates sigma^2
by very nearly the factor by which deff inflates the mean's variance,
and the two errors compound. The standard error is therefore
s * sqrt(deff / n) * sqrt((n - 1) / (n - deff)), and NA where
deff >= n (the cell then holds one observation's worth of information
and s carries none about sigma). This is the package's own derivation,
not taken from a reference.
A fixed numeric design effect (deff = 2, say) inflates the standard
errors uniformly: it is applied as sd * sqrt(deff / n), exactly
sqrt(deff) times the naive SE in every cell. The E[s^2] correction of
the estimated design effects is derived from within-cell correlation, and
is not applied to a number the caller chose.
Even with these corrections the adjusted SE is an approximation. For
inference under spatial dependence, fit an explicit spatial covariance
model, such as fit_bayesian_spatial_model().
Confidence intervals
With conf_level set, every numeric response and predictor column gains
four more columns: ..neff_*, that column's effective sample size in the
cell (its non-missing count over its design effect, the per-column version
of cell_weight); ..df_*, the degrees of freedom the interval uses; and
..ci_lo_* / ..ci_hi_*, a t interval for a mean. Which mean follows
deff, as for ..se_*: at the default, deff = 1, the cell's own mean,
when its observations are spread through the cell; under deff = "kish",
"variogram" or a number other than 1, the cell mean as an estimate of
the population (grand) mean. "Standard errors and design effects" applies
to it, including that the corrected interval is not one for the cell's own
block average. The interval is
mean +/- qt((1 + conf_level) / 2, df) * se, centred on the plain mean of
the column's non-missing values whatever agg_funs computes, and is NA
wherever the standard error is (a single observation; complete redundancy
under deff). ..neff_* and ..df_* are NA where the column has one
non-missing value or none, like the standard error; cell_weight still
counts such a cell (1, or 1 / deff for a numeric deff), so the two
differ there.
At no setting is ..ci_* a range for one observation: it is an interval
for a mean, and it narrows as a cell's count grows where the spread of
single observations does not. The interval for one further observation in
a cell has its own argument and columns, obs_level with
estimate = "pooled" and ..obs_lo_* / ..obs_hi_* (see "Intervals:
which one answers which question"). Away from the observations no interval
here is calibrated.
The degrees of freedom are not neff - 1. The interval's spread comes
from the within-cell sample variance, and under exchangeable correlation
(deff = "kish") that variance keeps its n - 1 degrees of freedom
whatever the design effect. The design effect inflates the mean's
variance and biases s^2, both of which the standard error already
corrects, and the resulting pivot is exactly t on n - 1 df. The
effective-sample-size
degrees of freedom of Faes et al. (2009) belong to a mean estimated across
many correlated units whose variance is estimated from the spread between
them; they do not transfer to a single cell's mean with a variance
estimated from inside it. ..df_* is therefore n - 1 at deff = 1, for
a numeric deff and for "kish". Under deff = "variogram" correlation
decays with distance and the within-cell variance loses degrees of freedom
to it; ..df_* is then the Satterthwaite (1946) moment-matched df of
s^2 under the fitted correlation matrix, a fraction of n - 1 that
shrinks as the range grows. The interval is only as good as the design
effect under it: a mis-specified variogram, or an ICC estimated from too
few cells, moves the coverage with it.
Conditions
What the pooled columns and the count record have to say is raised as R
warnings with a class, so tryCatch(<class> = ) and
withCallingHandlers() catch each without matching its text. A warning
of the pooled columns is raised once per call and reason, for all the
columns it applies to: its text names them and the condition carries them
in columns, in the order of the pooled columns. A field said to be by
column is a vector named by those columns, and the numbers of each column
are in attr(, "pooled").
-
"spatialkit_pool_unavailable": the pooled columns of a column areNA. The plain columns are returned, and this is never an error.reasonis"no coordinates"(a layer without geometry),"no located value"(no row with a value, a cell and a location),"no cell holds two values"(the condition also carriesnandcellsby column),"values out of range"(values so large, or so close to their median, that the squares of many such values can overflow or lose their precision; the message gives the bounds, and the column rescaled by a power of ten is pooled) or"work limit". The last is the case of many cells without the FNN package: the neighbour search then compares every pair of cells and is not made abovegetOption("spatialkit.exact_pairs_max", 2e9)pairs, which is about 44,700 cells (the condition also carrieswork,limit, andcellsby column). With FNN there is no such limit, and the result is the same. -
"spatialkit_pool_degenerate": the pooled values were computed and carry no pooling.reasonis"one cell"(the pooled value is the plain mean; alsonby column),"no spread inside any cell"(the values do not vary inside any cell to their precision, so every own weight is 1; alsoconstantby column) or"no signal between cells"(tau2is 0 and every own weight is 0; alsosigma2by column). -
"spatialkit_pool_few_cells": 2 to 9 cells, so each target is the mean of all the other cells, and a cell whose own weight is below its share of the column's rows gets a pooled value on the far side of the overall mean from its plain mean (cells, andown_weight, the smallest, by column). The text also names each column with two cells andtau2at 0, which hascells2 andown_weight0: each cell's pooled value is then the other cell's mean, so the two values change places. -
"spatialkit_pool_few_df":sigma2rests on fewer than 30 values beyond one per cell (needed, anddf,nandcellsby column). -
"spatialkit_no_structure":structuredisFALSE(see "Pooled values"). The text says which of the two tests failed, andbeatsisTRUEfor a column whose pooled values beat one mean while the F test does not tell the cell means from one mean (alsocriterion = "loo",estimate = "pooled", and by columnn, the cells,one_cell,looandstructure_p). -
"spatialkit_pool_rows_skipped": rows with a value and a cell have no location: an empty point, a coordinate that is not finite or lies beyond 1e150, as given or in the CRS the distances are measured in, or in a geographic CRS a vertex at a latitude beyond 90 degrees. They count innand the plain columns and take no part in the pooled ones (n,cells). -
"spatialkit_repeated_locations", withobs_level: rows with a value share a location. A residual leaves one row out and keeps the others at its location, so the interval then describes a further observation at a place already observed (nandtotalby column). -
"spatialkit_few_residuals", withobs_level: fewer than five residuals are expected beyond each end of the interval, which at 0.90 is fewer than 100 residuals (needed,level, andnby column). -
"spatialkit_estimate_mismatch"and"spatialkit_cells_differ": the two checks of the count record, described under "Value".
The two about few cells and few values are raised for columns whose
weights were estimated, and the two of obs_level for columns whose
interval is read from residuals, so a constant column raises
"spatialkit_pool_degenerate" and no other.
How this was checked
The figures on this page that describe pooled values and the two
intervals come from one simulation,
dev/sim-pooled-values.R
in the package's GitHub repository, whose header holds its settings and
seeds. It draws 200 layers on a square of side 1,000. Each has 2,100
clustered locations (four fifths of them round 25 parent points with a
standard deviation of 40, the rest uniform) and a response that is a field
with covariance exp(-d / 100) plus noise of variance 0.3. The 300
locations nearest a random centre are held out as a block, 300 of the
others are held out at random, and the 1,500 left are the layer: 333 cells
at 4.5 observations a cell from resolution_profile() with
partition = "density", select_resolution(criterion = "size"),
get_voronoi_seeds(), build_tessellation() and
assign_features_to_polygons(), summarised with estimate = "pooled". A
held-out observation is given the value of its cell by cell_values_at().
At the observations held out at random the root mean squared error of the pooled value was 0.96 of the plain mean's: 0.84 in cells that hold one of the layer's observations, 0.95 in cells of 2 to 4, 0.98 in cells of 5 to 9 and 0.99 in cells of 10 or more. In the held-out block it was 0.95.
The interval at obs_level = 0.90 held 89.6 percent of the observations
held out at random among the others (83.7 to 94.0 percent in single layers)
and 75.1 percent of those in the held-out block. ..ci_* at
conf_level = 0.90, read as a range for one observation, held 58.9 and
49.2 percent of them, over the held-out observations whose cell has that
interval.
With a cell's true mean taken as the mean of the noise-free field over
further locations drawn in it like the data's, the squared error of the
pooled value was 0.98 of (1 - w) * tau2 among the observations and 6.9
times it in the held-out block.
With white noise as the response on the simulation's 200 layers the median
own weight was 0.11, tau2 was 0 on 20 layers, the warning of class
"spatialkit_no_structure" was raised on all 200, and a cell's pooled
value had a correlation of 0.79 with the mean of the pooled values of its 8
nearest cells, where the plain means had one of -0.02.
References
Faes, C., Molenberghs, G., Aerts, M., Verbeke, G. and Kenward, M. G. (2009). The effective sample size and an alternative small-sample degrees-of-freedom method. The American Statistician, 63(4), 389–399. doi:10.1198/tast.2009.08196
Satterthwaite, F. E. (1946). An approximate distribution of estimates of variance components. Biometrics Bulletin, 2(6), 110–114. doi:10.2307/3002019
See Also
assign_features_to_polygons(), which produces the input layer;
build_tessellation() for the cells themselves.
Other assign and summarise:
assign_features_to_polygons(),
cell_values_at(),
kriging_adequacy()
Examples
library(sf)
set.seed(1)
n <- 200
east <- runif(n, 0, 100)
north <- runif(n, 0, 100)
# A response with spatial structure, so the within-cell ICC is not zero.
pts <- st_as_sf(
data.frame(x = 5e5 + east, y = 5e6 + north,
val = 5 + 0.02 * east + 0.02 * north + rnorm(n, sd = 0.5)),
coords = c("x", "y"), crs = 32632
)
bnd <- st_sf(geometry = st_sfc(st_polygon(list(rbind(
c(5e5, 5e6), c(5e5 + 100, 5e6), c(5e5 + 100, 5e6 + 100),
c(5e5, 5e6 + 100), c(5e5, 5e6)
))), crs = 32632))
grid <- create_grid_polygons(bnd, target_cells = 9, type = "square")
assigned <- assign_features_to_polygons(pts, grid)
# Nine cells are too few for pooled values (each would be pulled toward
# all the other cells), so these summaries report plain means alone:
# estimate = "mean".
# IID standard errors (default) against the Kish design effect. The Kish
# correction is large here: about 22 points per cell that share the cell's
# part of the trend carry far fewer than 22 independent pieces of
# information about the cell mean.
naive <- summarize_by_cell(assigned, response_var = "val", estimate = "mean")
kish <- summarize_by_cell(assigned, response_var = "val", deff = "kish",
estimate = "mean")
data.frame(n = naive$n,
se_naive = naive$..se_resp_val,
se_kish = kish$..se_resp_val)
attr(kish, "deff_applied") # method, icc_resp, icc_pred, per-cell deff
# A 95% interval for each cell mean as an estimate of the grand mean, on
# the Kish-corrected standard error and n - 1 degrees of freedom.
ci <- summarize_by_cell(assigned, response_var = "val", deff = "kish",
conf_level = 0.95, estimate = "mean")
ci[, c("poly_id", "n", "resp_mean_val", "..neff_resp_val", "..df_resp_val",
"..ci_lo_resp_val", "..ci_hi_resp_val")]
# Pooled values, and a range for one observation: a smooth field plus
# noise at 400 points, on an 8 x 8 grid, so that a cell holds about six.
set.seed(2)
east <- runif(400, 0, 8000)
north <- runif(400, 0, 8000)
pts2 <- st_as_sf(
data.frame(x = 5e5 + east, y = 5e6 + north,
val = 10 + 3 * sin(east / 1500) + 3 * cos(north / 1200) +
rnorm(400)),
coords = c("x", "y"), crs = 32632
)
bnd2 <- st_sf(geometry = st_sfc(st_polygon(list(rbind(
c(5e5, 5e6), c(5e5 + 8000, 5e6), c(5e5 + 8000, 5e6 + 8000),
c(5e5, 5e6 + 8000), c(5e5, 5e6)
))), crs = 32632))
grid2 <- create_grid_polygons(bnd2, target_cells = 64, type = "square")
assigned2 <- assign_features_to_polygons(pts2, grid2)
# estimate = "pooled" is the default.
pooled <- summarize_by_cell(assigned2, response_var = "val", obs_level = 0.90)
# The plain mean, the pooled value and the weight on the cell's own mean.
head(pooled[, c("poly_id", "n", "resp_mean_val", "..pooled_resp_val",
"..pooled_w_resp_val")])
# The range for one further observation in a cell.
head(pooled[, c("poly_id", "..obs_lo_resp_val", "..obs_hi_resp_val")])
attr(pooled, "pooled") # what was fitted, and what the interval covers
Compare every criterion's pick on a resolution profile
Description
select_resolution() reads one criterion at a time. This puts
the count criteria in one table: the level each prefers, the flat region
around it, and whether a ladder bound is doing the choosing rather than
the criterion. The closing line gives the levels that lie in every
flat region, the cell counts no criterion objects to.
Usage
## S3 method for class 'resolution_profile'
summary(object, criteria = NULL, tol = 0.02, ...)
Arguments
object |
A |
criteria |
Character vector, any of |
tol |
Passed to |
... |
Ignored. |
Details
Read the table with what each criterion returns in mind (see
resolution_profile()): reliability is read at or
above the range floor and often returns it, elbow is absent unless
the points cluster, and
cp's optimum is often the support ceiling. moran_z is a
diagnostic of the cell means and not a count rule, so it is not in the
default set; named in criteria it gets a row, and it is left out
of the closing comparison.
The criterion curves are not monotone, so a flat region can skip rungs
of the ladder, and the table lists the levels it accepts
("26, 31") rather than a range ("26 to 31") that would
include the levels it rejected.
The levels common to every flat region are often none. The criteria
answer different questions: how well the cells represent the field
(C_p), whether the cell values are distinguishable from noise
(reliability), and where the within-cluster sum of squares bends
(elbow). An empty set means the criteria favour different
counts, and the print gives the spread between the picks.
A flat region can be wide, and the choice within it is the analyst's;
plot.resolution_profile() draws the curves the regions were
read from.
A profile whose ladder is one size (obs_per_cell set to one
number, or the default profile) has one level, and the size set it. The
table then has one row per criterion that is finite at that level, and
the line under it says
that the count is set by the size and that no criterion chooses among
levels. The result carries the size as attr(, "obs_per_cell").
Value
A data.frame of class resolution_summary, one row per
criterion in the order given, with columns criterion,
best, flat_min, flat_max, n_flat,
value (the optimum itself, on that criterion's own scale and so
not comparable across rows, which is why the print method leaves it out),
at_floor, at_ceiling, edge (which bound an
edge optimum sits on, as select_resolution() reports it;
NA when interior) and structured (as
select_resolution() reports it: FALSE for a cp
that one cell matches, and where the cells beat one cell but the F test
does not tell their means from one mean or, for cp, the
profile's variogram found no spatial structure). Attributes:
bands (a named list holding each
criterion's flat region in full, since flat_min and
flat_max are only its ends and the region can have holes in it),
common (the levels in every flat region of the count criteria,
moran_z left out; an integer vector that is
empty when the regions do not overlap), scored (the levels each
criterion returned a finite value at, which is what decides whether a gap
in a flat region is a rejection or a level nothing was computed at),
ladder (every level on the profile), n_levels, tol
and variable (what the criteria were scored on), and, only when
some row has structured FALSE although its cells beat one
cell by more than tol, not_identified (a character vector
named by criterion that says why: the F test, or for cp the
profile's variogram). The print method recomputes the closing
comparison from bands, so a row subset of the result prints its
own comparison.
See Also
select_resolution() for one criterion, with the
per-level values attached; plot.resolution_profile() for
the curves behind these flat regions.
Other resolution:
determine_optimal_levels(),
plot.resolution_profile(),
resolution_profile(),
select_resolution()
Examples
library(sf)
# An exponential field with range parameter 200 (true effective range
# 600 m) on a 1 km square, with a nugget of 0.6 on a unit sill.
set.seed(4)
n <- 400
xy <- data.frame(x = 5e5 + runif(n, 0, 1000), y = 5e6 + runif(n, 0, 1000))
D <- as.matrix(dist(xy))
xy$z <- as.numeric(t(chol(exp(-D / 200) + diag(0.6, n))) %*% rnorm(n))
pts <- st_as_sf(xy, coords = c("x", "y"), crs = 32632)
prof <- resolution_profile(pts, response_var = "z", n_levels = 12,
estimate = NULL)
s <- summary(prof)
s
attr(s, "common") # the levels every flat region accepts, if any
attr(s, "bands") # each criterion's flat region in full
Summarise a fitted model
Description
Computes goodness-of-fit metrics from fitted(object) against the
observed response, and prints them with what they are to be read
against. A character or factor response is an error; a logical response
is scored as 0/1.
Usage
## S3 method for class 'spatial_fit'
summary(object, ...)
Arguments
object |
A |
... |
Not used. |
Value
An object of class summary.spatial_fit: a list with
class, formula, n, response_var,
predictor_vars, info and in_sample (the metric
data.frame, out-of-bag for an rf_fit).
What the metrics are computed on
For a GWR or a Bayesian GP fit these are in-sample metrics:
fitted() returns values computed at the training locations from
the model that saw them. For a random forest they are out-of-bag,
because fitted() on an rf_fit returns out-of-bag
predictions (see fit_rf_model()). The two are not
comparable, and print() on the result says which one it holds,
from $info$fitted_are_oob. Use compare_models_cv() to
compare backends.
Adjusted R^2 is not computed: a GWR's effective number of
parameters far exceeds the global predictor count, and a GP model has no
simple p.
For a GWR, print() on the result adds what the in-sample metrics
are to be read against: the effective number of parameters and residual
degrees of freedom, the number of local windows of deficient rank, the
number of locations when observations share one, and the AICc and RMSE of
one global least-squares regression on the same rows beside the fit's own
AICc ($info$global_ols; see fit_gwr_model()).
MAPE and SMAPE skip rows whose denominator is zero;
n_MAPE and n_SMAPE count the rows they used (see
"Percentage errors on responses with zeros" in
model_metrics()).
See Also
model_metrics() for the metrics alone, and on new
data.
Other fit methods:
plot.spatial_fit(),
print.spatial_fit(),
spatial_fit-coef,
spatial_fit-fitted,
spatial_fit-predict,
spatial_fit-residuals
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)
fit <- fit_rf_model(pts, "z", "a", num_trees = 50, seed = 1)
summary(fit) # out-of-bag metrics for a forest
Place seeds at k-means cluster centres
Description
Places k seed points at k-means cluster centres of the observed
coordinates, so seeds (and the Voronoi cells built from them) follow the
sampling density: clusters of observations attract seeds, empty ground gets
none. Use it when the cells should follow the data. With the default
density kind the cells hold similar numbers of observations once there
are more cells than clusters of points, which keeps per-cell aggregates in
summarize_by_cell() from resting on one or two observations. Plain
k-means (partition = "kmeans") minimises the spread of points around
each centre and does not even out the counts. Use
voronoi_seeds_random() instead when you want coverage of the study area
rather than of the data, and get_voronoi_seeds() to pick between them by
name.
Usage
voronoi_seeds_kmeans(
points_sf,
k,
set_seed = 456,
nstart = NULL,
partition = c("density", "kmeans"),
init = NULL,
density_power = 1,
density_k = 8,
iter_max = NULL
)
Arguments
points_sf |
An sf object with POINT geometries. Points that mix XY and XYZ (or XYM) are read without Z and M before they are projected or clustered, since sf reads a layer in the dimension of its first geometry. |
k |
Integer; requested number of clusters, treated as an upper bound
only. It is clamped, with a warning, to whichever is smaller of the number
of distinct point positions and one fewer than the number of points with
a location (rows without one are dropped first), and not below 1, because
k-means can produce neither more centres than there are distinct points
nor as many centres as there are rows. Check |
set_seed |
Optional integer RNG seed. Default 456, so a call gives the
same seeds every time whatever the session's random-number state; an
outer |
nstart |
The number of starts, of which the best is kept. |
partition |
What the seeds minimise. |
init |
How each start is drawn: |
density_power |
For |
density_k |
For |
iter_max |
The most iterations a start runs for: a single positive
whole number, or |
Details
Lon/lat input is projected first so the k-means distances are metric and not
degrees; so is input with no CRS whose coordinates look like lon/lat (the
heuristic ensure_projected() applies, with its warning), and the seeds
come back in the input's own coordinates. Rows without a location (an
empty point, a coordinate that is not finite or lies beyond 1e150, or in
a geographic CRS a latitude beyond 90 degrees, read as given before the
projection) are dropped with a warning, and k is
clamped to the number of distinct positions or one fewer than the number
of points, whichever is smaller, and not below 1.
A count given as a number gets a fresh partition, which is not the
partition resolution_profile() or determine_optimal_levels() scored
that count on: those fit their own run, the profile to every row or to a
subsample, and keep the best of their own starts. Pass the
select_resolution() result or the profile itself as k to get the
scored one: the centres of the scored partition are then returned (in
the CRS of points_sf, with attr(, "n_from")), and no k-means is run.
On a profile without an estimate whose centres were fitted to a
subsample, they are those centres refitted to every point by
select_resolution(), with attr(, "refit").
partition says what the seeds minimise. "kmeans" is the sum of
squared distances from the points to their nearest seed, from nstart
random starts by stats::kmeans() (Hartigan-Wong) unless init says
otherwise. The seeds
follow the square root of the point density, so the cells are compact,
smaller where the points are dense, and a cell in a dense place still
holds several times the points of a cell in a sparse place. "density"
weights each point by its local density (the number of points in the disc
that reaches its density_k-th nearest neighbour, over the disc's area)
to the power density_power, and is the default. At the default power
of 1 the seeds follow the point density itself, and the cells are
compact: many small cells where the points are dense, a few large ones
where they are sparse. They
hold about the same number of points each once k is above the number
of dense places (clusters of points). With fewer cells than that a cell
takes in whole clusters, large and small, and the counts are about as
uneven as under "kmeans". The density kind is the best of
nstart starts, each refined by at most 100 steps of Lloyd's iteration
(iter_max sets another limit, and a kept start that was cut off at the
limit is a warning of class "spatialkit_not_converged");
it does not depend on the order of the rows or on the unit of the
coordinates, and points at one location share a cell. A seed can end
with no point at counts from about a fifth of the points up, mostly from
init = "random"; that is a warning of class "spatialkit_empty_cells".
"The partition" in
resolution_profile() gives the details and a comparison of the two
kinds.
The centres lie inside the points, so their own hull is smaller than the
data's. The result carries the convex hull of points_sf as
attr(, "cover"), and build_tessellation() clips the cells to that hull
(grown by 2 percent of its diagonal) when no boundary is passed, so every
point of points_sf falls in a cell.
Value
An sf object of at most k cluster-centre POINTs (fewer when
k is clamped, see k), with seed_id and
method = "kmeans" columns matching get_voronoi_seeds(), and
attr(, "cover"), the convex hull of the coordinates of points_sf
(an sfc in its CRS): for lon/lat points, the hull in degrees, with the
longitudes of points on both sides of 180 degrees taken from 0 to 360
(-170 as 190).
Seeds placed with partition = "density" or init = "kmeans++", and
the scored centres of a profile of the density kind or from random
starts, also carry attr(, "partition"): a list with
kind, init, density_power and density_k, and for seeds this
call placed iter, iter_max and converged (the iterations the kept
start took, the limit, and whether it stopped before the limit).
build_tessellation() returns the list as params$partition. Seeds
with no such record are plain k-means: from random starts when this call
placed them, or the scored centres of a k-means profile from k-means++
starts. When k is a
select_resolution() result that carries count_rule, or a profile
built with an estimate or read by cp, the seeds carry that record as
attr(, "count_rule"), with scored_cells TRUE for the scored
centres and FALSE for refitted centres and for centres this call fits
itself at that count (see get_voronoi_seeds()).
See Also
Other cell building:
build_tessellation(),
clip_target_for(),
create_grid_polygons(),
create_grid_polygons_cached(),
create_voronoi_polygons(),
ensure_stable_poly_id(),
get_voronoi_seeds(),
plot_tessellation_map(),
voronoi_seeds_random()
Examples
library(sf)
set.seed(1)
pts <- st_as_sf(
data.frame(x = 5e5 + runif(100, 0, 1000), y = 5e6 + runif(100, 0, 1000)),
coords = c("x", "y"), crs = 32632
)
seeds <- voronoi_seeds_kmeans(pts, k = 8) # density-weighted, 3 starts
nrow(seeds) # at most 8: one seed per non-empty cluster
seeds # the cluster centres, as an sf POINT layer in the points' CRS
# Plain k-means from 10 random starts.
voronoi_seeds_kmeans(pts, k = 8, partition = "kmeans")
Place seeds at random inside a boundary
Description
Draws k seed points uniformly at random inside boundary, ignoring where
the observations are. Reach for this when the cells should cover the study
area evenly (so that sparsely sampled ground still gets its own cells and
is visibly under-sampled in the results) instead of concentrating
resolution where the data already are, which is what
voronoi_seeds_kmeans() does. It also suits a null or sensitivity
comparison: rerunning an analysis over several random seedings shows how
much of a result depends on one tessellation.
Usage
voronoi_seeds_random(boundary, k, set_seed = NULL)
Arguments
boundary |
An sf or sfc polygonal object, the area the seeds are
drawn in. Rows without a location, rows the repair leaves without a
polygon, vertices at a latitude beyond 90 and mixed dimensions are
handled as "Boundaries" in spatialkit-geometry says. The seeds are
drawn as "Sampling inside the boundary" in |
k |
Integer; number of random seeds. |
set_seed |
Optional integer RNG seed. Default |
Details
Seeds are drawn uniformly inside the polygon. When a draw falls short of k
it is topped up with further uniform draws from the same polygon, so the
result has exactly k seeds; only a geometry that still yields too few
after ten top-ups returns fewer, and that shortfall is logged.
Value
An sf object of k random POINTs (fewer only in the degenerate
case above), with seed_id and method = "random" columns matching
get_voronoi_seeds(), and attr(, "cover"), the polygons of boundary:
build_tessellation() clips the cells to it (grown by 2 percent of its
diagonal) when no boundary is passed there, so the cells fill the area
the seeds were drawn in and not only the seeds' own hull.
See Also
Other cell building:
build_tessellation(),
clip_target_for(),
create_grid_polygons(),
create_grid_polygons_cached(),
create_voronoi_polygons(),
ensure_stable_poly_id(),
get_voronoi_seeds(),
plot_tessellation_map(),
voronoi_seeds_kmeans()
Examples
library(sf)
bnd <- st_sf(geometry = st_sfc(st_polygon(list(rbind(
c(0, 0), c(100, 0), c(100, 100), c(0, 100), c(0, 0)
))), crs = 32632))
set.seed(1)
seeds <- voronoi_seeds_random(bnd, k = 10)
nrow(seeds) # 10
seeds
# Another call is another seeding; set_seed pins one.
identical(st_coordinates(voronoi_seeds_random(bnd, k = 10, set_seed = 7)),
st_coordinates(voronoi_seeds_random(bnd, k = 10, set_seed = 7)))