Learn R Programming

glmmfields (version 0.1.7)

predict: Predict from a glmmfields model

Description

These functions extract posterior draws or credible intervals. The helper functions are named to match those in the rstanarm package and call the function predict() with appropriate argument values.

Usage

# S3 method for glmmfields
predictive_interval(object, ...)

# S3 method for glmmfields posterior_linpred(object, ...)

# S3 method for glmmfields posterior_predict(object, ...)

# S3 method for glmmfields predict( object, newdata = NULL, estimate_method = c("median", "mean"), conf_level = 0.95, interval = c("confidence", "prediction"), type = c("link", "response"), return_mcmc = FALSE, offset = NULL, iter = "all", ... )

Arguments

object

An object returned by glmmfields().

...

Ignored currently

newdata

Optionally, a data frame to predict on

estimate_method

Method for computing point estimate ("mean" or "median")

conf_level

Probability level for the credible intervals.

interval

Type of interval calculation. Same as for stats::predict.lm().

type

Whether the predictions are returned on "link" scale or "response" scale (Same as for stats::predict.glm()).

return_mcmc

Logical. Should the full MCMC draws be returned for the predictions?

offset

Optional offset vector to be used in prediction.

iter

Number of MCMC iterations to draw. Defaults to all.

Examples

Run this code
# \donttest{
library(ggplot2)

# simulate:
set.seed(1)
s <- sim_glmmfields(
  n_draws = 12, n_knots = 12, gp_theta = 2.5,
  gp_sigma = 0.2, sd_obs = 0.1
)

# fit:
# options(mc.cores = parallel::detectCores()) # for parallel processing
m <- glmmfields(y ~ 0,
  data = s$dat, time = "time",
  lat = "lat", lon = "lon",
  nknots = 12, iter = 800, chains = 1
)

# Predictions:
# Link scale credible intervals:
p <- predict(m, type = "link", interval = "confidence")
head(p)

# Prediction intervals on new observations (include observation error):
p <- predictive_interval(m)
head(p)

# Posterior prediction draws:
p <- posterior_predict(m, iter = 100)
dim(p) # rows are iterations and columns are data elements

# Draws from the linear predictor (not in link space):
p <- posterior_linpred(m, iter = 100)
dim(p) # rows are iterations and columns are data elements

# Use the `tidy` method to extract parameter estimates as a data frame:
head(tidy(m, conf.int = TRUE, conf.method = "HPDinterval"))

# Make predictions on a fine-scale spatial grid:
pred_grid <- expand.grid(
  lat = seq(min(s$dat$lat), max(s$dat$lat), length.out = 25),
  lon = seq(min(s$dat$lon), max(s$dat$lon), length.out = 25),
  time = unique(s$dat$time)
)
pred_grid$prediction <- predict(m,
  newdata = pred_grid, type = "response", iter = 100,
  estimate_method = "median", offset = rep(0, nrow(pred_grid))
)$estimate

ggplot(pred_grid, aes(lon, lat, fill = prediction)) +
  facet_wrap(~time) +
  geom_raster() +
  scale_fill_gradient2()
# }

Run the code above in your browser using DataLab