Package {spmboost}


Type: Package
Title: Model-Based Boosting with Gaussian Process Spatial Effects
Version: 0.2.0
Description: Componentwise gradient boosting for point-referenced spatial data, extending 'mboost'. In every boosting iteration, a Gaussian process spatial effect is re-estimated by (restricted) maximum likelihood with 'spmodel', and the base-learners are fitted to the residual after removing it. Predictions at new locations are obtained by kriging. A threshold on the spatial share of the residual variance allows the spatial effect to be dropped when it is negligible. Includes spatial and random cross-validation for choosing the number of boosting iterations.
URL: https://github.com/larsknieper/spmboost
BugReports: https://github.com/larsknieper/spmboost/issues
Depends: R (≥ 3.5.0), mboost
Imports: spmodel, sf, spatialsample, parallel, stats, utils, graphics
License: GPL-2
Encoding: UTF-8
Config/roxygen2/version: 8.0.0
NeedsCompilation: no
Packaged: 2026-11-11 17:39:19 UTC; lars
Author: Lars Knieper [aut, cre]
Maintainer: Lars Knieper <lars.knieper@uni-goettingen.de>
Repository: CRAN
Date/Publication: 2026-12-02 13:00:02 UTC

Create cross-validation folds for spmboost models

Description

Builds a fold matrix for spat_cvrisk(): spatial folds via spatialsample, or ordinary random k-fold CV via mboost::cv().

Usage

## S3 method for class 'spat_cv_boost'
autoplot(object, ...)

spat_cv(
  data,
  k = 10,
  coords = NULL,
  cv_type = c("spatial", "block", "buffered", "loo", "random"),
  crs = NA,
  loo_group = NULL,
  radius = NULL,
  buffer = NULL,
  ...
)

Arguments

object

A fold matrix of class "spat_cv_boost" from spat_cv().

...

Further arguments passed to the spatialsample function (used for "buffered" and "loo").

data

A data.frame (then coords is required for the spatial types) or an sf object.

k

Number of folds.

coords

Character vector of length 2: names of the x- and y-coordinate columns in data. Ignored for sf data and for cv_type = "random".

cv_type

Type of cross-validation:

"spatial"

Spatial clustering CV: locations are clustered into k groups (spatialsample::spatial_clustering_cv()).

"block"

Spatial block CV: the domain is cut into blocks that are assigned to folds (spatialsample::spatial_block_cv()).

"buffered"

Random k-fold CV with an exclusion buffer around each test fold (spatialsample::spatial_buffer_vfold_cv()); see buffer.

"loo"

Leave-location-out CV: groups given by loo_group are held out together (spatialsample::spatial_leave_location_out_cv()).

"random"

Ordinary (non-spatial) random k-fold CV, folds drawn by mboost::cv(type = "kfold"). Needs no coordinates.

crs

Coordinate reference system used when converting a data.frame to sf (ignored for sf data and cv_type = "random"). The default NA uses plain Euclidean distances between the coordinates, matching the distances used by spmboost(). If the coordinates are longitude/latitude, set crs = 4326 (or project them first).

loo_group

Name of the grouping column for cv_type = "loo".

radius, buffer

For cv_type = "buffered" (both required there, in the units of the coordinates): observations within radius of a randomly chosen test observation are added to its test fold, and observations within buffer of the test fold are excluded from training. Excluded observations are coded -1 in the returned matrix.

Value

A numeric ⁠N x k⁠ matrix of class "spat_cv_boost", one column per fold, with 1 = training and 0 = test observation (and -1 = excluded, for the buffer of cv_type = "buffered"). Every observation is in exactly one test fold, except for "buffered" with radius > 0, where test folds can overlap. For the spatial types, the underlying spatialsample object is attached as attribute "cv_object", which autoplot() uses to plot the folds (not available for "random").

See Also

spat_cvrisk()

Examples

set.seed(1)
dat <- data.frame(sx = runif(200), sy = runif(200), y = rnorm(200))

# spatial clustering CV and ordinary random CV, 5 folds each
f_sp <- spat_cv(dat, k = 5, coords = c("sx", "sy"))
f_rd <- spat_cv(dat, k = 5, cv_type = "random")
colSums(f_sp == 0)   # test-fold sizes

# buffered CV: points within 0.1 of a test fold are left out of training
f_bf <- spat_cv(dat, k = 5, coords = c("sx", "sy"), cv_type = "buffered",
                radius = 0.05, buffer = 0.1)
table(f_bf[, 1])     # -1 = excluded, 0 = test, 1 = training


# plot the spatial folds
spatialsample::autoplot(f_sp)



Extract the estimated spatial effect of an spmboost model

Description

Returns the spatial part of a fitted spmboost() model for one boosting iteration: the fitted spatial effect at the training locations, the estimated spatial covariance parameters, and whether the spatial effect was included in that iteration (see spat_threshold in spmboost()).

Usage

extract_spatial(object, iteration = mstop(object))

Arguments

object

A fitted model of class "spmboost".

iteration

Boosting iteration to extract, between 1 and mstop(object). Defaults to the final iteration, mstop(object).

Details

For the spatial effect at new locations use predict(object, newdata, spatial = "only"), which krigs it.

Value

A list with elements

fitted

Numeric vector (one value per training observation) of the fitted spatial effect \hat s at the training locations. All zeros if the spatial effect was not included in this iteration.

SpatCov

Estimated spatial covariance parameters from spmodel::splm() (class of the covariance type): de (partial sill, \hat\sigma_s^2), ie (nugget, \hat\sigma^2), range, plus rotate/scale (anisotropy) and extra where applicable. Both de and ie are variances. Reported even if the spatial effect was not included.

share

Spatial share of the residual variance, \hat\sigma_s^2 / (\hat\sigma_s^2 + \hat\sigma^2).

included

Logical: was the spatial effect included in this iteration, i.e. share >= spat_threshold?

See Also

spmboost(), predict.spmboost()

Examples

set.seed(1)
n   <- 100
dat <- data.frame(sx = runif(n), sy = runif(n), x1 = runif(n))
D   <- as.matrix(dist(dat[, c("sx", "sy")]))
dat$y <- sin(2 * pi * dat$x1) + drop(t(chol(exp(-D / 0.3))) %*% rnorm(n)) +
  rnorm(n, sd = 0.3)
mod <- spmboost(y ~ bbs(x1), data = dat, spcov_type = "exponential",
                xcoord = "sx", ycoord = "sy",
                control = boost_control(mstop = 20))

sp <- extract_spatial(mod)
sp$SpatCov       # partial sill (de), nugget (ie), range
sp$share         # spatial share of the residual variance

# estimated partial sill along the boosting path
plot(sapply(1:20, function(m) extract_spatial(mod, m)$SpatCov[["de"]]),
     type = "l", xlab = "iteration", ylab = "partial sill")


Fitted values of an spmboost model

Description

In-sample fitted values on the response scale, including the spatial effect, i.e. predict(object, type = "response").

Usage

## S3 method for class 'spmboost'
fitted(object, spatial = TRUE, ...)

Arguments

object

A fitted model of class "spmboost".

spatial

Include the spatial effect (TRUE, default) or not.

...

Further arguments passed to predict.spmboost().

Value

Numeric vector of fitted values, one per training observation.

See Also

predict.spmboost()


Predictions from an spmboost model

Description

Predicts the additive predictor of an spmboost() model, by default including the spatial effect, which is kriged to new locations.

Usage

## S3 method for class 'spmboost'
predict(
  object,
  newdata = NULL,
  spatial = TRUE,
  type = c("link", "response", "class"),
  which = NULL,
  aggregate = c("sum", "cumsum", "none"),
  local = NULL,
  ...
)

Arguments

object

A fitted model of class "spmboost".

newdata

Optional data.frame (or sf object with POINT geometries, transformed to the CRS of the training data) with the covariates and – whenever the spatial effect is needed – the coordinate columns used in spmboost(). If NULL, predictions are for the training data.

spatial

What to do with the spatial effect: TRUE (default) adds the kriged spatial effect, FALSE predicts without it (no coordinates needed), "only" returns the kriged spatial effect alone (final iteration; not combined with aggregate = "cumsum").

type

Scale of the predictions: "link" (default), "response", or "class" (binomial only).

which

Optional subset of base-learners (names or indices). Then, as in mboost::predict.mboost(), the contributions of these base-learners are returned, without intercept and spatial effect.

aggregate

"sum" (default): prediction at mstop; "cumsum": matrix with one column per iteration ⁠1, ..., mstop⁠ (used by spat_cvrisk()); "none": per-iteration contributions of the base-learners, as in mboost (without intercept and spatial effect).

local

Optional integer k: krige with the k nearest training locations instead of all of them – an approximation that keeps prediction cheap for very large data. Used automatically (with k = 100) when the model was fitted with local fitting (N > 3000).

...

Further arguments passed to mboost::predict.mboost().

Details

The predictor at iteration m is

\hat\eta = f^{[m]} + \hat\beta_0^{[m]} + \hat s^{[m]},

with f^{[m]} the offset plus all base-learner contributions, \hat\beta_0^{[m]} the intercept of the spatial model and \hat s^{[m]} the spatial effect, kriged from the training locations with that iteration's covariance parameters. If the spatial effect was excluded in an iteration (see spat_threshold in spmboost()), \hat s^{[m]} = 0.

Value

A numeric vector (or a matrix for aggregate = "cumsum" and "none", as in mboost).

See Also

spmboost(), extract_spatial()

Examples

set.seed(1)
n   <- 100
dat <- data.frame(sx = runif(n), sy = runif(n), x1 = runif(n))
D   <- as.matrix(dist(dat[, c("sx", "sy")]))
dat$y <- sin(2 * pi * dat$x1) + drop(t(chol(exp(-D / 0.3))) %*% rnorm(n)) +
  rnorm(n, sd = 0.3)
mod <- spmboost(y ~ bbs(x1), data = dat, spcov_type = "exponential",
                xcoord = "sx", ycoord = "sy",
                control = boost_control(mstop = 20))

new <- data.frame(sx = c(0.2, 0.8), sy = c(0.5, 0.5), x1 = 0.5)
predict(mod, newdata = new)                     # with spatial effect
predict(mod, newdata = new, spatial = FALSE)    # without
predict(mod, newdata = new, spatial = "only")   # spatial effect alone
dim(predict(mod, newdata = new, aggregate = "cumsum"))


Methods for cross-validation results

Description

mstop() returns the CV-optimal number of boosting iterations; plot() shows the out-of-sample risk of every fold (grey), their average (black) and the optimal iteration (dashed line).

Usage

## S3 method for class 'spat_cv'
mstop(object, ...)

## S3 method for class 'spat_cv'
plot(x, main = "CV Risks", ...)

Arguments

object, x

An object of class "spat_cv" from spat_cvrisk().

...

Not used (mstop()), or further graphical parameters passed to graphics::plot().

main

Plot title.

Value

mstop(): the CV-optimal number of iterations. plot(): called for its side effect.

See Also

spat_cvrisk()


Cross-validated risk for choosing mstop of an spmboost model

Description

For every fold, refits spmboost() on the training part with the settings of object, predicts the test part for every iteration ⁠1, ..., mstop(object)⁠, and evaluates the out-of-sample risk. The iteration with the lowest average risk is the CV-optimal mstop.

Usage

spat_cvrisk(object, folds, cores = 1, include_spatial = FALSE)

Arguments

object

A fitted model of class "spmboost". Its current mstop (also after object[m]) is the largest number of iterations evaluated.

folds

Fold matrix, typically from spat_cv(): ⁠N x k⁠, 1 = training, 0 = test (any other value, e.g. -1 for buffered CV, = excluded from both), with rows matching object$data.

cores

Number of cores; folds are run in parallel via parallel::mclapply() (forking – on Windows only cores = 1 works).

include_spatial

Logical. If TRUE, the test predictions include the kriged spatial effect (offset + base-learners + intercept + \hat s), which is appropriate when test locations lie within the observed domain (e.g. random folds). If FALSE (default), only the non-spatial part is used (offset + base-learners + intercept).

Details

Each refit uses the same boost_formula, spcov_type, coordinates, estmethod, spat_threshold, spmodel_control, offset, family, control and baselearner as object. Arguments that were passed to spmboost() via ... or weights are not stored and therefore not used in the refits.

The risk per iteration is the squared error for the Gaussian family and half the AIC (i.e. the negative log-likelihood) otherwise, divided by the size of the test fold, so folds of different sizes are comparable.

mboost::cvrisk() cannot be used for spmboost models.

Value

An object of class "spat_cv" with elements

cv_risks

⁠mstop x k⁠ matrix of out-of-sample risks per iteration and fold.

avg_risks

Average risk per iteration (row means of cv_risks).

m_opt

CV-optimal number of iterations, also returned by mstop().

folds

The fold matrix used.

plot() shows the risk paths of all folds and their average.

See Also

spat_cv(), spmboost()

Examples


set.seed(1)
n   <- 60
dat <- data.frame(sx = runif(n), sy = runif(n), x1 = runif(n))
D   <- as.matrix(dist(dat[, c("sx", "sy")]))
dat$y <- sin(2 * pi * dat$x1) + drop(t(chol(exp(-D / 0.3))) %*% rnorm(n)) +
  rnorm(n, sd = 0.3)

mod   <- spmboost(y ~ bbs(x1), data = dat, spcov_type = "exponential",
                  xcoord = "sx", ycoord = "sy",
                  control = boost_control(mstop = 20))
folds <- spat_cv(dat, k = 3, cv_type = "random")
cvr   <- spat_cvrisk(mod, folds, include_spatial = TRUE)
mstop(cvr)
plot(cvr)

# set the model to the CV-optimal number of iterations
# (same result as refitting with mstop = mstop(cvr))
mod <- mod[mstop(cvr)]



Model-based boosting with a Gaussian Process spatial effect

Description

Fits a componentwise gradient boosting model (via mboost::mboost()) in which a Gaussian-process spatial effect is re-estimated in every boosting iteration by spmodel::splm().

Usage

spmboost(
  boost_formula,
  data = list(),
  spcov_type = "gaussian",
  xcoord = NULL,
  ycoord = NULL,
  estmethod = "reml",
  spat_threshold = 0,
  spmodel_control = list(),
  na.action = na.omit,
  weights = NULL,
  offset = NULL,
  family = gaussian(),
  control = boost_control(),
  oobweights = NULL,
  baselearner = c("bbs", "bols", "btree", "bss", "bns"),
  verbose = FALSE,
  ...
)

Arguments

boost_formula

Formula for the boosted (non-spatial) part, as in mboost::mboost().

data

A data.frame with coordinate columns, or an sf object with POINT geometries (other geometries are replaced by their centroids). An sf object is converted to a data.frame once, up front: its coordinates become ordinary columns named xcoord/ycoord (default ".xcoord", ".ycoord"), and its CRS is stored so that sf newdata in predict() is transformed to the same CRS. Distances are Euclidean, so use a projected CRS.

spcov_type

Spatial covariance type passed to spmodel::splm(), e.g. "gaussian" (default), "exponential", "matern".

xcoord, ycoord

Names of the x- and y-coordinate columns in data. Required for a data.frame; optional for sf data (then they name the coordinate columns that are created from the geometry).

estmethod

Estimation method for the spatial covariance parameters, passed to spmodel::splm(): one of "reml" (default), "ml", "sv-wls", "sv-cl".

spat_threshold

Threshold t_s \in [0, 1) on the spatial share of the residual variance, \hat\sigma_s^2 / (\hat\sigma_s^2 + \hat\sigma^2) (partial sill / (partial sill + nugget)). In every boosting iteration in which the share falls below spat_threshold, no spatial effect is included: it is set to zero in the negative gradient, the risk and the predictor, so the base-learners are fitted to the residual without it, and the intercept is the plain mean. The spatial model is still fitted in every iteration; if the share stays below spat_threshold throughout, the result is a fixed-effects-only model. The default 0 always includes the spatial effect.

spmodel_control

Named list of further arguments for spmodel::splm(): spcov_initial, weights (splm's semivariogram weights, e.g. "cressie" – not to be confused with the boosting weights below), anisotropy, random, randcov_initial, partition_factor, local, range_constrain, ddf, or arguments passed on to stats::optim() (e.g. method, control). Merged over the package default list(range_constrain = TRUE); set an element to NULL to drop that default and use splm()'s own. formula, data, spcov_type, xcoord, ycoord and estmethod are set by spmboost() itself and must not appear here. Note that splm() ignores spcov_type when spcov_initial is given, and that spcov_initial and local only affect the initial fit – from the first boosting iteration on, both are managed internally (warm starts, and local fitting for large N).

na.action, weights, offset, control, oobweights, baselearner, ...

Arguments passed to mboost::mboost(). If offset is NULL, the link of the mean response is used.

family

Response distribution. Currently only gaussian() with identity link is supported (as family object, function or name); other families give an error.

verbose

Logical; if TRUE, print progress messages of the spatial fits (cold restarts of the covariance optimisation, local fitting for large N). Default FALSE.

Value

An object of class c("spmboost", "mboost"). Besides the usual mboost methods, see predict.spmboost() for predictions including the kriged spatial effect and extract_spatial() for the spatial fit.

See Also

spat_cv() and spat_cvrisk() for choosing mstop, extract_spatial()

Examples

set.seed(1)
n   <- 100
dat <- data.frame(sx = runif(n), sy = runif(n),
                  x1 = runif(n), x2 = rnorm(n))
# spatial effect: Gaussian process with exponential covariance
D <- as.matrix(dist(dat[, c("sx", "sy")]))
s <- drop(t(chol(exp(-D / 0.3))) %*% rnorm(n))
dat$y <- 1 + sin(2 * pi * dat$x1) + 0.5 * dat$x2 + s + rnorm(n, sd = 0.3)

mod <- spmboost(y ~ bbs(x1) + bols(x2), data = dat,
                spcov_type = "exponential",
                xcoord = "sx", ycoord = "sy",
                control = boost_control(mstop = 30))

# estimated covariance parameters (de = partial sill, ie = nugget) and
# spatial share of the residual variance
extract_spatial(mod)[c("SpatCov", "share")]

# selected base-learners and partial effect of x1
table(selected(mod))
plot(mod, which = "x1")

# predictions at new locations: full predictor and spatial effect only
new <- data.frame(sx = c(0.2, 0.8), sy = c(0.5, 0.5), x1 = 0.5, x2 = 0)
predict(mod, newdata = new)
predict(mod, newdata = new, spatial = "only")