| Title: | Multivariate (Dynamic) Generalized Additive Models |
|---|---|
| Description: | Fit Bayesian Dynamic Generalized Additive Models to multivariate observations. Users can build nonlinear State-Space models that can incorporate semiparametric effects in observation and process components, using a wide range of observation families. Estimation is performed using Markov Chain Monte Carlo with Hamiltonian Monte Carlo in the software 'Stan'. References: Clark & Wells (2023) <doi:10.1111/2041-210X.13974>. |
| Authors: | Nicholas J Clark [aut, cre] (ORCID: <https://orcid.org/0000-0001-7131-3301>), KANK Karunarathna [ctb] (ARMA parameterisations and factor models, ORCID: <https://orcid.org/0000-0002-8995-5502>), Sarah Heaps [ctb] (VARMA parameterisations, ORCID: <https://orcid.org/0000-0002-5543-037X>), Scott Pease [ctb] (broom enhancements, ORCID: <https://orcid.org/0009-0006-8977-9285>), Matthijs Hollanders [ctb] (ggplot visualizations, ORCID: <https://orcid.org/0000-0003-0796-1018>) |
| Maintainer: | Nicholas J Clark <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 2.0.0.9000 |
| Built: | 2026-11-29 12:25:15 UTC |
| Source: | https://github.com/nicholasjclark/mvgam |
A factor model fitted with n_lv factors may need fewer. This
function counts the factors whose variance the data support. It
suits a fit under the multiplicative gamma process (MGP) prior,
loadings_prior = "mgp" (Bhattacharya and Dunson 2011). That prior
shrinks surplus factors toward zero. n_lv then acts as a ceiling.
The function applies to every factor model. Under other loadings
priors a surplus factor keeps the variance its prior gives it. The
count can then exceed the number of factors the data need.
active_factors(object, ...) ## S3 method for class 'mvgam' active_factors( object, criterion = c("relative", "cumulative"), threshold = NULL, prob = 0.5, ... ) ## S3 method for class 'mvgam_active_factors' plot(x, ...)active_factors(object, ...) ## S3 method for class 'mvgam' active_factors( object, criterion = c("relative", "cumulative"), threshold = NULL, prob = 0.5, ... ) ## S3 method for class 'mvgam_active_factors' plot(x, ...)
object |
A fitted |
... |
Unused. Anything passed here is refused. |
criterion |
The activity rule: |
threshold |
Numeric in |
prob |
Numeric in |
x |
An |
The factors give the series the covariance ,
where Z holds the loadings and the covariance of the
latent states. Its eigenvalues are the variances along its principal dimensions. Each
posterior draw gives one set. The eigenvalues stay the same when the
factors are rotated or relabelled, which the individual columns of
Z do not.
Two rules decide whether dimension k is active in a draw:
"relative"The dimension holds at least threshold
times the variance of the leading one,
threshold . The default
threshold is 0.1. The rule counts any number of factors of
similar size.
"cumulative"The dimension is among the fewest leading
dimensions whose variance reaches a share threshold of the
total. The default threshold is 0.9. The count is the
number of factors a scree plot would keep.
prob_active is the posterior probability that a dimension is
active. A dimension with prob_active >= prob is reported active.
The count is summarised over the per-draw counts.
Both rules compare the factors with one another. The leading
dimension is always active, which makes the count at least one. A
model whose factors hold almost no variance still reports one.
shared_variation() gives the size of that variance on the scale
of the linear predictor.
A list with class mvgam_active_factors containing:
count: the posterior median, q025 and q975 of the
per-draw count of active dimensions.
per_factor: data frame with one row per dimension,
largest first. Its columns are the factor rank, the
posterior prob_active, the posterior median_variance
, the posterior median_share of the total
variance and is_active.
threshold: list with criterion, value and prob.
n_lv: the number of factors the model was fitted with.
print() reports the posterior median count with its 95% interval.
plot() draws the posterior probability that each dimension is
active, largest first, with a dashed line at prob.
Nicholas J Clark
Bhattacharya, A. and Dunson, D. B. (2011). Sparse Bayesian infinite factor models. Biometrika, 98(2), 291-306. doi:10.1093/biomet/asr013.
shared_variation() reports the covariance the factors
give the series. compare_loadings() compares the loadings under
two priors. The JSDM article fits
an MGP prior and counts its active factors.
Other latent dynamics:
compare_loadings(),
fevd.mvgam(),
irf.mvgam(),
ordinate(),
posterior_transition_matrix(),
residual_cor(),
shared_variation(),
stability.mvgam()
## Not run: # Counts of 20 species at 100 sites, driven by two latent factors. # Each species has its own intercept and response to `env`. simdat <- sim_jsdgam(family = brms::negbinomial(), n_species = 20L, n_sites = 100L, n_lv = 2L, seed = 3L) # Up to five factors under the MGP prior, which shrinks the factors # the data do not need mod <- jsdgam( y ~ env * series, data = simdat$data_train, family = brms::negbinomial(), n_lv = 5L, loadings_prior = "mgp", chains = 2, silent = 2 ) # Dimensions holding at least a tenth of the leading one's variance af <- active_factors(mod) af plot(af) # The fewest dimensions that explain 90 percent of the variance active_factors(mod, criterion = "cumulative") # Next: ordinate() plots the species on the leading factors ## End(Not run)## Not run: # Counts of 20 species at 100 sites, driven by two latent factors. # Each species has its own intercept and response to `env`. simdat <- sim_jsdgam(family = brms::negbinomial(), n_species = 20L, n_sites = 100L, n_lv = 2L, seed = 3L) # Up to five factors under the MGP prior, which shrinks the factors # the data do not need mod <- jsdgam( y ~ env * series, data = simdat$data_train, family = brms::negbinomial(), n_lv = 5L, loadings_prior = "mgp", chains = 2, silent = 2 ) # Dimensions holding at least a tenth of the leading one's variance af <- active_factors(mod) af plot(af) # The fewest dimensions that explain 90 percent of the variance active_factors(mod, criterion = "cumulative") # Next: ordinate() plots the species on the leading factors ## End(Not run)
mvgam object's training data with fitted values
and residualsThe training data with posterior summaries of the fitted value and residual of each row, under broom's column names.
## S3 method for class 'mvgam' augment( x, robust = FALSE, conf.int = TRUE, conf.level = 0.95, resp = NULL, ... )## S3 method for class 'mvgam' augment( x, robust = FALSE, conf.int = TRUE, conf.level = 0.95, resp = NULL, ... )
x |
A fitted |
robust |
Logical. If |
conf.int |
Logical. |
conf.level |
Numeric. Probability covered by the
credible interval reported in |
resp |
Character specifying which response variable for multivariate models. NULL (default) returns predictions for all responses. |
... |
Unused. Anything passed here is refused. |
A tibble (or list, when class(x$data) == "list")
with the original training data plus:
.observed – the response value.
.fitted – the posterior mean (or median) fitted value.
.se.fit – the posterior standard deviation (or MAD) of
the fitted value.
.lower, .upper – the lower / upper bound of the
conf.level credible interval for .fitted. Present only
when conf.int = TRUE.
.resid – the posterior mean (or median) residual.
.resid.se – the posterior standard deviation (or MAD)
of the residual.
.resid.lower, .resid.upper – the residual credible
interval bounds. Present only when conf.int = TRUE.
.unit – only for closure-unit families (nmix(),
occ()): the closure-unit ID this row belongs to. Rows
sharing the same .unit share the same .resid* columns
(see below).
nmix(), occ()).fitted is the expected count of each visit: psi * p for
occ() and lambda * p for nmix(). residuals.mvgam()
computes one residual per closure unit, a site in a season, from
the PIT of the summed visit counts. Each visit row of a unit
repeats that residual. The .unit column names the unit.
fitted.mvgam(), residuals.mvgam()
Other tidiers:
glance.mvgam(),
tidy.mvgam()
## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # The training data with fitted values and residuals appended aug <- augment(mod) head(aug) # Residuals against fitted values, from one tibble library(ggplot2) ggplot(aug, aes(.fitted, .resid)) + geom_hline(yintercept = 0, linetype = "dashed") + geom_point(colour = "#8F2727", alpha = 0.6) + labs(x = "Fitted", y = "Residual") + mvgam_theme() # Next, glance() summarises the whole fit in one row ## End(Not run)## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # The training data with fitted values and residuals appended aug <- augment(mod) head(aug) # Residuals against fitted values, from one tibble library(ggplot2) ggplot(aug, aes(.fitted, .resid)) + geom_hline(yintercept = 0, linetype = "dashed") + geom_point(colour = "#8F2727", alpha = 0.6) + labs(x = "Fitted", y = "Residual") + mvgam_theme() # Next, glance() summarises the whole fit in one row ## End(Not run)
A three-parameter count family that mixes the negative binomial success probability over a Beta distribution. The tail follows a power law. It suits outbreak counts and boom-bust population series, where a negative binomial fits the bulk of the data but repeatedly underpredicts the largest observations.
beta_nb()beta_nb()
The family is parameterised with mu as the mean:
where r is shape and is mtail. Writing Stan's
native first Beta parameter as makes the
mean finite by construction. requires
.
The variance is finite only when mtail exceeds 1. Below that value,
the family is heavy-tailed. This is the behaviour the
family exists to provide. It has two consequences worth knowing.
Randomised quantile residuals, the default in residuals.mvgam(),
are unaffected. They need only the distribution function. Moment-based
scoring is affected. score(..., score = "dss") assumes a finite
predictive variance. Avoid it when the posterior for mtail places
appreciable mass below 1. Prefer "crps", "drps" or "logs".
As mtail grows the family converges to the negative binomial with
the same shape. A posterior for mtail that runs off toward its
prior upper range is evidence that the extra tail parameter is not
needed.
A customfamily object for use with mvgam().
muMean of the response, with a log link.
shapeNegative binomial shape r, log link, positive.
Default prior gamma(2, 0.5).
mtailTail parameter , log
link, positive. Smaller values give heavier tails; values
below 1 give infinite variance. Default prior
gamma(2, 0.25).
The Stan code supplies the distribution function as well as the
density. The cens() and trunc() addition terms work as they do
for the built-in count families.
Two limits are worth knowing. The distribution function accumulates the mass function term by term. Its cost and the length of the automatic-differentiation tape both grow linearly in the count at which it is evaluated. At the counts these models usually see this is unnoticeable. A censoring bound in the thousands dominates the gradient evaluation. One in the millions is impractical.
Right censoring also needs the upper tail, which is computed as
log1m_exp() of the distribution function. That subtraction loses
precision once the survival probability approaches the accumulated
rounding error, roughly when 1 - F(y) falls below y * 5e-16. A
censoring bound placed far into the tail of a light-tailed fit can
return a survival probability of zero. A small positive value is the
correct result there. Heavy-tailed fits, the purpose of this family,
keep 1 - F(y) large. They are unaffected.
Irwin, J. O. (1968). The generalized Waring distribution applied to accident theory. Journal of the Royal Statistical Society A, 131(2), 205-225. doi:10.2307/2343842
brms::negbinomial(), which this family approaches as
mtail grows. tweedie() covers non-negative continuous responses
with a point mass at zero.
Other observation families:
categ(),
com_binomial(),
diri(),
multi(),
mvgam_families,
mvn(),
mvt(),
nmix(),
occ(),
tweedie()
## Not run: # Counts drawn from the mixture in Details: a negative binomial # whose success probability follows a Beta distribution. The tail # is set by `mtail = 2`, the bulk by `shape = 3`. set.seed(1) n <- 300 dat <- data.frame(x = rnorm(n), time = seq_len(n)) mu <- exp(1 + 0.5 * dat$x) p <- rbeta(n, 1 + 2, mu * 2 / 3) dat$y <- rnbinom(n, size = 3, prob = p) mod <- mvgam(y ~ x, data = dat, family = beta_nb(), chains = 2, silent = 2) # The posteriors recover `shape` and `mtail`. A negative binomial # is the limit of a large `mtail`. summary(mod) mcmc_plot(mod, variable = c("shape", "mtail"), type = "areas") ## End(Not run)## Not run: # Counts drawn from the mixture in Details: a negative binomial # whose success probability follows a Beta distribution. The tail # is set by `mtail = 2`, the bulk by `shape = 3`. set.seed(1) n <- 300 dat <- data.frame(x = rnorm(n), time = seq_len(n)) mu <- exp(1 + 0.5 * dat$x) p <- rbeta(n, 1 + 2, mu * 2 / 3) dat$y <- rnbinom(n, size = 3, prob = p) mod <- mvgam(y ~ x, data = dat, family = beta_nb(), chains = 2, silent = 2) # The posteriors recover `shape` and `mtail`. A negative binomial # is the limit of a large `mtail`. summary(mod) mcmc_plot(mod, variable = c("shape", "mtail"), type = "areas") ## End(Not run)
how_to_cite objectJoins the BibTeX entries of how_to_cite() into one string. It is
printed, or written to file.
bibtex(x, ...) ## S3 method for class 'how_to_cite' bibtex(x, file = NULL, other = TRUE, ...)bibtex(x, ...) ## S3 method for class 'how_to_cite' bibtex(x, file = NULL, other = TRUE, ...)
x |
A |
... |
Unused. Anything passed here is refused. |
file |
Optional path of a |
other |
Logical. |
The string of entries separated by blank lines, invisibly.
how_to_cite() builds the object, with an example of both.
methods_md() writes the model's equations.
Other posterior summaries:
VarCorr.mvgam(),
how_to_cite.mvgam(),
hypothesis.mvgam(),
index-mvgam,
mcmc_plot.mvgam(),
methods_md(),
mvgam_draws,
pairs.mvgam(),
posterior_interval.mvgam(),
ranef.mvgam(),
smooths.mvgam(),
summary.mvgam()
A multivariate count time series for four bird species observed weekly across 80 weeks. Each species has its own AR(1) latent trend; the four series are coupled through a contemporaneous innovation correlation matrix. Two species (warbler, thrush) rise together; two (wren, finch) move opposite to them. A shared cyclic seasonal smooth is added on week-within-year.
birdsongbirdsong
A data.frame with 320 rows and the following fields:
factor identifying the species (warbler,
thrush, wren, finch); duplicated as species for
readability.
integer week index from 1 to 80.
integer weekly count (Poisson sampled); duplicated as
count.
factor, alias of series.
integer week index, alias of time.
integer week within the annual cycle (1..52), used for the shared seasonal smooth.
integer weekly count, alias of y.
An independent-AR fit (trend_formula = ~ AR(p = 1)) treats the
four trajectories as unrelated. trend_formula = ~ AR(p = 1, cor = TRUE) recovers the cross-species correlation that couples them.
True generative components:
Species random intercepts (centred) on the log scale.
Shared cyclic seasonal smooth (mgcv bs = "cc") on
week-within-year.
Hierarchically correlated AR(1) trends with phi = 0.7 and
innovation standard deviation 0.35. The 4 x 4 innovation
correlation matrix sets (warbler, thrush) against
(wren, finch).
AR() for the trend, residual_cor() to extract the fitted
correlations between species, mvgam_data() to check the data.
data(birdsong) mvgam_data(birdsong, family = poisson()) ## Not run: # A model with the structure the data were simulated from mod <- mvgam( formula = y ~ s(week_in_year, bs = "cc", k = 8) + s(species, bs = "re"), trend_formula = ~ AR(p = 1, cor = TRUE), data = birdsong, family = poisson(), chains = 2, silent = 2 ) summary(mod) ## End(Not run)data(birdsong) mvgam_data(birdsong, family = poisson()) ## Not run: # A model with the structure the data were simulated from mod <- mvgam( formula = y ~ s(week_in_year, bs = "cc", k = 8) + s(species, bs = "re"), trend_formula = ~ AR(p = 1, cor = TRUE), data = birdsong, family = poisson(), chains = 2, silent = 2 ) summary(mod) ## End(Not run)
mvgam fitsEstimates the log marginal likelihood of a fit by bridge sampling
(Gronau, Singmann and Wagenmakers 2020) and compares two fits by
their Bayes factor. The marginal likelihood weighs how well a model
explains the data under its prior. loo.mvgam() and
lfo_cv.mvgam() score predictions of held-out data instead. A
Bayes factor sets no forecast horizon, which makes it a complement
to leave-future-out scores for state-space models. It also
depends on the priors, which predictive scores barely do.
## S3 method for class 'mvgam' bridge_sampler(samples, recompile = FALSE, ...) ## S3 method for class 'mvgam' bayes_factor(x1, x2, log = FALSE, ...)## S3 method for class 'mvgam' bridge_sampler(samples, recompile = FALSE, ...) ## S3 method for class 'mvgam' bayes_factor(x1, x2, log = FALSE, ...)
samples |
An |
recompile |
Logical. Bridge sampling evaluates the density
through a compiled rstan model. A fit without one, sampled by
cmdstanr or loaded with |
... |
Arguments of |
x1, x2
|
|
log |
Logical. |
The Stan program must keep the normalising constants of its
densities. mvgam builds it that way by default. A fit built with
normalize = FALSE is refused. Bridge sampling also needs the draws
of every parameter, which a fit keeps under
save_pars = save_pars(all = TRUE).
bridge_sampler() returns a bridge object holding the
log marginal likelihood in logml. bayes_factor() returns a
bayes_factor object.
The Stan program of an mvbf() fit has
one joint log posterior over every response. bridge_sampler()
then estimates the joint log marginal likelihood
. The
variance of the estimate grows with the number of parameters. For
multi-response, factor or VAR fits, pass repetitions above 1 or
method = "warp3" when the default method reports a high re2
(relative squared error).
Nicholas J Clark
Gronau QF, Singmann H and Wagenmakers E-J (2020). bridgesampling: An R package for estimating normalizing constants. Journal of Statistical Software. 92(10).
loo.mvgam(), lfo_cv.mvgam(). The
forecast evaluation article
compares models by their forecasts.
Other model comparison:
compare_elpds(),
kfold.mvgam(),
lfo_cv.mvgam(),
log_lik.mvgam(),
loo.mvgam(),
loo_compare.mvgam_lfo(),
mvgam_loo_extras,
posterior_average.mvgam(),
waic.mvgam()
## Not run: set.seed(1) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 80L, trend_model = AR()) # Bridge sampling needs many draws and every parameter's draws. It # evaluates the density through rstan. A fit sampled by rstan needs # no second compile. mod_ar <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), save_pars = save_pars(all = TRUE), backend = "rstan", chains = 2, iter = 3000, silent = 2) mod_rw <- update(mod_ar, trend_formula = ~ RW()) # The log marginal likelihood of each model bs_ar <- bridge_sampler(mod_ar, silent = TRUE) bs_rw <- bridge_sampler(mod_rw, silent = TRUE) bs_ar # A Bayes factor above 1 favours the AR(1) trend. Passing the # bridge objects reuses their estimates. bayes_factor(bs_ar, bs_rw) # Next, compare their forecasts with loo() or lfo_cv() ## End(Not run)## Not run: set.seed(1) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 80L, trend_model = AR()) # Bridge sampling needs many draws and every parameter's draws. It # evaluates the density through rstan. A fit sampled by rstan needs # no second compile. mod_ar <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), save_pars = save_pars(all = TRUE), backend = "rstan", chains = 2, iter = 3000, silent = 2) mod_rw <- update(mod_ar, trend_formula = ~ RW()) # The log marginal likelihood of each model bs_ar <- bridge_sampler(mod_ar, silent = TRUE) bs_rw <- bridge_sampler(mod_rw, silent = TRUE) bs_ar # A Bayes factor above 1 favours the AR(1) trend. Passing the # bridge objects reuses their estimates. bayes_factor(bs_ar, bs_rw) # Next, compare their forecasts with loo() or lfo_cv() ## End(Not run)
For a single category recorded on each unit, such as the dominant
species at a site. The data hold one row per category at each unit,
with response 1 on the observed category and 0 on the others. The
observed category is categorical with probabilities softmax(mu),
where mu holds the categories' linear predictors.
categ()categ()
jsdgam() fits the family, taking the unit and category columns
and the number of latent factors n_lv. The constraints that
identify the model are those of diri(). A unit holds one trial.
It informs the factor loadings less than a multi() unit of many
counts does. Recovering the residual correlations needs more
units.
A family object to pass to jsdgam() or mvgam().
The softmax is unchanged when the same constant is added to every component. The data then identify neither a shift of the linear predictors that every component shares nor a shift of the loadings that every component shares. mvgam removes both:
The first component is the reference. Its linear predictor
is subtracted from every component's before the softmax, as in
brms's dirichlet() family. A term that acts on every
component alike, such as Intercept or env in
y ~ env * series, then cancels. Its posterior is its prior,
student_t(3, 0, 2.5) by default. The series terms are
contrasts with the first component. jsdgam() warns when the
formula has no term that varies by component.
Each column of the loadings Z sums to zero, through
Stan's sum_to_zero_vector type.
A loadings_prior combines with that constraint.
The density is joint over a unit's components, which makes the unit
the grain of log_lik(), loo() and waic() (Vehtari et al.
2017). log_lik() gives each unit's log density on its first row
and NA on the others. loo() then counts each unit once.
loo_compare() needs every model it compares scored at that grain.
posterior_linpred() gives mu per row before the reference
subtraction. posterior_epred() gives the expected shares, which
sum to one within each unit.
species_effects(), variance_partition() and
forecast_uncertainty(scale = "link") report the predictor centred
across each unit's components, the centred log-ratio scale. A shift
shared by every component then drops out.
Warton, D. I., Blanchet, F. G., O'Hara, R. B., Ovaskainen, O., Taskinen, S., Walker, S. C. and Hui, F. K. C. (2015). So many variables: joint modeling in community ecology. Trends in Ecology and Evolution, 30(12):766-779. doi:10.1016/j.tree.2015.09.007
Other observation families:
beta_nb(),
com_binomial(),
diri(),
multi(),
mvgam_families,
mvn(),
mvt(),
nmix(),
occ(),
tweedie()
## Not run: # The one category observed at each of 150 sites simdat <- sim_jsdgam(family = categ(), n_species = 3L, n_sites = 150L, seed = 4L) fit <- jsdgam( formula = y ~ env * series, factor_formula = ~ -1, data = simdat$data_train, unit = time, species = series, family = categ(), n_lv = 1L, chains = 2L, silent = 2 ) # The probability of each category along the gradient conditional_effects(fit, effects = "env:series") # Next, pp_check(fit) compares observed and replicated categories ## End(Not run)## Not run: # The one category observed at each of 150 sites simdat <- sim_jsdgam(family = categ(), n_species = 3L, n_sites = 150L, seed = 4L) fit <- jsdgam( formula = y ~ env * series, factor_formula = ~ -1, data = simdat$data_train, unit = time, species = series, family = categ(), n_lv = 1L, chains = 2L, silent = 2 ) # The probability of each category along the gradient conditional_effects(fit, effects = "env:series") # Next, pp_check(fit) compares observed and replicated categories ## End(Not run)
newdata against the training data of an mvgam modelRuns the structural checks that predict.mvgam() and
forecast.mvgam() apply to a newdata frame. A misaligned frame is
refused before an expensive prediction. The trend constructor in
trend_formula names the time and series columns, time and
series by default. Each of them the training data holds must
also be in newdata. A hierarchical trend identifies its series by
its gr and subgr columns. Those columns are then required. Series
levels absent from the training data are refused. The series column
of newdata is coerced to the training levels. The prediction
functions check the columns the formulas use.
check_newdata(newdata, data, trend_formula = NULL)check_newdata(newdata, data, trend_formula = NULL)
newdata |
A |
data |
The training |
trend_formula |
The trend formula passed to |
newdata with its series column coerced to the training
factor levels, returned invisibly, or NULL (invisibly) when
newdata is NULL. Checked against a fitted model, newdata
is returned with the columns that model predicts from.
predict.mvgam(), forecast.mvgam()
Other model fitting:
jsdgam(),
mvgam(),
mvgam_data(),
mvgam_multiple(),
pivot_detection_array(),
pivot_species_matrix(),
print.mvgam_formula(),
series_to_mvgam(),
stancode.mvgam_formula(),
update.mvgam()
train <- data.frame( species = factor(rep(c("a", "b"), each = 3L)), week = rep(1:3, times = 2L), y = rnorm(6L) ) test_weeks <- data.frame( species = factor(rep(c("a", "b"), each = 2L)), week = rep(4:5, times = 2L) ) check_newdata(test_weeks, train, ~ AR(time = week, series = species)) # A species the model never saw is refused. test_weeks$species <- factor(rep(c("a", "c"), each = 2L)) try(check_newdata(test_weeks, train, ~ AR(time = week, series = species)))train <- data.frame( species = factor(rep(c("a", "b"), each = 3L)), week = rep(1:3, times = 2L), y = rnorm(6L) ) test_weeks <- data.frame( species = factor(rep(c("a", "b"), each = 2L)), week = rep(4:5, times = 2L) ) check_newdata(test_weeks, train, ~ AR(time = week, series = species)) # A species the model never saw is refused. test_weeks$species <- factor(rep(c("a", "c"), each = 2L)) try(check_newdata(test_weeks, train, ~ AR(time = week, series = species)))
M is adequateComputes the per-observation Poisson rate
lambda = mu^(2 - theta) / ((2 - theta) * phi) at the
posterior mean of (mu, mphi, mtheta) and compares it
against the truncation count M saved in the fit's
standata. Warns if max(lambda) exceeds 0.7 * M, the
rough point at which the log_sum_exp over m = 1..M
starts to omit appreciable Poisson tail mass and bias the
log-density downward.
check_tweedie_truncation(object, resp = NULL)check_tweedie_truncation(object, resp = NULL)
object |
An |
resp |
Optional name of one response to check. Without it,
every |
The rate is taken for every response whose family is tweedie(). A
multivariate model can name it for one response among several. All of
them share the one M. mphi and mtheta are taken per observation.
This covers a parameter given a formula of its own as well as a scalar
one.
Invisible NULL. Emits a message on the adequacy of M. It
also emits a warning if M looks tight.
tweedie() for the family and its argument M.
## Not run: set.seed(3) simdat <- sim_mvgam(family = tweedie(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = tweedie(), chains = 2, silent = 2) # The largest Poisson rate the fit implies, against the default M = 30 check_tweedie_truncation(mod) # A warning here would call for a refit with a longer series, such # as family = tweedie(M = 60) ## End(Not run)## Not run: set.seed(3) simdat <- sim_mvgam(family = tweedie(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = tweedie(), chains = 2, silent = 2) # The largest Poisson rate the fit implies, against the default M = 30 check_tweedie_truncation(mod) # A warning here would call for a refit with a longer series, such # as family = tweedie(M = 60) ## End(Not run)
A two-parameter generalisation of the binomial that exponentiates
the binomial coefficient by a real-valued dispersion parameter
nu. nu = 1 is the standard binomial. nu > 1 under-disperses,
concentrating mass near the mode. 0 < nu < 1 over-disperses.
nu < 0 super-disperses, producing bimodal "all-or-nothing" mass at
the boundaries. Useful when a binomial fit shows systematic lack-of-fit
in either tail and the response is bounded by a known trial count.
com_binomial(link = "logit")com_binomial(link = "logit")
link |
Link function for the success probability |
A brms::custom_family() object suitable for the
family argument of mvgam() / jsdgam(). The object has an
attr(., "mvgam_stanvars") attribute, which holds the Stan
function-block stanvar. mvgam's setup attaches it automatically.
mulogit-scale success probability (link = logit).
Distributional regression on mu is the standard formula
side: bf(y | trials(trials) ~ x).
nureal-valued dispersion exponent (link = identity,
lb = -5). nu = 1 is binomial. Distributional regression
is supported via bf(y | trials(trials) ~ x, nu ~ z).
The support is 0:T, a finite range. The normalising sum
runs over T + 1 positive terms at every real nu, which
keeps the density proper with no lower bound on it. lb = -5
is a numerical floor. The log factorial term grows with
-nu. Gradients past that point are hard for the sampler. A
scalar nu carries the floor as
real<lower=-5> with a prior truncated to match. A modelled
nu is a linear predictor and carries no such declaration,
leaving nu[n] free. Hold the predictor inside the range the
data resolve, roughly (-1, 4).
nu ~ normal(1, 1) – centred at nu = 1, where the
trials are independent and the distribution is binomial.
The scale spans the range the data can resolve. The response
saturates below nu = -1 and above nu = 4. Values outside
roughly (-1, 4) are barely distinguishable. Strongly
under-dispersed data have nu near 3. Override
with prior(normal(1, 2), class = "nu") to explore wider,
or a tighter scale to pull harder toward the binomial.
Two corners of (p, nu) parameter space stress HMC and should
be monitored:
nu >> 1: the PMF concentrates on a single mode and the
log-normaliser gradient saturates; max-treedepth saturation
becomes possible above roughly nu = 5.
nu << 0 with p near 0.5: mass concentrates at both
boundaries and the likelihood is invariant under
p -> 1 - p, producing bimodal posteriors. Asymmetric
covariates break the symmetry.
Inspect mcmc_plot(fit, variable = "nu", type = "trace") and
the R-hat + ESS on both nu and the intercept; if either
degrades, tighten the prior on nu or shift the design to
bias p away from 0.5.
Nicholas J Clark, Julijus Bogomolovas
Shmueli, G., Minka, T. P., Kadane, J. B., Borle, S. and Boatwright, P. (2005). A useful distribution for fitting discrete data: revival of the Conway-Maxwell-Poisson distribution. Journal of the Royal Statistical Society Series C, 54:127-142.
Conway, R. W. and Maxwell, W. L. (1962). A queuing model with state dependent service rates. Journal of Industrial Engineering, 12:132-136.
Other observation families:
beta_nb(),
categ(),
diri(),
multi(),
mvgam_families,
mvn(),
mvt(),
nmix(),
occ(),
tweedie()
## Not run: # Counts out of 10 trials, simulated with `nu = 3`. At `nu = 1` # the family is the binomial. Values above 1 give counts with # less spread than a binomial. set.seed(1) sim <- sim_mvgam( family = com_binomial(), n_series = 1L, n_timepoints = 160L, trend_model = "None", family_pars = list(nu = 3, trials = 10L) ) # The denominator enters through brms's `trials()` term fit <- mvgam( bf(y | trials(trials) ~ s(x)), data = sim$data_train, family = com_binomial(), chains = 2, silent = 2 ) # The posterior for `nu` lies above the binomial's value of 1 summary(fit) mcmc_plot(fit, variable = "nu", type = "areas") pp_check(fit, type = "bars", ndraws = 50) ## End(Not run)## Not run: # Counts out of 10 trials, simulated with `nu = 3`. At `nu = 1` # the family is the binomial. Values above 1 give counts with # less spread than a binomial. set.seed(1) sim <- sim_mvgam( family = com_binomial(), n_series = 1L, n_timepoints = 160L, trend_model = "None", family_pars = list(nu = 3, trials = 10L) ) # The denominator enters through brms's `trials()` term fit <- mvgam( bf(y | trials(trials) ~ s(x)), data = sim$data_train, family = com_binomial(), chains = 2, silent = 2 ) # The posterior for `nu` lies above the binomial's value of 1 summary(fit) mcmc_plot(fit, variable = "nu", type = "areas") pp_check(fit, type = "bars", ndraws = 50) ## End(Not run)
Computes quantities of a whole community, draw by draw, from a model
of many series. A community is every series at one site and time.
Each gets its expected number of species, its diversity and its
community-weighted mean traits. Each species gets its probability of
presence. Each pair of species gets how often it occurs together
beyond what the covariates predict. Pass newdata as a covariate
gradient, such as one from datagrid(), to see how the community
changes along it.
community(object, ...) ## S3 method for class 'mvgam' community( object, newdata = NULL, ..., threshold = NULL, traits = NULL, latent = c("marginal", "conditional", "forecast", "zero"), n_nodes = 100L, ndraws = NULL, draw_ids = NULL, resp = NULL, prob_threshold = 0.95 ) ## S3 method for class 'mvgam_community' summary(object, probs = c(0.025, 0.975), ...) ## S3 method for class 'mvgam_community' as_draws_rvars(x, ...) ## S3 method for class 'mvgam_community' as_draws_df(x, ...) ## S3 method for class 'mvgam_community' print(x, digits = 2L, ...) ## S3 method for class 'mvgam_community' plot( x, type = c("richness", "diversity", "cooccurrence"), along = NULL, supported_only = FALSE, ... )community(object, ...) ## S3 method for class 'mvgam' community( object, newdata = NULL, ..., threshold = NULL, traits = NULL, latent = c("marginal", "conditional", "forecast", "zero"), n_nodes = 100L, ndraws = NULL, draw_ids = NULL, resp = NULL, prob_threshold = 0.95 ) ## S3 method for class 'mvgam_community' summary(object, probs = c(0.025, 0.975), ...) ## S3 method for class 'mvgam_community' as_draws_rvars(x, ...) ## S3 method for class 'mvgam_community' as_draws_df(x, ...) ## S3 method for class 'mvgam_community' print(x, digits = 2L, ...) ## S3 method for class 'mvgam_community' plot( x, type = c("richness", "diversity", "cooccurrence"), along = NULL, supported_only = FALSE, ... )
object |
A fitted |
... |
Unused. Anything passed here is refused. |
newdata |
Data frame with one row per community, holding its
covariates. Each row is crossed with every fitted series, which
replaces any series column it holds. |
threshold |
A species counts as present when its response
exceeds |
traits |
Species traits for community-weighted means: a data
frame with one row per species, matched as |
latent |
How the latent state enters. |
n_nodes |
Number of latent states each draw averages over under
|
ndraws, draw_ids
|
The posterior draws to use, as
|
resp |
The response to report, needed on a model with several. |
prob_threshold |
The posterior probability of its sign a pair's
excess co-occurrence needs to count as supported, at least 0.5 and
below 1. Defaults to 0.95. It sets the |
probs |
Interval probabilities of the tables. Defaults to
|
x |
An |
digits |
Integer number of significant digits. Defaults to 2. |
type |
|
along |
The column of the communities to draw along. |
supported_only |
Logical, for |
Richness. Each draw sums the species' probabilities of presence,
giving the expected number present. A count family's probability is
one less its probability of a zero, which covers zero inflation and
hurdles. Under occ() it is the occupancy probability and under
nmix() the probability that the latent abundance exceeds
threshold. Richness counts the species the model holds.
Latent state. Species share their latent factors or trends, which
move them together. Because presence is a non-linear function of the
latent state, a typical site differs from an average one. Under
latent = "marginal" each draw averages presence over n_nodes
latent states drawn from the trend's stationary covariance across
series. The draws of the latent state are shared by every community,
which makes a difference between communities free of their noise. A
RW() or LLT() trend has no stationary covariance. Each draw then
averages over the latent states it fitted at the training times.
Under latent = "forecast" each draw propagates its last fitted state
n_nodes times with fresh innovations, as forecast_uncertainty()
does. Presence is averaged over these paths. The communities need
times after the training data. Communities at one time share the
paths. A pair's excess co-occurrence then comes from the uncertainty
in the forecast state, which grows with the horizon.
Diversity. A family with an abundance, such as a count or a
biomass, weights each species by its expected value. Under nmix()
the weight is the latent abundance. Hill numbers of order one and two
(the exponential of Shannon entropy and inverse Simpson) follow from
the relative weights. A binary or occupancy family has no abundance.
Its weight is the probability of presence, which gives the expected
trait of the species present. Hill numbers are then left out. Each
measure is averaged over the latent states, giving the expected value
at one site. Under a count family the weights confound abundance
with detection.
A factor trait gives one column per level, whose weighted mean is the share of that level.
Co-occurrence. Species sharing a latent state appear together more
or less often than their covariates alone predict. A pair's excess
co-occurrence is the probability that both are present less the
product of their probabilities, averaged over the communities. A
pair the latent state moves independently has none. Neither does any
pair under latent = "conditional" or "zero", which fix the state.
An object of class mvgam_community. print() gives each
community's richness. summary() takes probs and returns a list
of tibbles, each with its median and interval. richness and
diversity hold one row per community, presence one per
community and series and cooccurrence one per pair of species.
plot() draws richness or diversity along a column of newdata,
or the excess co-occurrence of each pair.
as_draws_rvars() returns the posterior draws as
posterior::rvar()s, ready for arithmetic between communities and
for posterior::summarise_draws(). Community i is row i of the
object's communities element.
richnessone per community
presence[community, species], NA where a community
lacks the species
diversity[community, measure], one measure per Hill
number and trait, when there are any
cooccurrence[species, species] excess co-occurrence
as_draws_df() returns the same draws as a data frame, one column
per element.
Nicholas J Clark
residual_cor() for the associations between species,
species_effects() for each species' response to the covariates,
variance_partition() for what moves each species
## Not run: # Detections of 6 species at 80 sites, 4 visits each. Occupancy # responds to the site covariate `env` and detection to the time of # day `tod_c`. Two latent factors drive the species associations. simdat <- sim_closure_unit_data( family = occ(), n_species = 6L, n_sites = 80L, n_visits = 4L, n_lv = 2L, seed = 1L ) # A joint occupancy model. Each species has its own occupancy # intercept and `env` slope, plus its own detection intercept. Two # latent factors take up the residual association. mod <- jsdgam( formula = bf(y ~ series * env, p ~ series + tod_c), factor_formula = ~ -1, data = simdat$data_train, family = occ(), n_lv = 2L, chains = 2, silent = 2 ) summary(mod) # The effect of `env` on the chance of a detection, occupancy times # detection conditional_effects(mod) # Each species' response to env, outlined where its sign is clear plot(species_effects(mod, variables = "env")) # The residual correlations among species the factors imply plot(residual_cor(mod)) # Site scores and species loadings on the two factors ordinate(mod, rotation = "varimax") # Expected richness along `env`. The second plot marks the pairs of # species found together more often than `env` predicts. gradient <- datagrid(model = mod, env = seq(-2, 2, length.out = 20)) cm <- community(mod, newdata = gradient) plot(cm) plot(cm, type = "cooccurrence") # The draws, for any contrast: richness at the end of the gradient # less that at its start rv <- as_draws_rvars(cm) rv$richness[20] - rv$richness[1] # Next, compare n_lv = 1 with update(mod, n_lv = 1L) and loo() ## End(Not run)## Not run: # Detections of 6 species at 80 sites, 4 visits each. Occupancy # responds to the site covariate `env` and detection to the time of # day `tod_c`. Two latent factors drive the species associations. simdat <- sim_closure_unit_data( family = occ(), n_species = 6L, n_sites = 80L, n_visits = 4L, n_lv = 2L, seed = 1L ) # A joint occupancy model. Each species has its own occupancy # intercept and `env` slope, plus its own detection intercept. Two # latent factors take up the residual association. mod <- jsdgam( formula = bf(y ~ series * env, p ~ series + tod_c), factor_formula = ~ -1, data = simdat$data_train, family = occ(), n_lv = 2L, chains = 2, silent = 2 ) summary(mod) # The effect of `env` on the chance of a detection, occupancy times # detection conditional_effects(mod) # Each species' response to env, outlined where its sign is clear plot(species_effects(mod, variables = "env")) # The residual correlations among species the factors imply plot(residual_cor(mod)) # Site scores and species loadings on the two factors ordinate(mod, rotation = "varimax") # Expected richness along `env`. The second plot marks the pairs of # species found together more often than `env` predicts. gradient <- datagrid(model = mod, env = seq(-2, 2, length.out = 20)) cm <- community(mod, newdata = gradient) plot(cm) plot(cm, type = "cooccurrence") # The draws, for any contrast: richness at the end of the gradient # less that at its start rv <- as_draws_rvars(cm) rv$richness[20] - rv$richness[1] # Next, compare n_lv = 1 with update(mod, n_lv = 1L) and loo() ## End(Not run)
Stacks the per-step ELPDs from several mvgam_lfo
objects into one long-format tibble, with one row per model
and evaluation time.
compare_elpds(..., model_names = NULL) ## S3 method for class 'mvgam_compare_elpds' plot(x, relative = NULL, cumulative = FALSE, ...)compare_elpds(..., model_names = NULL) ## S3 method for class 'mvgam_compare_elpds' plot(x, relative = NULL, cumulative = FALSE, ...)
... |
Two or more |
model_names |
Optional character vector of model names, one per forecast. It replaces the names taken from the call. |
x |
An |
relative |
Optional name of a model in |
cumulative |
Logical. |
A tibble with columns:
model – factor with one level per supplied LFO run.
eval_time – the rolling-origin evaluation timepoint.
elpd – per-step expected log predictive density.
pareto_k – the Pareto-k diagnostic at that step.
refit_here – logical, TRUE when the step triggered
a fresh refit (Pareto-k above threshold or initial fit).
plot() draws each model's ELPD by origin. Hollow points mark the
origins where a Pareto k above the threshold forced a refit.
Nicholas J Clark
lfo_cv(), loo_compare.mvgam_lfo(),
loo_model_weights.mvgam_lfo(), compare_scores()
Other model comparison:
bridge_sampler.mvgam(),
kfold.mvgam(),
lfo_cv.mvgam(),
log_lik.mvgam(),
loo.mvgam(),
loo_compare.mvgam_lfo(),
mvgam_loo_extras,
posterior_average.mvgam(),
waic.mvgam()
## Not run: set.seed(1) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) # Two models of one count series: a smooth of x with and without # an AR(1) trend. The trend model samples with smaller steps # (adapt_delta = 0.95). That avoids divergent transitions when # lfo_cv() refits it to shorter stretches of the series mod_gam <- mvgam(y ~ s(x, k = 5), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) mod_ar <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2, control = list(adapt_delta = 0.95)) ## End(Not run) ## Not run: # Each origin after t = 70 forecasts the next time step. The # pointwise log densities feed stacking weights lfo_gam <- lfo_cv(mod_gam, min_t = 70L, save_log_lik = TRUE) lfo_ar <- lfo_cv(mod_ar, min_t = 70L, save_log_lik = TRUE) # One row per model and origin elpds <- compare_elpds(lfo_gam, lfo_ar, model_names = c("GAM", "AR")) head(elpds) # The running sum of the AR model's ELPD minus the GAM's. Hollow # points mark the origins where the model was refitted plot(elpds, relative = "GAM", cumulative = TRUE) # Next, loo_compare() sums the ELPDs with a standard error ## End(Not run)## Not run: set.seed(1) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) # Two models of one count series: a smooth of x with and without # an AR(1) trend. The trend model samples with smaller steps # (adapt_delta = 0.95). That avoids divergent transitions when # lfo_cv() refits it to shorter stretches of the series mod_gam <- mvgam(y ~ s(x, k = 5), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) mod_ar <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2, control = list(adapt_delta = 0.95)) ## End(Not run) ## Not run: # Each origin after t = 70 forecasts the next time step. The # pointwise log densities feed stacking weights lfo_gam <- lfo_cv(mod_gam, min_t = 70L, save_log_lik = TRUE) lfo_ar <- lfo_cv(mod_ar, min_t = 70L, save_log_lik = TRUE) # One row per model and origin elpds <- compare_elpds(lfo_gam, lfo_ar, model_names = c("GAM", "AR")) head(elpds) # The running sum of the AR model's ELPD minus the GAM's. Hollow # points mark the origins where the model was refitted plot(elpds, relative = "GAM", cumulative = TRUE) # Next, loo_compare() sums the ELPDs with a standard error ## End(Not run)
Side-by-side comparison of the posterior-median species loadings
from two latent-factor mvgam / jsdgam fits on the same set of
species. Two fits need not order or orient their factors alike,
and a direct overlay of their loadings would mislead.
compare_loadings() applies the orthogonal Procrustes solution
(Schoenemann 1966) that rotates the posterior-median loadings of
fit_b to best match those of fit_a in the least-squares
sense, then either overlays both
onto a single biplot with displacement segments (default) or
splits them into two facets sharing axes.
Useful when teaching the effect of a structured loadings prior:
fit one model with loadings_prior = NULL and a second with
traits = or phylo =, then plot the comparison to show how
the trait or phylogeny similarity reshapes the latent positions.
Procrustes alignment is orthogonal: it rotates and reflects the
loadings with their scale unchanged. A factor the model has shrunk
towards zero has short loadings, close to the origin. The panel
shows which species cluster together and how that arrangement moves
between fits. active_factors() reports how many factors the data
support.
compare_loadings( fit_a, fit_b, labels = c("fit_a", "fit_b"), which_lvs = c(1L, 2L), align = TRUE, facet = FALSE, label_species = c("all", "shift", "none"), ... )compare_loadings( fit_a, fit_b, labels = c("fit_a", "fit_b"), which_lvs = c(1L, 2L), align = TRUE, facet = FALSE, label_species = c("all", "shift", "none"), ... )
fit_a, fit_b
|
Two fitted |
labels |
Optional length-2 character vector of fit labels
shown in the legend / facet strips. Defaults to
|
which_lvs |
Integer vector of length 2 indicating which
two latent factors to plot. Defaults to |
align |
Logical. When |
facet |
Logical. When |
label_species |
Character. Controls which species are
labelled. |
... |
Unused. Anything passed here is refused. |
The orthogonal Procrustes rotation is the closed-form solution
where and
are the posterior-median loading matrices
restricted to which_lvs. The aligned Z_b is Z_b %*% t(R).
Alignment is a sufficient but not unique solution to factor
rotation indeterminacy; alternative alignments (varimax on the
joint matrix, sign-flip only) are possible but typically less
interpretable for the prior-comparison use case here.
Both fits must report the same species in the same factor order; the function errors otherwise. To compare fits with different species sets, subset before fitting.
A ggplot object.
Nicholas J Clark
Schoenemann PH (1966). A generalized solution of the orthogonal Procrustes problem. Psychometrika 31, 1-10. doi:10.1007/BF02289451
Heaps SE and Jermyn IH (2024). Structured prior distributions for the covariance matrix in latent factor models. Statistics and Computing 34, 143. doi:10.1007/s11222-024-10454-0
ordinate(), residual_cor(), active_factors()
Other latent dynamics:
active_factors(),
fevd.mvgam(),
irf.mvgam(),
ordinate(),
posterior_transition_matrix(),
residual_cor(),
shared_variation(),
stability.mvgam()
## Not run: # Counts of 10 species at 60 sites, driven by two latent factors simdat <- sim_jsdgam(family = poisson(), n_species = 10L, n_sites = 60L, n_lv = 2L, seed = 3L) mod <- jsdgam(y ~ env * series, data = simdat$data_train, family = poisson(), n_lv = 2L, chains = 2, silent = 2) # A trait that tracks each species' true loading on the first factor set.seed(3) traits <- data.frame( size = simdat$truth$loadings[, 1] + rnorm(10, sd = 0.2), row.names = levels(simdat$data_train$series) ) mod_traits <- jsdgam(y ~ env * series, data = simdat$data_train, family = poisson(), n_lv = 2L, traits = traits, chains = 2, silent = 2) # Grey segments join each species' loadings under the two priors compare_loadings(mod, mod_traits, labels = c("Default prior", "Trait prior")) ## End(Not run)## Not run: # Counts of 10 species at 60 sites, driven by two latent factors simdat <- sim_jsdgam(family = poisson(), n_species = 10L, n_sites = 60L, n_lv = 2L, seed = 3L) mod <- jsdgam(y ~ env * series, data = simdat$data_train, family = poisson(), n_lv = 2L, chains = 2, silent = 2) # A trait that tracks each species' true loading on the first factor set.seed(3) traits <- data.frame( size = simdat$truth$loadings[, 1] + rnorm(10, sd = 0.2), row.names = levels(simdat$data_train$series) ) mod_traits <- jsdgam(y ~ env * series, data = simdat$data_train, family = poisson(), n_lv = 2L, traits = traits, chains = 2, silent = 2) # Grey segments join each species' loadings under the two priors compare_loadings(mod, mod_traits, labels = c("Default prior", "Trait prior")) ## End(Not run)
Scores the forecasts of several models of the same
held-out data with one rule, then stacks the results in one table
for comparison. Lower scores are better. The table has one row per
model, series and forecast horizon. A joint score ("energy",
"variogram" or "twenergy") scores all series together. Its
per-series rows hold NA. The rows with series == "all_series"
hold its value.
compare_scores(..., score = "crps", model_names = NULL, score_args = list()) ## S3 method for class 'mvgam_compare_scores' plot(x, relative = NULL, facet = TRUE, ...) ## S3 method for class 'mvgam_compare_scores' summary(object, ...) ## S3 method for class 'mvgam_compare_scores' print(x, digits = 2L, ...)compare_scores(..., score = "crps", model_names = NULL, score_args = list()) ## S3 method for class 'mvgam_compare_scores' plot(x, relative = NULL, facet = TRUE, ...) ## S3 method for class 'mvgam_compare_scores' summary(object, ...) ## S3 method for class 'mvgam_compare_scores' print(x, digits = 2L, ...)
... |
Two or more |
score |
Character name of the scoring rule. The section
'Available scores' of |
model_names |
Optional character vector of model names, one per forecast. It replaces the names taken from the call. |
score_args |
Optional named list of further arguments of
|
x |
An |
relative |
Optional name of a model in |
facet |
Logical. |
object |
An |
digits |
Integer number of significant digits. Defaults to 2. |
A tibble of class mvgam_compare_scores. Its print()
method ranks the models by their mean score. Its columns are:
model: a factor with one level per forecast.
series: a factor of series names, with an "all_series"
level for a joint score.
eval_horizon: the forecast horizon, 1 for the first
held-out time.
score: the value of the score.
in_interval: whether the observation fell in the central
interval, as score.mvgam_forecast() reports it.
summary() returns the scores wide, one column per model and one
row per series and horizon, or per horizon for a joint score.
plot() draws each model's score by horizon. A univariate score
takes one panel per series and a joint score one panel. An ensemble
plots as one more model.
Nicholas J Clark
score.mvgam_forecast(), compare_elpds(),
forecast.mvgam(), ensemble.mvgam_forecast()
Other forecasting:
ensemble.mvgam_forecast(),
forecast.mvgam(),
forecast_uncertainty(),
hindcast(),
lfo_cv.mvgam(),
score()
## Not run: set.seed(1) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) # Two models of one count series: a smooth of x with and without # an AR(1) trend. The trend model samples with smaller steps # (adapt_delta = 0.95). That avoids divergent transitions when # lfo_cv() refits it to shorter stretches of the series mod_gam <- mvgam(y ~ s(x, k = 5), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) mod_ar <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2, control = list(adapt_delta = 0.95)) ## End(Not run) ## Not run: fc_gam <- forecast(mod_gam, newdata = simdat$data_test) fc_ar <- forecast(mod_ar, newdata = simdat$data_test) # One row per model and horizon, scored by the discrete ranked # probability score (lower is better) scores <- compare_scores(fc_gam, fc_ar, score = "drps", model_names = c("GAM", "AR")) summary(scores) # The AR model's DRPS minus the GAM's. Negative values favour the # AR model plot(scores, relative = "GAM") # Next, ensemble() combines the two forecasts ## End(Not run)## Not run: set.seed(1) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) # Two models of one count series: a smooth of x with and without # an AR(1) trend. The trend model samples with smaller steps # (adapt_delta = 0.95). That avoids divergent transitions when # lfo_cv() refits it to shorter stretches of the series mod_gam <- mvgam(y ~ s(x, k = 5), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) mod_ar <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2, control = list(adapt_delta = 0.95)) ## End(Not run) ## Not run: fc_gam <- forecast(mod_gam, newdata = simdat$data_test) fc_ar <- forecast(mod_ar, newdata = simdat$data_test) # One row per model and horizon, scored by the discrete ranked # probability score (lower is better) scores <- compare_scores(fc_gam, fc_ar, score = "drps", model_names = c("GAM", "AR")) summary(scores) # The AR model's DRPS minus the GAM's. Negative values favour the # AR model plot(scores, relative = "GAM") # Next, ensemble() combines the two forecasts ## End(Not run)
Plots how the prediction changes with each predictor, holding the
other predictors at typical values. Predictors of the observation
and trend formulas both count, as do interactions of up to three
terms. Each effect gets one panel, drawn by
marginaleffects::plot_predictions().
as.data.frame() returns the numbers the panels plot, one row per
grid point of each effect. Use it to build a custom plot, overlay
several fits or compare with a known truth. The columns are:
resp, the response, for a multivariate fit alone.
effect, the predictor the panel varies.
estimate__, lower__ and upper__, the prediction and its
interval, named as in brms and conditional_smooths.mvgam().
The other grid columns that marginaleffects filled.
## S3 method for class 'mvgam' conditional_effects( x, effects = NULL, type = "expected", points = FALSE, rug = FALSE, process_error = FALSE, series = NULL, resp = NULL, dpar = NULL, ... ) ## S3 method for class 'mvgam_conditional_effects' plot(x, plot = TRUE, ask = FALSE, ...) ## S3 method for class 'mvgam_conditional_effects' print(x, ...) ## S3 method for class 'mvgam_conditional_effects' as.data.frame(x, row.names = NULL, optional = FALSE, ...)## S3 method for class 'mvgam' conditional_effects( x, effects = NULL, type = "expected", points = FALSE, rug = FALSE, process_error = FALSE, series = NULL, resp = NULL, dpar = NULL, ... ) ## S3 method for class 'mvgam_conditional_effects' plot(x, plot = TRUE, ask = FALSE, ...) ## S3 method for class 'mvgam_conditional_effects' print(x, ...) ## S3 method for class 'mvgam_conditional_effects' as.data.frame(x, row.names = NULL, optional = FALSE, ...)
x |
A fitted |
effects |
Optional character vector of effects to plot. If
|
type |
Scale of predictions. One of |
points |
Logical or numeric. If |
rug |
Logical. If |
process_error |
Logical. Passed to |
series |
Which series the panels show. |
resp |
Character specifying which response variable for multivariate models. NULL (default) returns predictions for all responses. |
dpar |
Character naming a distributional parameter with a
formula of its own, such as |
... |
For |
plot |
Logical. If |
ask |
Logical. If |
row.names, optional
|
Ignored. |
An object of class mvgam_conditional_effects: a named
list with one ggplot per effect, drawn by the plot and
print methods.
The plot() method returns, invisibly, a flat named list of
ggplot objects, as
brms::conditional_effects() plots return one. A multivariate
fit's panels are named <response>.<effect>, response by
response.
Nicholas J Clark
Arel-Bundock, V., Greifer, N. and Heiss, A. (2024). How to interpret statistical models using marginaleffects for R and Python. Journal of Statistical Software, 111(9):1-32. doi:10.18637/jss.v111.i09
marginaleffects::predictions() returns the plotted
values as a data frame. marginaleffects::avg_slopes() and
marginaleffects::avg_comparisons() summarise effects as numbers.
posterior_epred.mvgam() computes the expected values the panels
draw. pp_check.mvgam() checks the fit against the data. The
overview vignette interprets
effects in both formulas.
Other predictions:
conditional_smooths.mvgam(),
fitted.mvgam(),
hindcast(),
posterior_epred.mvgam(),
posterior_linpred.mvgam(),
posterior_predict.mvgam(),
posterior_smooths.mvgam(),
predict.mvgam(),
predictive_error.mvgam(),
predictive_interval.mvgam()
## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # The effect of x on the expected count, with the observations conditional_effects(mod, points = TRUE) # The same effect on the log link scale conditional_effects(mod, type = "link") # A covariate of the observation SD, drawn as the SD itself gaus <- sim_mvgam(family = gaussian(), n_series = 1L, n_timepoints = 120L, trend_model = AR())$data_train gaus$weather <- rnorm(nrow(gaus)) mod_sigma <- mvgam(bf(y ~ s(x, k = 5), sigma ~ weather), trend_formula = ~ AR(p = 1), data = gaus, family = gaussian(), chains = 2, silent = 2) conditional_effects(mod_sigma, effects = "weather", dpar = "sigma") # The average slope of the expected count with respect to x marginaleffects::avg_slopes(mod, variables = "x", type = "expected") # Next: marginaleffects::plot_predictions() draws custom effect # displays, such as one covariate conditional on another ## End(Not run)## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # The effect of x on the expected count, with the observations conditional_effects(mod, points = TRUE) # The same effect on the log link scale conditional_effects(mod, type = "link") # A covariate of the observation SD, drawn as the SD itself gaus <- sim_mvgam(family = gaussian(), n_series = 1L, n_timepoints = 120L, trend_model = AR())$data_train gaus$weather <- rnorm(nrow(gaus)) mod_sigma <- mvgam(bf(y ~ s(x, k = 5), sigma ~ weather), trend_formula = ~ AR(p = 1), data = gaus, family = gaussian(), chains = 2, silent = 2) conditional_effects(mod_sigma, effects = "weather", dpar = "sigma") # The average slope of the expected count with respect to x marginaleffects::avg_slopes(mod, variables = "x", type = "expected") # Next: marginaleffects::plot_predictions() draws custom effect # displays, such as one covariate conditional on another ## End(Not run)
Summarises the posterior of every smooth over a grid of its own
variables, in the shape brms::conditional_smooths() returns. Its
plot() method draws a smooth of one variable as a line and ribbon,
and a smooth of two as a heatmap.
## S3 method for class 'mvgam' conditional_smooths( x, smooths = NULL, int_conditions = NULL, prob = 0.95, spaghetti = FALSE, surface = TRUE, facets = 3L, resolution = 100L, too_far = 0, ndraws = NULL, draw_ids = NULL, resp = NULL, ... ) ## S3 method for class 'mvgam_conditional_smooths' plot(x, plot = TRUE, ask = FALSE, ...) ## S3 method for class 'mvgam_conditional_smooths' print(x, ...)## S3 method for class 'mvgam' conditional_smooths( x, smooths = NULL, int_conditions = NULL, prob = 0.95, spaghetti = FALSE, surface = TRUE, facets = 3L, resolution = 100L, too_far = 0, ndraws = NULL, draw_ids = NULL, resp = NULL, ... ) ## S3 method for class 'mvgam_conditional_smooths' plot(x, plot = TRUE, ask = FALSE, ...) ## S3 method for class 'mvgam_conditional_smooths' print(x, ...)
x |
An object of class |
smooths |
The terms to summarise, as |
int_conditions |
A named list setting the grid of a variable:
a vector of values, or a function of the variable's training
values, such as |
prob |
A number in |
spaghetti |
Logical. |
surface |
Logical. |
facets |
An integer of at least 2: the number of values taken
by the second variable and by a numeric |
resolution |
An integer of at least 2: the number of grid points along each variable. |
too_far |
A number in |
ndraws, draw_ids
|
The number of posterior draws, or their
indices. Give at most one. |
resp |
The response whose smooths to summarise, or |
... |
Unused. Anything passed here is refused. |
plot |
Logical. |
ask |
Logical. |
A list of class mvgam_conditional_smooths, one data frame
per smooth, named by predictor and term. Each holds its grid with
the columns estimate__, se__, lower__, upper__,
effect1__ and cond__. A smooth of two variables adds
effect2__.
The list of ggplot panels, one per smooth, invisibly.
Nicholas J Clark
posterior_smooths.mvgam() gives the draws of one smooth.
conditional_effects.mvgam() plots covariate effects on the
response.
Other predictions:
conditional_effects.mvgam(),
fitted.mvgam(),
hindcast(),
posterior_epred.mvgam(),
posterior_linpred.mvgam(),
posterior_predict.mvgam(),
posterior_smooths.mvgam(),
predict.mvgam(),
predictive_error.mvgam(),
predictive_interval.mvgam()
## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # The smooth with 30 of its draws cs <- conditional_smooths(mod, spaghetti = TRUE, ndraws = 30) plot(cs) head(cs[[1]]) # Next, plot(mod, type = "smooths") draws the same panels in one # figure ## End(Not run)## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # The smooth with 30 of its draws cs <- conditional_smooths(mod, spaghetti = TRUE, ndraws = 30) plot(cs) head(cs[[1]]) # Next, plot(mod, type = "smooths") draws the same panels in one # figure ## End(Not run)
The NUTS settings the model was sampled with, such as
adapt_delta, max_treedepth and stepsize. A fit that reported
divergent transitions can be refitted with a higher adapt_delta,
such as update(fit, control = list(adapt_delta = 0.95)). The
sampler then takes smaller steps.
## S3 method for class 'mvgam' control_params(x, ...)## S3 method for class 'mvgam' control_params(x, ...)
x |
A fitted |
... |
Unused. Anything passed here is refused. |
A named list, as brms::control_params() returns for a
brmsfit. A fit with no NUTS settings, such as a variational
fit, gives an empty list.
mvgam_diagnostics for the divergence counts,
summary.mvgam() for convergence checks.
## Not run: set.seed(1) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 60L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, seed = 2, silent = 2) control_params(mod)$adapt_delta ## End(Not run)## Not run: set.seed(1) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 60L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, seed = 2, silent = 2) control_params(mod)$adapt_delta ## End(Not run)
A state-space dataset for three coral reefs surveyed at
irregular monthly intervals (gap distribution
Uniform(1, 6) months, mean approximately 3.5). Each survey
inspects between 20 and 40 colonies and counts those that have
bleached. The latent state is a continuous-time AR(1) (CAR(1))
trend per reef with phi = 0.9 and sigma = 0.3 on the logit
scale. The observation equation adds an observed sea-surface
temperature (SST) driver through a smooth nonlinear effect.
coral_surveyscoral_surveys
A data.frame with 150 rows and the following fields:
factor identifying the reef (flynn,
myrmidon, pixie); duplicated as reef.
integer month index (irregularly spaced within each reef).
integer count of bleached colonies; duplicated as
bleaching.
factor, alias of series.
numeric observed sea-surface temperature in degrees Celsius.
integer count of bleached colonies, alias of
y.
integer number of colonies inspected, the binomial trials.
A naive AR(1) treats every consecutive survey as one step. It
gives a one-month gap and a six-month gap the same persistence.
trend_formula = ~ CAR() with the supplied time column decays
the state by the length of each gap. Its ar1_trend measures the
persistence over the median gap between surveys, three months
here. The simulated value is 0.9^3 = 0.73.
True generative components, on the logit scale:
An intercept of -0.85, which puts a typical survey near 30% bleached. Each reef adds its own centred intercept.
Latent CAR(1) state per reef with phi = 0.9 and
sigma = 0.3, propagated through
trend[t] = phi^dt * trend[t-1] + N(0, sigma * sqrt((1 - phi^(2*dt)) / (1 - phi^2))).
Shared smooth nonlinear effect of SST, evaluated through a thin-plate basis.
Binomial observations: bleaching ~ Binomial(colonies, p).
CAR() for the trend, AR() for evenly spaced surveys,
mvgam_data() to check the data.
data(coral_surveys) mvgam_data(coral_surveys, formula = y | trials(colonies) ~ s(sst), family = binomial()) ## Not run: # A model with the structure the data were simulated from mod <- mvgam( formula = y | trials(colonies) ~ series + s(sst, k = 8), trend_formula = ~ CAR(), data = coral_surveys, family = binomial(), chains = 2, silent = 2 ) summary(mod) ## End(Not run)data(coral_surveys) mvgam_data(coral_surveys, formula = y | trials(colonies) ~ s(sst), family = binomial()) ## Not run: # A model with the structure the data were simulated from mod <- mvgam( formula = y | trials(colonies) ~ series + s(sst, k = 8), trend_formula = ~ CAR(), data = coral_surveys, family = binomial(), chains = 2, silent = 2 ) summary(mod) ## End(Not run)
For proportions measured together on each unit that sum to one, such
as the cover shares of several species at a site. The data hold one
row per component at each unit, whose responses sum to one within
the unit. Each unit's vector of K shares is Dirichlet with
concentrations softmax(mu) * phi. mu holds the components'
linear predictors. phi sets how tightly the shares gather around
softmax(mu) (Aitchison 1982).
diri()diri()
jsdgam() fits the family, taking the unit and component columns
and the number of latent factors n_lv. The factors give the
components correlated departures from their expected shares
(Warton et al. 2015).
A family object to pass to jsdgam() or mvgam().
The softmax is unchanged when the same constant is added to every component. The data then identify neither a shift of the linear predictors that every component shares nor a shift of the loadings that every component shares. mvgam removes both:
The first component is the reference. Its linear predictor
is subtracted from every component's before the softmax, as in
brms's dirichlet() family. A term that acts on every
component alike, such as Intercept or env in
y ~ env * series, then cancels. Its posterior is its prior,
student_t(3, 0, 2.5) by default. The series terms are
contrasts with the first component. jsdgam() warns when the
formula has no term that varies by component.
Each column of the loadings Z sums to zero, through
Stan's sum_to_zero_vector type.
A loadings_prior combines with that constraint.
phi
bf(y ~ env * series, phi ~ env) models the concentration. A unit's
density takes one phi. Its covariates must take one value per
unit. mvgam refuses a covariate that varies within a unit.
The coefficients of phi take a flat prior by default.
prior(student_t(3, 0, 2.5), class = b, dpar = phi) regularises
them.
The density is joint over a unit's components, which makes the unit
the grain of log_lik(), loo() and waic() (Vehtari et al.
2017). log_lik() gives each unit's log density on its first row
and NA on the others. loo() then counts each unit once.
loo_compare() needs every model it compares scored at that grain.
posterior_linpred() gives mu per row before the reference
subtraction. posterior_epred() gives the expected shares, which
sum to one within each unit.
species_effects(), variance_partition() and
forecast_uncertainty(scale = "link") report the predictor centred
across each unit's components, the centred log-ratio scale. A shift
shared by every component then drops out.
Aitchison, J. (1982). The statistical analysis of compositional data. Journal of the Royal Statistical Society Series B, 44(2):139-177.
Vehtari, A., Gelman, A. and Gabry, J. (2017). Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC. Statistics and Computing, 27:1413-1432. doi:10.1007/s11222-016-9696-4
Warton, D. I., Blanchet, F. G., O'Hara, R. B., Ovaskainen, O., Taskinen, S., Walker, S. C. and Hui, F. K. C. (2015). So many variables: joint modeling in community ecology. Trends in Ecology and Evolution, 30(12):766-779. doi:10.1016/j.tree.2015.09.007
Heaps, S. E. and Jermyn, I. H. (2024). Structured prior distributions for the covariance matrix in latent factor models. Statistics and Computing, 34:143. doi:10.1007/s11222-024-10454-0
Other observation families:
beta_nb(),
categ(),
com_binomial(),
multi(),
mvgam_families,
mvn(),
mvt(),
nmix(),
occ(),
tweedie()
## Not run: # Shares of three categories at 60 sites along an environmental # gradient simdat <- sim_jsdgam(family = diri(), n_species = 3L, n_sites = 60L, seed = 2L) head(simdat$data_train) # `env * series` gives each category its own slope fit <- jsdgam( formula = y ~ env * series, factor_formula = ~ -1, data = simdat$data_train, unit = time, species = series, family = diri(), n_lv = 2L, chains = 2L, silent = 2 ) # The species terms are contrasts with the first species. `Intercept` # and `env` act on every species alike. The softmax cancels them. Their # posteriors repeat the prior. summary(fit) # Each species' response to env relative to the average species species_effects(fit, variables = "env") # The expected shares move along the gradient conditional_effects(fit, effects = "env:series") # Each site's expected shares sum to one pe <- posterior_epred(fit, ndraws = 50L) first_site <- which(simdat$data_train$time == 1L) rowSums(pe[1:5, first_site]) ## End(Not run)## Not run: # Shares of three categories at 60 sites along an environmental # gradient simdat <- sim_jsdgam(family = diri(), n_species = 3L, n_sites = 60L, seed = 2L) head(simdat$data_train) # `env * series` gives each category its own slope fit <- jsdgam( formula = y ~ env * series, factor_formula = ~ -1, data = simdat$data_train, unit = time, species = series, family = diri(), n_lv = 2L, chains = 2L, silent = 2 ) # The species terms are contrasts with the first species. `Intercept` # and `env` act on every species alike. The softmax cancels them. Their # posteriors repeat the prior. summary(fit) # Each species' response to env relative to the average species species_effects(fit, variables = "env") # The expected shares move along the gradient conditional_effects(fit, effects = "env:series") # Each site's expected shares sum to one pe <- posterior_epred(fit, ndraws = 50L) first_site <- which(simdat$data_train$time == 1L) rowSums(pe[1:5, first_site]) ## End(Not run)
Build a single mvgam_forecast from the hindcast and forecast
draws of two or more mvgam_forecast objects. Each input supplies
a share of the draws set by its weight. Weights are even by
default.
ensemble(object, ...) ## S3 method for class 'mvgam_forecast' ensemble(object, ..., weights = NULL, ndraws = 5000L, seed = NULL)ensemble(object, ...) ## S3 method for class 'mvgam_forecast' ensemble(object, ..., weights = NULL, ndraws = 5000L, seed = NULL)
object |
An |
... |
More |
weights |
Either |
ndraws |
Positive integer giving the total number of
ensemble draws to return per series. Defaults to |
seed |
Optional integer seed. The session's random state is restored when the call returns. |
Per-model weights are split into integer draw counts
that sum to ndraws by the largest-remainder rule, after
brms::round_largest_remainder(). Each model then gives one set
of sampled draws. Every series, in the hindcasts and in the
forecasts, takes that same set. The ensemble keeps the dependence
between series and the pairing of each hindcast with its forecast.
The returned object takes its series names, family, training data and test data from the first input. All inputs must share the series names, the hindcast lengths, the forecast horizons and, when present, the test observations.
A multivariate fit on a wide frame gives one forecast whose series are its responses. The ensemble is a forecast over those series. On a long frame the ensemble keeps one forecast per response. Every response takes the same draws.
An object of class mvgam_forecast containing the
ensembled hindcasts and forecasts. Suitable for
plot.mvgam_forecast() and score.mvgam_forecast().
Attribute weights records the per-model weights used.
Attribute ndraws_per_model records the integer draw
counts drawn from each input.
Nicholas J Clark
score.mvgam_forecast() scores the ensemble.
loo_model_weights.mvgam_lfo() computes weights from forecast
performance. pp_average.mvgam() averages predictions in place of
forecasts. The
forecast evaluation article
weights an ensemble by leave-future-out stacking weights.
Other forecasting:
compare_scores(),
forecast.mvgam(),
forecast_uncertainty(),
hindcast(),
lfo_cv.mvgam(),
score()
## Not run: set.seed(1) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) # Two models of one count series: a smooth of x with and without # an AR(1) trend. The trend model samples with smaller steps # (adapt_delta = 0.95). That avoids divergent transitions when # lfo_cv() refits it to shorter stretches of the series mod_gam <- mvgam(y ~ s(x, k = 5), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) mod_ar <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2, control = list(adapt_delta = 0.95)) ## End(Not run) ## Not run: fc_gam <- forecast(mod_gam, newdata = simdat$data_test) fc_ar <- forecast(mod_ar, newdata = simdat$data_test) # An ensemble that draws 30% of its draws from the GAM ens <- ensemble(fc_gam, fc_ar, weights = c(0.3, 0.7)) attr(ens, "ndraws_per_model") plot(ens) # The ensemble scored against its components scores <- compare_scores(fc_gam, fc_ar, ens, score = "drps", model_names = c("GAM", "AR", "Ensemble")) plot(scores, relative = "GAM") ## End(Not run)## Not run: set.seed(1) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) # Two models of one count series: a smooth of x with and without # an AR(1) trend. The trend model samples with smaller steps # (adapt_delta = 0.95). That avoids divergent transitions when # lfo_cv() refits it to shorter stretches of the series mod_gam <- mvgam(y ~ s(x, k = 5), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) mod_ar <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2, control = list(adapt_delta = 0.95)) ## End(Not run) ## Not run: fc_gam <- forecast(mod_gam, newdata = simdat$data_test) fc_ar <- forecast(mod_ar, newdata = simdat$data_test) # An ensemble that draws 30% of its draws from the GAM ens <- ensemble(fc_gam, fc_ar, weights = c(0.3, 0.7)) attr(ens, "ndraws_per_model") plot(ens) # The ensemble scored against its components scores <- compare_scores(fc_gam, fc_ar, ens, score = "drps", model_names = c("GAM", "AR", "Ensemble")) plot(scores, relative = "GAM") ## End(Not run)
Extract family from mvgam object
## S3 method for class 'mvgam' family(object, resp = NULL, ...)## S3 method for class 'mvgam' family(object, resp = NULL, ...)
object |
mvgam object |
resp |
Optional name of one response of a multivariate model. Without it, a model with several responses returns one family per response. |
... |
Unused. Anything passed here is refused. |
A family object, or a list of them named by response
Compute forecast error variance decompositions from
mvgam models with Vector Autoregressive dynamics. A
decomposition gives the share of each series' forecast uncertainty
at horizons up to h that comes from the innovations of each
series.
fevd(object, ...) ## S3 method for class 'mvgam' fevd( object, h = 10, ndraws = NULL, draw_ids = NULL, summary = TRUE, probs = c(0.025, 0.975), future = FALSE, ... )fevd(object, ...) ## S3 method for class 'mvgam' fevd( object, h = 10, ndraws = NULL, draw_ids = NULL, summary = TRUE, probs = c(0.025, 0.975), future = FALSE, ... )
object |
An object of class |
... |
Unused. Anything passed here is refused. |
h |
Positive integer. The number of forecast horizons to decompose. |
ndraws |
Positive integer specifying number of posterior draws to use. NULL (default) uses all available draws. |
draw_ids |
Optional integer vector selecting a subset of posterior
draw indices to use. NULL (default) uses all draws (subject to
|
summary |
Logical; return the posterior median and interval of each decomposition (the default), or the per-draw decompositions themselves. |
probs |
The lower and upper percentiles of the interval reported
with the median when |
future |
|
An object of mvgam_fevd-class, which describes
the quantities computed, with references.
Nicholas J Clark
Lutkepohl H (2005). New Introduction to Multiple Time Series Analysis. Springer, Berlin. doi:10.1007/978-3-540-27752-1
irf() and stability() summarise the same VAR dynamics.
forecast_uncertainty() splits a forecast of any model by source.
The VAR article runs fevd() on a
plankton community.
Other latent dynamics:
active_factors(),
compare_loadings(),
irf.mvgam(),
ordinate(),
posterior_transition_matrix(),
residual_cor(),
shared_variation(),
stability.mvgam()
## Not run: # Ten years of monthly counts of a prey species and its predator. # Predators suppress the prey a month later. Prey raise the # predators a month later. set.seed(2025) n_months <- 120 A <- rbind(prey = c(0.6, -0.5), predator = c(0.4, 0.5)) z <- matrix(0, n_months, 2) for (t in 2:n_months) { z[t, ] <- A %*% z[t - 1, ] + rnorm(2, sd = 0.35) } predator_prey <- data.frame( time = rep(seq_len(n_months), 2), series = factor(rep(c("prey", "predator"), each = n_months), levels = c("prey", "predator")), y = rpois(2 * n_months, exp(c(2.5 + z[, 1], 1.5 + z[, 2]))) ) var_mod <- mvgam(y ~ series, trend_formula = ~ VAR(), data = predator_prey, family = poisson(), chains = 2, silent = 2) ## End(Not run) ## Not run: # The share of each series' forecast-error variance due to each # shock, over an eight-step horizon fevd_obj <- fevd(var_mod, h = 8L) plot(fevd_obj) # Next: irf() traces each shock through the system over time ## End(Not run)## Not run: # Ten years of monthly counts of a prey species and its predator. # Predators suppress the prey a month later. Prey raise the # predators a month later. set.seed(2025) n_months <- 120 A <- rbind(prey = c(0.6, -0.5), predator = c(0.4, 0.5)) z <- matrix(0, n_months, 2) for (t in 2:n_months) { z[t, ] <- A %*% z[t - 1, ] + rnorm(2, sd = 0.35) } predator_prey <- data.frame( time = rep(seq_len(n_months), 2), series = factor(rep(c("prey", "predator"), each = n_months), levels = c("prey", "predator")), y = rpois(2 * n_months, exp(c(2.5 + z[, 1], 1.5 + z[, 2]))) ) var_mod <- mvgam(y ~ series, trend_formula = ~ VAR(), data = predator_prey, family = poisson(), chains = 2, silent = 2) ## End(Not run) ## Not run: # The share of each series' forecast-error variance due to each # shock, over an eight-step horizon fevd_obj <- fevd(var_mod, h = 8L) plot(fevd_obj) # Next: irf() traces each shock through the system over time ## End(Not run)
Expected values E[Y | X] of an mvgam model, or its linear
predictor with scale = "linear", at the training observations by
default. The interface follows
fitted.brmsfit().
## S3 method for class 'mvgam' fitted( object, newdata = NULL, re_formula = NULL, scale = c("response", "linear"), components = c("response", "latent_state", "detection"), unit_level = NULL, resp = NULL, dpar = NULL, ndraws = NULL, draw_ids = NULL, summary = TRUE, robust = FALSE, probs = c(0.025, 0.975), process_error = FALSE, incl_autocor = is.null(newdata), allow_new_levels = FALSE, sample_new_levels = "uncertainty", ... )## S3 method for class 'mvgam' fitted( object, newdata = NULL, re_formula = NULL, scale = c("response", "linear"), components = c("response", "latent_state", "detection"), unit_level = NULL, resp = NULL, dpar = NULL, ndraws = NULL, draw_ids = NULL, summary = TRUE, robust = FALSE, probs = c(0.025, 0.975), process_error = FALSE, incl_autocor = is.null(newdata), allow_new_levels = FALSE, sample_new_levels = "uncertainty", ... )
object |
An object of class |
newdata |
Optional data frame with covariates for prediction. If NULL, uses original training data stored in the model object. |
re_formula |
Group-level terms to include: |
scale |
Character; one of |
components |
Character; one of
The argument matches |
unit_level |
Logical or |
resp |
Character specifying which response variable for multivariate models. NULL (default) returns predictions for all responses. |
dpar |
Character naming a distributional parameter, such as
|
ndraws |
Positive integer specifying number of posterior draws to use. NULL (default) uses all available draws. |
draw_ids |
Optional integer vector selecting a subset of posterior
draw indices to use. NULL (default) uses all draws (subject to
|
summary |
Logical. If |
robust |
Logical. If |
probs |
Numeric vector of probabilities for quantile computation.
Default is |
process_error |
Logical. Each call draws new innovations. Two calls on one fit give different results. Set a seed to reproduce a result. |
incl_autocor |
Logical; whether the fitted values include the
latent trend state the model inferred at each time. Defaults to
|
allow_new_levels |
Logical. |
sample_new_levels |
How a new level's coefficients are drawn:
|
... |
Unused. Anything passed here is refused. |
As in brms, fitted values leave out the observation noise.
posterior_predict.mvgam() adds it. Use predict.mvgam() for
predictive draws.
For the training data the fitted values include the trend state the
model inferred at each time. hindcast.mvgam() returns the same
state. With newdata, or under incl_autocor = FALSE, the fitted
values describe the covariate part of the model. process_error then
sets the trend's part. FALSE keeps the trend's covariate effects.
TRUE also samples a state per draw from the trend's dynamics.
The brms arguments nlpar and sort are refused. Rows come back in
the order of the frame.
With summary = FALSE, an [ndraws, nobs] matrix of
draws. With summary = TRUE, a matrix with one row per
observation and the columns:
Estimate: the posterior mean, or the median under
robust = TRUE.
Est.Error: the posterior SD, or the MAD under
robust = TRUE.
Q*: one quantile column per value of probs.
A multivariate model with resp = NULL gives a named list of
these, one per response.
residuals.mvgam() compares the fitted values with the
data. hindcast.mvgam() returns the fitted latent states.
forecast.mvgam() predicts future times.
Other predictions:
conditional_effects.mvgam(),
conditional_smooths.mvgam(),
hindcast(),
posterior_epred.mvgam(),
posterior_linpred.mvgam(),
posterior_predict.mvgam(),
posterior_smooths.mvgam(),
predict.mvgam(),
predictive_error.mvgam(),
predictive_interval.mvgam()
## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # Expected counts at the training observations: the posterior mean, # error and 95% interval of each head(fitted(mod)) # The covariate effects alone, without the inferred trend state head(fitted(mod, incl_autocor = FALSE)) # One row per posterior draw and one column per observation dim(fitted(mod, summary = FALSE)) # Next: residuals() and pp_check() compare the fit with the data ## End(Not run)## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # Expected counts at the training observations: the posterior mean, # error and 95% interval of each head(fitted(mod)) # The covariate effects alone, without the inferred trend state head(fitted(mod, incl_autocor = FALSE)) # One row per posterior draw and one column per observation dim(fitted(mod, summary = FALSE)) # Next: residuals() and pp_check() compare the fit with the data ## End(Not run)
Shows where a forecast's uncertainty comes from and how each source grows with the horizon. The variance of the forecast at each horizon splits among the model's terms, its random effects, the latent dynamics, process error and, on the response scale, observation noise.
forecast_uncertainty(object, ...) ## S3 method for class 'mvgam' forecast_uncertainty( object, newdata = NULL, ..., scale = c("link", "expected", "response"), n_replicates = 20L, n_boot = 200L, ndraws = NULL, draw_ids = NULL, re_formula = NULL, allow_new_levels = FALSE, sample_new_levels = "uncertainty", resp = NULL ) ## S3 method for class 'mvgam_forecast_uncertainty' summary(object, probs = c(0.025, 0.975), ...) ## S3 method for class 'mvgam_forecast_uncertainty' print(x, digits = 2L, ...) ## S3 method for class 'mvgam_forecast_uncertainty' plot( x, type = c("variance", "share"), by = c("kind", "source"), series = NULL, ... ) ## S3 method for class 'mvgam_forecast_scenarios' summary(object, probs = c(0.025, 0.975), ...) ## S3 method for class 'mvgam_forecast_scenarios' print(x, digits = 2L, ...) ## S3 method for class 'mvgam_forecast_scenarios' plot(x, series = NULL, ...)forecast_uncertainty(object, ...) ## S3 method for class 'mvgam' forecast_uncertainty( object, newdata = NULL, ..., scale = c("link", "expected", "response"), n_replicates = 20L, n_boot = 200L, ndraws = NULL, draw_ids = NULL, re_formula = NULL, allow_new_levels = FALSE, sample_new_levels = "uncertainty", resp = NULL ) ## S3 method for class 'mvgam_forecast_uncertainty' summary(object, probs = c(0.025, 0.975), ...) ## S3 method for class 'mvgam_forecast_uncertainty' print(x, digits = 2L, ...) ## S3 method for class 'mvgam_forecast_uncertainty' plot( x, type = c("variance", "share"), by = c("kind", "source"), series = NULL, ... ) ## S3 method for class 'mvgam_forecast_scenarios' summary(object, probs = c(0.025, 0.975), ...) ## S3 method for class 'mvgam_forecast_scenarios' print(x, digits = 2L, ...) ## S3 method for class 'mvgam_forecast_scenarios' plot(x, series = NULL, ...)
object |
A fitted |
... |
Unused. Anything passed here is refused. |
newdata |
Data frame of future times, as |
scale |
|
n_replicates |
Number of times each draw is propagated, at least two. More replicates steady the process error. |
n_boot |
Number of bootstrap resamples of the draws, which give each share its interval. |
ndraws, draw_ids
|
The posterior draws to use, as
|
re_formula, allow_new_levels, sample_new_levels
|
How group-level
terms enter, as |
resp |
The response to report, needed on a model with several. |
probs |
Interval probabilities of the table. Defaults to
|
x |
An |
digits |
Integer number of significant digits. Defaults to 2. |
type |
|
by |
|
series |
The series to plot, by name or position. |
With the parameters and the forecast at horizon
, the law of total variance gives
Each draw is propagated n_replicates times with fresh innovations.
The variance across a draw's replicates, averaged over the draws, is
the process error. The variance of the replicates' means is the
parameter uncertainty, less its known excess of the process error over
n_replicates. This holds exactly on every scale. Monte Carlo error
can leave a small estimate negative. No estimate is clipped.
Sources. Parameter uncertainty splits by source, each of one kind:
coefficientseach population-level term, smooth or gp().
This uncertainty falls with more data.
random effectseach group-level term
latent dynamicsthe latent state's mean path, holding the uncertain last state and trend parameters
process errorwhat the trend's innovations add. It persists however much data arrives.
driverwhat an uncertain future covariate adds. A mi()
covariate missing from newdata follows its own trend into the
forecast. Its innovations are imputed covariates, split from
process error by their covariance with the forecast.
observationnoise around the expected value, under
scale = "response" alone
Terms of the trend formula are labelled (trend). A term that is zero
at every forecast row is left out.
Contributions. Parts of a model share a posterior: an intercept and
a covariate's effect can each be uncertain while their sum is not. A
source's own variance can then far exceed the forecast's. Its
contribution is its covariance with the whole forecast, which counts
what reaches the forecast. The contributions sum to the forecast's
variance. A source offsetting another takes a negative one. The
contribution is the source's Shapley value in the forecast's variance.
Terms that overlap, such as s(x) with t2(x, z), can take large
contributions of opposite sign. The sum over a kind stays stable, which
is why the overview and the default plot work by kind.
A diri(), multi() or categ() fit gives each species' share
through a softmax, which ignores a shift every species at a site
shares. Its link scale is centred across the species at each site,
the centred log-ratio scale.
On the link scale the contributions are exact. On the other scales a
term's values are the expected value less the expected value without
that term, as in variance_partition(), rescaled to sum to the
parameter uncertainty. The terms then interact, which makes their
split an approximation. The split between parameter uncertainty,
process error and observation stays exact. On a skewed scale a few
draws can drive a variance, which makes the link scale steadier.
Scenarios. A list of frames sharing their series and times gives each scenario its own split. It also gives the difference between each scenario and the first, draw by draw, with a posterior interval. Every scenario takes the same draws and the same innovations. On the link scale the state then cancels, leaving what the covariates change. Because a list of scenarios is no probability distribution, no variance is taken across it. To separate two covariates, vary one at a time.
The intervals resample the draws. They measure the Monte Carlo error
of a share, which falls with ndraws and n_replicates.
An object of class mvgam_forecast_uncertainty. print()
gives each series' overview. summary() takes probs and returns
a list of three tibbles:
overviewone row per series: the forecast's SD at its
first and last horizons, the dominant kind of source at the
last horizon, the share of resamples that agree (support) and
the horizon at which the dominant kind first changes_at
horizonsthe forecast's variance at each horizon
sourceseach source's variance, contribution and
share at each horizon, the share with its interval
plot() stacks the sources over the horizon. A negative
contribution is drawn as zero. The object's draws element holds,
per series, the [draws, horizons] matrix of the forecast's mean
given each draw.
A list of frames in newdata gives an object of class
mvgam_forecast_scenarios. print() gives each difference at the
last horizon. summary() returns a list of contrasts, one row per
horizon, with overview, one row per scenario and series. plot()
draws each difference over the horizon. Its scenarios element holds
each scenario's own mvgam_forecast_uncertainty object.
Nicholas J Clark
Dietze MC (2017). Prediction in ecology: a first-principles framework. Ecological Applications 27(7), 2048-2060.
forecast.mvgam() for coef_uncertainty and
trend_uncertainty, fevd() for the sources of a VAR's forecast
errors, variance_partition() for the fitted predictor. The
forecast evaluation article
runs forecast_uncertainty() on rodent captures.
Other forecasting:
compare_scores(),
ensemble.mvgam_forecast(),
forecast.mvgam(),
hindcast(),
lfo_cv.mvgam(),
score()
## Not run: set.seed(11) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR(), proportional_train = 0.75) mod <- mvgam( y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, newdata = simdat$data_test, family = poisson(), chains = 2, silent = 2 ) # The held-out data given to mvgam() set the forecast horizon fc <- forecast(mod) plot(fc) # The latent AR(1) trend alone, on the log scale plot(forecast(mod, type = "trend")) # The expected counts, without the Poisson sampling noise plot(forecast(mod, type = "expected")) # Next, score the forecast against the held-out counts head(score(fc, score = "crps")[[1]]) # The sources of the forecast's variance at each horizon plot(forecast_uncertainty(mod, ndraws = 200)) # How a future with higher `x` would change the forecast higher <- simdat$data_test higher$x <- higher$x + 1 plot(forecast_uncertainty( mod, newdata = list(observed = simdat$data_test, higher = higher), ndraws = 200 )) ## End(Not run)## Not run: set.seed(11) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR(), proportional_train = 0.75) mod <- mvgam( y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, newdata = simdat$data_test, family = poisson(), chains = 2, silent = 2 ) # The held-out data given to mvgam() set the forecast horizon fc <- forecast(mod) plot(fc) # The latent AR(1) trend alone, on the log scale plot(forecast(mod, type = "trend")) # The expected counts, without the Poisson sampling noise plot(forecast(mod, type = "expected")) # Next, score the forecast against the held-out counts head(score(fc, score = "crps")[[1]]) # The sources of the forecast's variance at each horizon plot(forecast_uncertainty(mod, ndraws = 200)) # How a future with higher `x` would change the forecast higher <- simdat$data_test higher$x <- higher$x + 1 plot(forecast_uncertainty( mod, newdata = list(observed = simdat$data_test, higher = higher), ndraws = 200 )) ## End(Not run)
Posterior forecasts at future time points, with posterior hindcasts at the training time points. Each draw propagates the fitted latent state through the trend's dynamics. The observation family then maps the trend to the response scale.
## S3 method for class 'mvgam' forecast( object, newdata = NULL, ..., type = c("response", "link", "expected", "trend", "latent_state"), component = NULL, ndraws = NULL, draw_ids = NULL, coef_uncertainty = TRUE, trend_uncertainty = TRUE, obs_uncertainty = TRUE, resp = NULL, re_formula = NULL, allow_new_levels = FALSE, sample_new_levels = "uncertainty" )## S3 method for class 'mvgam' forecast( object, newdata = NULL, ..., type = c("response", "link", "expected", "trend", "latent_state"), component = NULL, ndraws = NULL, draw_ids = NULL, coef_uncertainty = TRUE, trend_uncertainty = TRUE, obs_uncertainty = TRUE, resp = NULL, re_formula = NULL, allow_new_levels = FALSE, sample_new_levels = "uncertainty" )
object |
A fitted mvgam object. |
newdata |
Optional The trend decides which future times are allowed:
|
... |
Unused. Anything passed here is refused. |
type |
The scale of the draws:
|
component |
|
ndraws |
Positive integer specifying number of posterior draws to use. NULL (default) uses all available draws. |
draw_ids |
Optional integer vector selecting a subset of posterior
draw indices to use. NULL (default) uses all draws (subject to
|
coef_uncertainty |
Logical, |
trend_uncertainty |
Logical, |
obs_uncertainty |
Logical, |
resp |
Character specifying which response variable for multivariate models. NULL (default) returns predictions for all responses. |
re_formula, allow_new_levels, sample_new_levels
|
As in
|
An object of class mvgam_forecast-class.
Hindcasts and forecasts are returned as named lists of
[ndraws, n_times] matrices, one per series. A forecast of state
components names them in its component slot.
hindcast.mvgam() returns the fitted latent states.
posterior_predict.mvgam() and posterior_epred.mvgam() predict
from the covariate part of the model. forecast()
extrapolates the fitted latent state. score.mvgam_forecast()
scores a forecast against held-out data.
forecast_uncertainty() splits its variance by source. The
forecast evaluation article
scores, compares and combines the forecasts of three models of
rodent counts.
Other forecasting:
compare_scores(),
ensemble.mvgam_forecast(),
forecast_uncertainty(),
hindcast(),
lfo_cv.mvgam(),
score()
## Not run: set.seed(11) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR(), proportional_train = 0.75) mod <- mvgam( y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, newdata = simdat$data_test, family = poisson(), chains = 2, silent = 2 ) # The held-out data given to mvgam() set the forecast horizon fc <- forecast(mod) plot(fc) # The latent AR(1) trend alone, on the log scale plot(forecast(mod, type = "trend")) # The expected counts, without the Poisson sampling noise plot(forecast(mod, type = "expected")) # Next, score the forecast against the held-out counts head(score(fc, score = "crps")[[1]]) # The sources of the forecast's variance at each horizon plot(forecast_uncertainty(mod, ndraws = 200)) # How a future with higher `x` would change the forecast higher <- simdat$data_test higher$x <- higher$x + 1 plot(forecast_uncertainty( mod, newdata = list(observed = simdat$data_test, higher = higher), ndraws = 200 )) ## End(Not run)## Not run: set.seed(11) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR(), proportional_train = 0.75) mod <- mvgam( y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, newdata = simdat$data_test, family = poisson(), chains = 2, silent = 2 ) # The held-out data given to mvgam() set the forecast horizon fc <- forecast(mod) plot(fc) # The latent AR(1) trend alone, on the log scale plot(forecast(mod, type = "trend")) # The expected counts, without the Poisson sampling noise plot(forecast(mod, type = "expected")) # Next, score the forecast against the held-out counts head(score(fc, score = "crps")[[1]]) # The sources of the forecast's variance at each horizon plot(forecast_uncertainty(mod, ndraws = 200)) # How a future with higher `x` would change the forecast higher <- simdat$data_test higher$x <- higher$x + 1 plot(forecast_uncertainty( mod, newdata = list(observed = simdat$data_test, higher = higher), ndraws = 200 )) ## End(Not run)
Extract formula from mvgam object
## S3 method for class 'mvgam' formula(x, ...)## S3 method for class 'mvgam' formula(x, ...)
x |
mvgam object |
... |
Unused. Anything passed here is refused. |
Formula object
Methods:
get_prior.mvgam_formula() lists the priors of a model
before it is fitted.
get_prior.mvgam() returns the prior table of a model.
get_prior.default() takes a formula or brmsformula
with the arguments of get_prior.mvgam_formula().
default_prior() is the same generic under the newer brms name.
A prior states the plausible values of a parameter before the data
are seen. Each row of the table gives the prior of one parameter
class. A _trend suffix marks the classes of the latent trend. The
defaults are weakly informative. Change one when outside knowledge
narrows a parameter, or when the sampler struggles in a region the
data cannot inform. Pass the new rows, built with brms::prior(),
to the prior argument of mvgam().
get_prior(object, ...) default_prior(object, ...)get_prior(object, ...) default_prior(object, ...)
object |
An |
... |
Arguments of the method. |
A brmsprior data frame.
mvgam_formula(), brms::get_prior()
## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) # The default priors of a Poisson GAM with an AR(1) trend, before # any fitting get_prior( mvgam_formula(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1)), data = simdat$data_train, family = poisson() ) # Outside knowledge that the series is strongly persistent narrows # the AR(1) coefficient persistent <- prior(normal(0.7, 0.15), class = ar1_trend) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), prior = persistent, chains = 2, silent = 2) # The fitted model's prior table records the change get_prior(mod) ## End(Not run)## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) # The default priors of a Poisson GAM with an AR(1) trend, before # any fitting get_prior( mvgam_formula(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1)), data = simdat$data_train, family = poisson() ) # Outside knowledge that the series is strongly persistent narrows # the AR(1) coefficient persistent <- prior(normal(0.7, 0.15), class = ar1_trend) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), prior = persistent, chains = 2, silent = 2) # The fitted model's prior table records the change get_prior(mod) ## End(Not run)
Covers a formula, brmsformula or mvbrmsformula, which it
wraps in the mvgam_formula it describes with any
trend_formula in the call. The table then carries the defaults
mvgam gives its own families, with or without a trend.
## Default S3 method: get_prior(object, ...) ## Default S3 method: default_prior(object, ...)## Default S3 method: get_prior(object, ...) ## Default S3 method: default_prior(object, ...)
object |
Model specification object |
... |
Arguments of |
A brmsprior data frame
get_prior(), default_prior() and prior_summary() return the
one prior table a model was built with. Edit it and pass it to
update(fit, prior = ...) to refit under other priors without
recompiling.
## S3 method for class 'mvgam' get_prior(object, ...) ## S3 method for class 'mvgam' default_prior(object, ...)## S3 method for class 'mvgam' get_prior(object, ...) ## S3 method for class 'mvgam' default_prior(object, ...)
object |
An |
... |
Unused. Anything passed here is refused. |
A brmsprior data frame of the observation and trend
priors. A row the user set has source = "user". brms
sets the source of the others, mostly "default".
Other priors:
get_prior.mvgam_formula()
Lists the priors of the observation and trend parts of the model an
mvgam_formula() describes, with their defaults for the data given.
Without a trend_formula the table matches that of
brms::get_prior(). default_prior() is the same method under the
newer brms name.
## S3 method for class 'mvgam_formula' get_prior( object, data, family = gaussian(), loadings_prior = NULL, data2 = NULL, ... ) ## S3 method for class 'mvgam_formula' default_prior(object, ...)## S3 method for class 'mvgam_formula' get_prior( object, data, family = gaussian(), loadings_prior = NULL, data2 = NULL, ... ) ## S3 method for class 'mvgam_formula' default_prior(object, ...)
object |
An |
data |
A data frame holding every variable the formulas use. |
family |
A description of the response distribution and link
function, given as a family function, a call to one or its name.
Supports most brms families, including the ordinal families
( A family written inside a univariate |
loadings_prior |
Optional named list giving a structured prior
on the loadings of a factor model, such as species traits or a
phylogeny. Most models leave it |
data2 |
A named list of objects the model uses that are not
variables in |
... |
Further arguments of |
The observation priors are those brms::get_prior() gives,
with mvgam's defaults for the families it adds. The trend rows list
every parameter the trend constructor samples and the coefficients
of the trend formula.
Default trend priors. brms sets the scale of its default
intercept, standard deviation and residual priors to
max(2.5, mad(link(y))), from the spread of the response on
the link scale under the identity, log, inverse, square-root and
inverse-square links. That widens its base scale of 2.5 by the
factor .
mvgam widens the trend's scale priors by the same factor, taking the
widest over several responses and under any other
link:
sigma_trend and sigma_group_trend take
inv_gamma(3, 1.07 s), with median . It
has no mass at zero. The process noise then stays separate from
an observation noise that competes for the same variance.
The factor loadings Z take
student_t(3, 0, 0.5 s). The static factors of
ZMVN(), which jsdgam() builds, take
normal(0, s).
LLT() is the exception. Its shock scales
(sigma_trend among them) and its starting states also
scale with the number of time points. So do the growth priors of
a linear PW(). Their help pages give the forms.
A count model on the log link rarely spreads past 2.5. Its defaults keep their link-scale values. Coefficients without units keep fixed priors: autoregressive and damping coefficients, correlations and degrees of freedom. The table this returns holds the resolved values for the data given.
A shrinkage prior on a trend-side class is written without
autoscaling. horseshoe() and R2D2() scale their global
parameter by the family's residual standard deviation. The trend's
own scale is sigma_trend, one per latent series. A family's
residual scale has no meaning on the trend side. Those rows take
autoscale = FALSE. Writing autoscale = TRUE on a
trend-side class is refused.
A brmsprior data frame of the observation and trend
priors, usable with brms::set_prior() and
brms::prior(). A trend class carries the _trend
suffix.
Heaps, S. E. and Jermyn, I. H. (2024). Structured prior distributions for the covariance matrix in latent factor models. Statistics and Computing, 34, 143. doi:10.1007/s11222-024-10454-0
mvgam_formula(), brms::prior() and
brms::set_prior(). The
hierarchical VAR article
sets priors on the observation error and the trend correlations.
Other priors:
get_prior.mvgam()
## Not run: set.seed(1) dat <- sim_mvgam(family = poisson(), n_series = 2L, n_timepoints = 120L, trend_model = AR())$data_train # Every prior the model takes, before any fitting. Trend classes # carry a `_trend` suffix: `b` belongs to the observation formula # and `b_trend` would belong to the trend formula. mf <- mvgam_formula(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1)) get_prior(mf, data = dat, family = poisson()) # Replace three defaults. Each `prior()` call gives one row. my_priors <- c( prior(std_normal(), class = b), prior(inv_gamma(5, 1), class = sigma_trend), prior(normal(0.5, 0.25), class = ar1_trend) ) # `run_model = FALSE` builds the model without sampling. Its prior # table marks the replaced rows as "user". pre <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = dat, family = poisson(), prior = my_priors, run_model = FALSE) prior_summary(pre) # Next, drop `run_model = FALSE` to fit the model under these priors ## End(Not run)## Not run: set.seed(1) dat <- sim_mvgam(family = poisson(), n_series = 2L, n_timepoints = 120L, trend_model = AR())$data_train # Every prior the model takes, before any fitting. Trend classes # carry a `_trend` suffix: `b` belongs to the observation formula # and `b_trend` would belong to the trend formula. mf <- mvgam_formula(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1)) get_prior(mf, data = dat, family = poisson()) # Replace three defaults. Each `prior()` call gives one row. my_priors <- c( prior(std_normal(), class = b), prior(inv_gamma(5, 1), class = sigma_trend), prior(normal(0.5, 0.25), class = ar1_trend) ) # `run_model = FALSE` builds the model without sampling. Its prior # table marks the replaced rows as "user". pre <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = dat, family = poisson(), prior = my_priors, run_model = FALSE) prior_summary(pre) # Next, drop `run_model = FALSE` to fit the model under these priors ## End(Not run)
mvgam fitbroom-style summary of an mvgam fit, one row per response. Reports the
Stan algorithm, post-warmup sample size, training-observation
count, response family, link function and (optionally) loo
criteria. Mirrors broom.mixed::glance.brmsfit().
## S3 method for class 'mvgam' glance(x, looic = FALSE, resp = NULL, ...)## S3 method for class 'mvgam' glance(x, looic = FALSE, resp = NULL, ...)
x |
A fitted |
looic |
Logical. If |
resp |
Character specifying which response variable for multivariate models. NULL (default) returns predictions for all responses. |
... |
Forwarded to |
A tibble with one row, or on a multivariate fit given no
resp one row per response with a resp column. Columns:
algorithm – the algorithm the fit ran, such as "sampling"
or "meanfield".
pss – post-warmup sample size summed across chains.
nobs – number of (non-missing) training observations.
nseries – number of unique series in the training data.
family – observation-family name.
link – observation-family link.
Optional: elpd_loo, se_elpd_loo, p_loo, looic
(only when looic = TRUE).
tidy.mvgam(), augment.mvgam(), loo.mvgam()
Other tidiers:
augment.mvgam(),
tidy.mvgam()
## Not run: # A Poisson GAM without a latent trend. PSIS approximates each # held-out count of such a model well (see Details of ?loo.mvgam) set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = "None") mod <- mvgam(y ~ s(x), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) ## End(Not run) ## Not run: # The sampler and data dimensions of the fit, in one row glance(mod) # Leave-one-out criteria take longer to compute glance(mod, looic = TRUE) ## End(Not run)## Not run: # A Poisson GAM without a latent trend. PSIS approximates each # held-out count of such a model well (see Details of ?loo.mvgam) set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = "None") mod <- mvgam(y ~ s(x), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) ## End(Not run) ## Not run: # The sampler and data dimensions of the fit, in one row glance(mod) # Leave-one-out criteria take longer to compute glance(mod, looic = TRUE) ## End(Not run)
Posterior draws at the training time points. Each draw takes the
latent state the model inferred at each time. The observation
family maps it to the response scale. A hindcast shows how closely
the fitted states track the data. forecast.mvgam() predicts
unseen times.
hindcast(object, ...) ## S3 method for class 'mvgam' hindcast( object, ..., type = c("response", "link", "expected", "trend", "latent_state"), component = NULL, ndraws = NULL, draw_ids = NULL, obs_uncertainty = TRUE, process_error = FALSE, resp = NULL ) ## S3 method for class 'mvgam_latent_state' summary(object, probs = c(0.025, 0.25, 0.75, 0.975), ...) ## S3 method for class 'mvgam_latent_state' print(x, digits = 2L, ...) ## S3 method for class 'mvgam_latent_state' plot(x, series = NULL, ...)hindcast(object, ...) ## S3 method for class 'mvgam' hindcast( object, ..., type = c("response", "link", "expected", "trend", "latent_state"), component = NULL, ndraws = NULL, draw_ids = NULL, obs_uncertainty = TRUE, process_error = FALSE, resp = NULL ) ## S3 method for class 'mvgam_latent_state' summary(object, probs = c(0.025, 0.25, 0.75, 0.975), ...) ## S3 method for class 'mvgam_latent_state' print(x, digits = 2L, ...) ## S3 method for class 'mvgam_latent_state' plot(x, series = NULL, ...)
object |
A fitted mvgam object, or for
|
... |
Unused. Anything passed here is refused. |
type |
The scale of the draws, as in |
component |
|
ndraws |
Positive integer specifying number of posterior draws to use. NULL (default) uses all available draws. |
draw_ids |
Optional integer vector selecting a subset of posterior
draw indices to use. NULL (default) uses all draws (subject to
|
obs_uncertainty |
Logical, |
process_error |
Logical. |
resp |
Character specifying which response variable for multivariate models. NULL (default) returns predictions for all responses. |
probs |
For |
x |
An |
digits |
Integer number of digits in the printed range. Defaults to 2. |
series |
Names or indices of the series to plot, or |
An mvgam_forecast-class object. Its hindcasts are a
named list of [ndraws, n_times] matrices, one per series. Its
forecast slots are NULL.
forecast.mvgam() extrapolates the fitted state.
posterior_predict.mvgam() and posterior_epred.mvgam() predict
from the covariate part of the model. The
multivariate article compares
type = "trend" hindcasts of one latent state from a joint model
and from each data source alone. The
N-mixture article summarises
type = "latent_state" hindcasts of abundance.
Other predictions:
conditional_effects.mvgam(),
conditional_smooths.mvgam(),
fitted.mvgam(),
posterior_epred.mvgam(),
posterior_linpred.mvgam(),
posterior_predict.mvgam(),
posterior_smooths.mvgam(),
predict.mvgam(),
predictive_error.mvgam(),
predictive_interval.mvgam()
Other forecasting:
compare_scores(),
ensemble.mvgam_forecast(),
forecast.mvgam(),
forecast_uncertainty(),
lfo_cv.mvgam(),
score()
## Not run: set.seed(11) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam( y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2 ) # The fitted states track the training counts hc <- hindcast(mod) plot(hc) # The AR(1) trend on the log scale plot(hindcast(mod, type = "trend")) # Fresh innovations in place of the fitted states give the wider # spread a model without the observed history would predict plot(hindcast(mod, process_error = TRUE)) # A local linear trend's slope, the level's growth per step mod_llt <- update(mod, trend_formula = ~ LLT()) plot(hindcast(mod_llt, type = "trend", component = "slope")) # Next, forecast the held-out times with forecast() ## End(Not run)## Not run: set.seed(11) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam( y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2 ) # The fitted states track the training counts hc <- hindcast(mod) plot(hc) # The AR(1) trend on the log scale plot(hindcast(mod, type = "trend")) # Fresh innovations in place of the fitted states give the wider # spread a model without the observed history would predict plot(hindcast(mod, process_error = TRUE)) # A local linear trend's slope, the level's growth per step mod_llt <- update(mod, trend_formula = ~ LLT()) plot(hindcast(mod_llt, type = "trend", component = "slope")) # Next, forecast the held-out times with forecast() ## End(Not run)
Drafts a methods paragraph for a fitted model, with the references it cites and their BibTeX entries. The text and references follow the model's structure: the family and link, the trend, the factor identification and loadings prior, Gaussian process smooths, piecewise trends, the Stan backend and the sampling algorithm.
how_to_cite(object, ...) ## S3 method for class 'mvgam' how_to_cite(object, ...)how_to_cite(object, ...) ## S3 method for class 'mvgam' how_to_cite(object, ...)
object |
A fitted |
... |
Unused. Anything passed here is refused. |
A how_to_cite object holding the methods_text, the
citations it makes, an other_citations list of related
references and a bibtex list keyed by reference. bibtex()
extracts the BibTeX entries. print() shows every section.
Nicholas J Clark
methods_md() writes the model's equations to accompany
the paragraph. utils::citation() cites the package itself.
Other posterior summaries:
VarCorr.mvgam(),
bibtex(),
hypothesis.mvgam(),
index-mvgam,
mcmc_plot.mvgam(),
methods_md(),
mvgam_draws,
pairs.mvgam(),
posterior_interval.mvgam(),
ranef.mvgam(),
smooths.mvgam(),
summary.mvgam()
## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # A methods paragraph naming the Poisson family, the smooth and # the AR(1) trend, with the references it cites cite <- how_to_cite(mod) cite # The BibTeX entries, for a reference manager bibtex(cite) # Next, methods_md() writes the model's equations ## End(Not run)## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # A methods paragraph naming the Poisson family, the smooth and # the AR(1) trend, with the references it cites cite <- how_to_cite(mod) cite # The BibTeX entries, for a reference manager bibtex(cite) # Next, methods_md() writes the model's equations ## End(Not run)
The mvgam method of brms::hypothesis(), with the arguments and
parameter names of brms::hypothesis.brmsfit(). By default a
hypothesis names population-level coefficients without their b_
prefix, as "x > 0" tests b_x. class = NULL names any
parameter by the full name variables.mvgam() lists, such as
ar1_trend[series_1] or sigma. That help page sets out how the
names are formed.
## S3 method for class 'mvgam' hypothesis( x, hypothesis, class = "b", group = "", alpha = 0.05, robust = FALSE, seed = NULL, ... )## S3 method for class 'mvgam' hypothesis( x, hypothesis, class = "b", group = "", alpha = 0.05, robust = FALSE, seed = NULL, ... )
x |
A fitted |
hypothesis |
Character vector of hypothesis strings in the
|
class |
The class prefix the names in |
group |
The grouping factor of a group-level class, as
|
alpha |
One minus the credible-interval mass. Defaults
to |
robust |
Logical. If |
seed |
Optional integer seed for the random draws of an evidence ratio. The session's random state is restored when the call returns. |
... |
Forwarded to |
A brmshypothesis object. See brms::hypothesis().
Nicholas J Clark
brms::hypothesis(), variables.mvgam().
Other posterior summaries:
VarCorr.mvgam(),
bibtex(),
how_to_cite.mvgam(),
index-mvgam,
mcmc_plot.mvgam(),
methods_md(),
mvgam_draws,
pairs.mvgam(),
posterior_interval.mvgam(),
ranef.mvgam(),
smooths.mvgam(),
summary.mvgam()
## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ x, trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # A population-level coefficient, named as fixef() names it. hypothesis(mod, "x > 0") # Any parameter by its full name. hypothesis(mod, c("ar1_trend[series_1] > 0", "sigma_trend[series_1] < 1"), class = NULL) ## End(Not run)## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ x, trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # A population-level coefficient, named as fixef() names it. hypothesis(mod, "x > 0") # Any parameter by its full name. hypothesis(mod, c("ar1_trend[series_1] > 0", "sigma_trend[series_1] < 1"), class = NULL) ## End(Not run)
variables() lists the name of every quantity in a fitted model's
draws. hypothesis.mvgam(), as_draws(), as.data.frame.mvgam(),
mcmc_plot.mvgam() and posterior_average.mvgam() accept these
names. summary.mvgam() and posterior_summary() label their rows
with them.
## S3 method for class 'mvgam' variables(x, ...)## S3 method for class 'mvgam' variables(x, ...)
x |
A fitted |
... |
Unused. Anything passed here is refused. |
A character vector of parameter names.
Observation parameters take their brms names, such as b_x,
sds_sx_1, sd_site__Intercept and r_site[a,Intercept]. The
trend model's parameters take the same names with a _trend
suffix, such as b_x_trend or sds_sx_1_trend.
An index that runs over the series takes the series' name, as
brms labels a grouping factor's levels. A model with series
DM and DO has sigma_trend[DM], ar1_trend[DM] and the
innovation covariance Sigma_trend[DM,DO]. A VAR's coefficients
keep the lag as a number, as in Phi_trend[1,DM,DO], as do the
changepoints of PW() in delta_trend[3,DM]. Factor loadings are
Z_tilde[DM,1], with the factor as the second index. In a factor
model the dynamics belong to the factors, as in ar1_trend[1].
The latent state matrices keep numeric indices, as in
trend[12,1] for time 12 of the first series.
A bare name such as variable = "sigma_trend" selects every element
of a vector, as in posterior. Because variables() includes
the latent states, its output runs to hundreds of names on most
fits. grep() narrows it, as in
grep("^(sigma|ar1)_trend", variables(fit), value = TRUE).
Nicholas J Clark
mvgam_draws to extract draws by name,
hypothesis.mvgam() to test them, summary.mvgam() and
posterior_summary() to summarise them.
Other posterior summaries:
VarCorr.mvgam(),
bibtex(),
how_to_cite.mvgam(),
hypothesis.mvgam(),
mcmc_plot.mvgam(),
methods_md(),
mvgam_draws,
pairs.mvgam(),
posterior_interval.mvgam(),
ranef.mvgam(),
smooths.mvgam(),
summary.mvgam()
## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 2L, trend_model = AR()) mod <- mvgam(y ~ x, trend_formula = ~ AR(), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # The trend dynamics, indexed by series grep("^(sigma|ar1)_trend", variables(mod), value = TRUE) # Every element of a vector by its bare name as_draws_df(mod, variable = "sigma_trend") # Two series' autoregressive coefficients compared hypothesis(mod, "ar1_trend[series_1] > ar1_trend[series_2]", class = NULL) # Next, plot chosen parameters with mcmc_plot(mod, variable = ...) ## End(Not run)## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 2L, trend_model = AR()) mod <- mvgam(y ~ x, trend_formula = ~ AR(), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # The trend dynamics, indexed by series grep("^(sigma|ar1)_trend", variables(mod), value = TRUE) # Every element of a vector by its bare name as_draws_df(mod, variable = "sigma_trend") # Two series' autoregressive coefficients compared hypothesis(mod, "ar1_trend[series_1] > ar1_trend[series_2]", class = NULL) # Next, plot chosen parameters with mcmc_plot(mod, variable = ...) ## End(Not run)
The init argument each chain started from.
## S3 method for class 'mvgam' inits(x, ...)## S3 method for class 'mvgam' inits(x, ...)
x |
A fitted |
... |
Unused. Anything passed here is refused. |
A list with one element per chain.
Compute Generalized or Orthogonalized Impulse Response Functions (IRFs) from
mvgam models with Vector Autoregressive dynamics. An impulse
response traces how the latent trend of every series moves over h
time steps after a one-standard-deviation innovation to one series.
The default generalised responses suit most analyses. Orthogonalised
responses need a causal ordering of the series.
irf(object, ...) ## S3 method for class 'mvgam' irf( object, h = 10, cumulative = FALSE, orthogonal = FALSE, ndraws = NULL, draw_ids = NULL, summary = TRUE, probs = c(0.025, 0.975), future = FALSE, ... )irf(object, ...) ## S3 method for class 'mvgam' irf( object, h = 10, cumulative = FALSE, orthogonal = FALSE, ndraws = NULL, draw_ids = NULL, summary = TRUE, probs = c(0.025, 0.975), future = FALSE, ... )
object |
An object of class |
... |
Unused. Anything passed here is refused. |
h |
Positive integer. The number of horizons to compute. Horizon 1 is the time step of the shock. |
cumulative |
Logical. |
orthogonal |
Logical. |
ndraws |
Positive integer specifying number of posterior draws to use. NULL (default) uses all available draws. |
draw_ids |
Optional integer vector selecting a subset of posterior
draw indices to use. NULL (default) uses all draws (subject to
|
summary |
Logical; return the posterior median and interval of
each response (the default), or the per-draw responses themselves.
The draws are one |
probs |
The lower and upper percentiles of the interval reported
with the median when |
future |
|
See mvgam_irf-class for the quantities computed and
returned, with references.
An object of mvgam_irf-class. plot.mvgam_irf()
and summary.mvgam_irf() take it.
Nicholas J Clark
Lutkepohl H (2005). New Introduction to Multiple Time Series Analysis. Springer, Berlin. doi:10.1007/978-3-540-27752-1
Pesaran HH and Shin Y (1998). Generalized impulse response analysis in linear multivariate models. Economics Letters 58, 17-29. doi:10.1016/S0165-1765(97)00214-0
fevd() and stability() summarise the same VAR dynamics.
The VAR article runs irf() on a
plankton community. The
hierarchical VAR article
runs it on each group of a hierarchical VAR.
Other latent dynamics:
active_factors(),
compare_loadings(),
fevd.mvgam(),
ordinate(),
posterior_transition_matrix(),
residual_cor(),
shared_variation(),
stability.mvgam()
## Not run: # Ten years of monthly counts of a prey species and its predator. # Predators suppress the prey a month later. Prey raise the # predators a month later. set.seed(2025) n_months <- 120 A <- rbind(prey = c(0.6, -0.5), predator = c(0.4, 0.5)) z <- matrix(0, n_months, 2) for (t in 2:n_months) { z[t, ] <- A %*% z[t - 1, ] + rnorm(2, sd = 0.35) } predator_prey <- data.frame( time = rep(seq_len(n_months), 2), series = factor(rep(c("prey", "predator"), each = n_months), levels = c("prey", "predator")), y = rpois(2 * n_months, exp(c(2.5 + z[, 1], 1.5 + z[, 2]))) ) var_mod <- mvgam(y ~ series, trend_formula = ~ VAR(), data = predator_prey, family = poisson(), chains = 2, silent = 2) ## End(Not run) ## Not run: # Generalised responses of every series to a shock in each irf_obj <- irf(var_mod, h = 8L) plot(irf_obj, series = 1) # Next: fevd() splits each series' forecast variance among the # shocks. stability() summarises how the system returns to # equilibrium ## End(Not run)## Not run: # Ten years of monthly counts of a prey species and its predator. # Predators suppress the prey a month later. Prey raise the # predators a month later. set.seed(2025) n_months <- 120 A <- rbind(prey = c(0.6, -0.5), predator = c(0.4, 0.5)) z <- matrix(0, n_months, 2) for (t in 2:n_months) { z[t, ] <- A %*% z[t - 1, ] + rnorm(2, sd = 0.35) } predator_prey <- data.frame( time = rep(seq_len(n_months), 2), series = factor(rep(c("prey", "predator"), each = n_months), levels = c("prey", "predator")), y = rpois(2 * n_months, exp(c(2.5 + z[, 1], 1.5 + z[, 2]))) ) var_mod <- mvgam(y ~ series, trend_formula = ~ VAR(), data = predator_prey, family = poisson(), chains = 2, silent = 2) ## End(Not run) ## Not run: # Generalised responses of every series to a shock in each irf_obj <- irf(var_mod, h = 8L) plot(irf_obj, series = 1) # Next: fevd() splits each series' forecast variance among the # shocks. stability() summarises how the system returns to # equilibrium ## End(Not run)
Tests whether an object is a valid mvgam trend specification.
is.mvgam_trend(x)is.mvgam_trend(x)
x |
Object to test |
Logical indicating if x is a mvgam trend
Fits a joint species distribution model (JSDM) to the presences,
detections or counts of many species across many sampling units.
Species often co-occur more or less often than their responses to
the measured covariates predict. A few latent factors capture that
residual association. They need far fewer parameters than a full
correlation matrix among species. The observation model takes the
smooths, Gaussian processes and random effects of any mvgam model.
The factors take their own predictors through factor_formula.
Write lv_axis() in one of its terms to give each factor its own
effect of a covariate, a constrained ordination.
jsdgam( formula, factor_formula = ~-1, knots, data, newdata, family = binomial(), unit = time, species = series, priors, n_lv = 2L, traits = NULL, trait_slopes = NULL, phylo = NULL, loadings_prior = NULL, backend = default_backend(), threads = NULL, run_model = TRUE, ... )jsdgam( formula, factor_formula = ~-1, knots, data, newdata, family = binomial(), unit = time, species = series, priors, n_lv = 2L, traits = NULL, trait_slopes = NULL, phylo = NULL, loadings_prior = NULL, backend = default_backend(), threads = NULL, run_model = TRUE, ... )
formula |
The observation model formula, in brms syntax:
smooths |
factor_formula |
A one-sided formula for the latent factors'
linear predictor. Write |
knots |
Optional named list of knot positions for smooth terms,
by covariate, as |
data |
A Data held as arrays, as unmarked, ubms,
flocker, Hmsc and spOccupancy take them, convert
to this long format. |
newdata |
Optional held-out |
family |
The observation family every species shares, as a
family object. mvgam_families lists them. Defaults to
The factors and a family's dispersion parameter, such as For one family per species, write The simplex families |
unit |
The unquoted name of the numeric column indexing the
sampling units, often |
species |
The unquoted name of the factor column indexing the
species. Defaults to |
priors |
Optional |
n_lv |
Integer number of latent factors, from 1 to the number
of species. Defaults to 2. The residual covariance
Under the default normal prior on |
traits |
Optional species traits for a structured loadings
prior: a |
trait_slopes |
Optional one-sided formula of traits, such as
|
phylo |
Optional phylogeny: an |
loadings_prior |
Optional structured prior on the loadings, as
|
backend |
|
threads |
Positive integer number of threads per chain, or
A brms family with a |
run_model |
Logical. |
... |
Further arguments of |
A fitted model of class c("mvgam", "jsdgam", "brmsfit").
Every mvgam method applies, such as summary(), predict(),
forecast() and loo(). ordinate() and residual_cor()
describe the factors. update(fit, n_lv = 3) refits it through
jsdgam() with the arguments given changed.
trait_slopes = ~ size adds terms to formula. Each term takes a
shared effect, an effect of each trait and a species deviation:
size, with the species deviation 1 in
(1 + ... | sp | series)
a numeric or factor covariate, an
interaction, I(), poly(), mo(), me() or mi(): the term
env:size and the deviation env in (1 + env | sp | series).
The |sp| tag correlates the deviations under one LKJ prior.
s() or t2()
s(x, by = size) scales the
smooth by the trait. s(x, by = series, m = 1) gives each species
a smooth penalised towards a flat line.
gp()
gp(x, by = size) and
gp(x, by = series), one approximate process per species
entered as written, as is a smooth with
bs = "re" or bs = "fs"
A smooth trait, ~ s(size), gives the intercept s(size). Each
design column of a covariate scales the trait's smooth: env takes
s(size, by = env) and a factor hab takes s(size, by = habb). A
smooth of x takes the surface t2(x, size). A smooth with its own
by, such as s(x, by = hab), crosses the trait level by level.
Its species deviations keep the by. mo(), me() and mi()
terms cross linear traits alone.
A smooth or gp() takes one column of data as its by. A factor
level, a poly() column or a by scaled per species enters through
a derived column. Its name follows fixef.mvgam(), such as habb,
polyx21 or env_size. Each prediction frame recomputes these
columns from the variables they come from. A frame that changes
env then changes env_size.
A crossing of a centred smooth passes through zero at the mean of its
covariates (mgcv's pc). The shared term then carries the effect at
the means. mgcv leaves a smooth with a numeric by uncentred. Its
crossing keeps the constant, the trait's effect on that column's
slope. A t2() surface takes first-order margins. Their penalties
separate it from the main smooths. A margin of one covariate is a thin
plate spline, or keeps a cyclic basis. An s() of several covariates
gives one isotropic Duchon spline margin.
The coefficients take their brms names, such as b_env:size. Each
population-level coefficient takes normal(0, r / s) by default. s
is the SD of its design column. r is 1, or the SD of the response
under an identity link, which keeps the coefficients in its units.
Every covariate then has one prior scale on the link, whatever its
units or the basis poly() gives it, as rstanarm's autoscaled priors
do. student_t(3, 0, 2.5 r) is the default on the SDs of the
correlated species deviations. The smooth and gp() deviations take
the brms defaults. priors overrides any of them. A prior on class
b without a coef replaces every coefficient's default. A term of
formula naming the species is refused: each species already takes
its own response. For some of these terms alone, write them in
formula directly, as in
y ~ env + size + env:size + (1 + env | series).
Warton, D. I., Blanchet, F. G., O'Hara, R. B., Ovaskainen, O., Taskinen, S., Walker, S. C. and Hui, F. K. C. (2015). So many variables: joint modeling in community ecology. Trends in Ecology and Evolution, 30(12):766-779. doi:10.1016/j.tree.2015.09.007
Ovaskainen, O., Tikhonov, G., Norberg, A., Blanchet, F. G., Duan, L., Dunson, D., Roslin, T. and Abrego, N. (2017). How to make more out of community data? Ecology Letters, 20(5):561-576. doi:10.1111/ele.12757
Tikhonov, G., Opedal, O. H., Abrego, N., Lehikoinen, A., de Jonge, M. M. J., Oksanen, J. and Ovaskainen, O. (2020). Joint species distribution modelling with the R-package Hmsc. Methods in Ecology and Evolution, 11(3):442-447. doi:10.1111/2041-210X.13345
Hui, F. K. C. (2016). boral - Bayesian Ordination and Regression Analysis of Multivariate Abundance Data in R. Methods in Ecology and Evolution, 7(6):744-750. doi:10.1111/2041-210X.12514
Heaps, S. E. and Jermyn, I. H. (2024). Structured prior distributions for the covariance matrix in latent factor models. Statistics and Computing, 34:143. doi:10.1007/s11222-024-10454-0
sim_jsdgam() simulates data this function fits.
sim_closure_unit_data() simulates the occ() and nmix()
case. residual_cor(), ordinate(), shared_variation(),
active_factors() and compare_loadings() interpret the fitted
factors. species_effects() gives each species' response to the
covariates. community() gives richness, diversity and
co-occurrence. lv_axis() gives each factor its own covariate
effect. how_to_cite() drafts a methods paragraph for the fit and
methods_md() writes its equations.
The JSDM article fits a negative
binomial model with a trait-informed loadings prior, ordination
biplots and multiplicative gamma process shrinkage. The
JSDM cheatsheet summarises the
functions on one page.
Other model fitting:
check_newdata(),
mvgam(),
mvgam_data(),
mvgam_multiple(),
pivot_detection_array(),
pivot_species_matrix(),
print.mvgam_formula(),
series_to_mvgam(),
stancode.mvgam_formula(),
update.mvgam()
## Not run: # Detections of 6 species at 80 sites, 4 visits each. Occupancy # responds to the site covariate `env` and detection to the time of # day `tod_c`. Two latent factors drive the species associations. simdat <- sim_closure_unit_data( family = occ(), n_species = 6L, n_sites = 80L, n_visits = 4L, n_lv = 2L, seed = 1L ) # A joint occupancy model. Each species has its own occupancy # intercept and `env` slope, plus its own detection intercept. Two # latent factors take up the residual association. mod <- jsdgam( formula = bf(y ~ series * env, p ~ series + tod_c), factor_formula = ~ -1, data = simdat$data_train, family = occ(), n_lv = 2L, chains = 2, silent = 2 ) summary(mod) # The effect of `env` on the chance of a detection, occupancy times # detection conditional_effects(mod) # Each species' response to env, outlined where its sign is clear plot(species_effects(mod, variables = "env")) # The residual correlations among species the factors imply plot(residual_cor(mod)) # Site scores and species loadings on the two factors ordinate(mod, rotation = "varimax") # Expected richness along `env`. The second plot marks the pairs of # species found together more often than `env` predicts. gradient <- datagrid(model = mod, env = seq(-2, 2, length.out = 20)) cm <- community(mod, newdata = gradient) plot(cm) plot(cm, type = "cooccurrence") # The draws, for any contrast: richness at the end of the gradient # less that at its start rv <- as_draws_rvars(cm) rv$richness[20] - rv$richness[1] # Next, compare n_lv = 1 with update(mod, n_lv = 1L) and loo() ## End(Not run)## Not run: # Detections of 6 species at 80 sites, 4 visits each. Occupancy # responds to the site covariate `env` and detection to the time of # day `tod_c`. Two latent factors drive the species associations. simdat <- sim_closure_unit_data( family = occ(), n_species = 6L, n_sites = 80L, n_visits = 4L, n_lv = 2L, seed = 1L ) # A joint occupancy model. Each species has its own occupancy # intercept and `env` slope, plus its own detection intercept. Two # latent factors take up the residual association. mod <- jsdgam( formula = bf(y ~ series * env, p ~ series + tod_c), factor_formula = ~ -1, data = simdat$data_train, family = occ(), n_lv = 2L, chains = 2, silent = 2 ) summary(mod) # The effect of `env` on the chance of a detection, occupancy times # detection conditional_effects(mod) # Each species' response to env, outlined where its sign is clear plot(species_effects(mod, variables = "env")) # The residual correlations among species the factors imply plot(residual_cor(mod)) # Site scores and species loadings on the two factors ordinate(mod, rotation = "varimax") # Expected richness along `env`. The second plot marks the pairs of # species found together more often than `env` predicts. gradient <- datagrid(model = mod, env = seq(-2, 2, length.out = 20)) cm <- community(mod, newdata = gradient) plot(cm) plot(cm, type = "cooccurrence") # The draws, for any contrast: richness at the end of the gradient # less that at its start rv <- as_draws_rvars(cm) rv$richness[20] - rv$richness[1] # Next, compare n_lv = 1 with update(mod, n_lv = 1L) and loo() ## End(Not run)
mvgam fitsMeasures how well a model predicts groups of data it was not fitted
to, such as sites or species. Each fold of groups is held out in
turn and scored by its expected log predictive density (ELPD).
Higher is better. A fold that importance sampling approximates well takes the
PSIS estimate of loo::loo() on the fold's summed log likelihood.
The rest are refitted without the fold, as lfo_cv.mvgam() refits
the time blocks it cannot approximate. Three settings cover the
range:
pareto_k_threshold = Inf refits nothing. Pareto-k
warnings mark folds the approximation fits poorly.
The default refits the folds whose Pareto-k exceeds
pareto_k_threshold, which is often a handful.
exact = TRUE refits every fold, as brms::kfold() does.
group takes several columns, such as c("site", "season"). Every
row of one combination stays in the same fold.
## S3 method for class 'mvgam' kfold( x, K = NULL, group = NULL, folds = NULL, exact = FALSE, pareto_k_threshold = NULL, fold_split = c("grouped", "stratified", "random"), seed = NULL, silent = 1L, ... ) ## S3 method for class 'mvgam_kfold' print(x, digits = 2L, ...) ## S3 method for class 'mvgam_kfold' summary(object, ...) ## S3 method for class 'mvgam_kfold' plot(x, ...)## S3 method for class 'mvgam' kfold( x, K = NULL, group = NULL, folds = NULL, exact = FALSE, pareto_k_threshold = NULL, fold_split = c("grouped", "stratified", "random"), seed = NULL, silent = 1L, ... ) ## S3 method for class 'mvgam_kfold' print(x, digits = 2L, ...) ## S3 method for class 'mvgam_kfold' summary(object, ...) ## S3 method for class 'mvgam_kfold' plot(x, ...)
x |
A fitted |
K |
Integer number of folds. With |
group |
Optional character vector of training-data columns
whose combinations define the groups. |
folds |
Optional integer vector of one fold per training row,
replacing |
exact |
Logical. |
pareto_k_threshold |
Numeric. A fold whose Pareto-k exceeds
it is refitted. |
fold_split |
|
seed |
Optional integer seed for the fold split and the refits. The session's random state is restored when the call returns. |
silent |
Integer in |
... |
Unused. Anything passed here is refused. |
digits |
Integer number of decimal places. Defaults to 2. |
object |
An |
A c("mvgam_kfold", "kfold", "loo") object, which
loo::loo_compare() takes as it takes loo.mvgam() results. It
holds:
estimates: elpd_kfold, p_kfold and kfoldic with
their standard errors.
pointwise: the ELPD of each group. pointwise_psis holds
the PSIS estimates before any refit.
pareto_k: the Pareto-k of each group's PSIS estimate, all
NA under exact = TRUE.
n_refits and refit_groups: the number of refitted folds
and the groups they hold.
K and exact: the number of folds and the mode.
group: the grouping columns, "fold" when folds was
given, or NULL for single rows.
pareto_k_threshold: the threshold applied, with
pareto_k_threshold_adaptive TRUE when the default rule set
it.
print() shows the ELPD with its standard error, the folds and
refits and the Pareto k of the PSIS estimates. It then names the
groups with the lowest ELPD and the refitted groups whose ELPD moved
most from the PSIS estimate. summary() returns a tibble with one
row per held-out group: group, its elpd and elpd_share of the
total, for a refitted group elpd_psis and the lift of the refit
over it, pareto_k and refit. plot() draws the ELPD of each
group and its Pareto k, as plot.mvgam_lfo() does for time blocks.
Dark red points mark a Pareto k above the dashed threshold, where
PSIS is unreliable. In the ELPD panel they mark the groups below the
15% quantile.
Nicholas J Clark
Burkner, P.-C., Gabry, J. and Vehtari, A. (2020). Approximate leave-future-out cross-validation for Bayesian time series models. Journal of Statistical Computation and Simulation, 90(14):2499-2523. doi:10.1080/00949655.2020.1783262
Vehtari, A., Gelman, A. and Gabry, J. (2017). Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC. Statistics and Computing, 27:1413-1432. doi:10.1007/s11222-016-9696-4
loo.mvgam() approximates leave-one-out cross-validation.
lfo_cv.mvgam() scores forecasts from rolling origins.
summary.mvgam_kfold() and plot.mvgam_kfold() report each group.
The
forecast evaluation article
compares models by cross-validation.
Other model comparison:
bridge_sampler.mvgam(),
compare_elpds(),
lfo_cv.mvgam(),
log_lik.mvgam(),
loo.mvgam(),
loo_compare.mvgam_lfo(),
mvgam_loo_extras,
posterior_average.mvgam(),
waic.mvgam()
## Not run: # Overdispersed counts: a negative binomial size of 2 set.seed(13) simdat <- sim_mvgam(family = negbinomial(), n_series = 1L, n_timepoints = 120L, type = 6L, family_pars = list(size = 2)) mod <- mvgam(y ~ s(season, bs = "cc", k = 6), trend_formula = ~ CAR(), data = simdat$data_train, family = negbinomial(), chains = 2, seed = 1, silent = 2) # Neighbouring times share information through the trend. Folds of # contiguous time blocks hold each block out whole. Folds that PSIS # approximates poorly are refitted. blocks <- cut(simdat$data_train$time, breaks = 4L, labels = FALSE) k <- kfold(mod, folds = blocks) k # The ELPD and Pareto k of each block plot(k) # Next, lfo_cv() scores forecasts made from rolling origins ## End(Not run)## Not run: # Overdispersed counts: a negative binomial size of 2 set.seed(13) simdat <- sim_mvgam(family = negbinomial(), n_series = 1L, n_timepoints = 120L, type = 6L, family_pars = list(size = 2)) mod <- mvgam(y ~ s(season, bs = "cc", k = 6), trend_formula = ~ CAR(), data = simdat$data_train, family = negbinomial(), chains = 2, seed = 1, silent = 2) # Neighbouring times share information through the trend. Folds of # contiguous time blocks hold each block out whole. Folds that PSIS # approximates poorly are refitted. blocks <- cut(simdat$data_train$time, breaks = 4L, labels = FALSE) k <- kfold(mod, folds = blocks) k # The ELPD and Pareto k of each block plot(k) # Next, lfo_cv() scores forecasts made from rolling origins ## End(Not run)
A state-space dataset for five lakes sampled monthly across 60 months. Each sample records total phosphorus in micrograms per litre, drawn from a Gamma distribution with a log link. The latent process is a correlated random walk across lakes. Two regional clusters share positive innovation correlation. A fifth lake is independent. The observation equation adds a binary treatment indicator that switches on at month 31, with heterogeneous slopes across lakes. Phosphorus rises in two lakes and falls in three.
lake_chemistrylake_chemistry
A data.frame with 300 rows and the following fields:
factor identifying the lake (alpine,
boreal, coastal, delta, estuary); duplicated as
lake.
integer month index from 1 to 60.
positive total phosphorus in micrograms per litre;
duplicated as chemistry.
factor, alias of series.
integer month index, alias of time.
integer (0/1) treatment indicator; switches on from month 31 onwards in all lakes.
positive total phosphorus, alias of y.
A pooled fit with one treatment slope for all lakes reports an
effect near zero with a wide credible interval. The positive and
negative responses cancel. A state-space fit
(trend_formula = ~ RW(cor = TRUE)) with a treatment slope for each
lake recovers the response of every lake.
True generative components, on the log scale:
An intercept of log(20), a typical 20 micrograms per litre.
Each lake adds its own centred intercept.
Latent random walk with cross-lake innovation correlation
0.6 between (alpine, boreal) and (coastal, delta),
independent for estuary. Innovation standard deviation
0.1.
Heterogeneous treatment slopes:
(alpine = +0.8, boreal = +0.6, coastal = -0.5, delta = -0.7, estuary = -0.6).
Gamma observations with shape 10, a coefficient of variation
near 0.32.
RW() for the trend, residual_cor() to extract the fitted
correlations between lakes, ranef.mvgam() for the lake slopes,
mvgam_data() to check the data.
data(lake_chemistry) mvgam_data(lake_chemistry, family = Gamma(link = "log")) ## Not run: # A model with the structure the data were simulated from mod <- mvgam( formula = y ~ treated + (treated || lake), trend_formula = ~ RW(cor = TRUE), data = lake_chemistry, family = Gamma(link = "log"), chains = 2, silent = 2 ) summary(mod) ## End(Not run)data(lake_chemistry) mvgam_data(lake_chemistry, family = Gamma(link = "log")) ## Not run: # A model with the structure the data were simulated from mod <- mvgam( formula = y ~ treated + (treated || lake), trend_formula = ~ RW(cor = TRUE), data = lake_chemistry, family = Gamma(link = "log"), chains = 2, silent = 2 ) summary(mod) ## End(Not run)
The sum over a unit's latent abundance stops at its cap K_max. A
unit whose posterior abundance often equals the cap is truncated,
which biases its abundance down. A higher value in that unit's cap
column, then a refit, removes the bias. Under occ() the cap is one,
and a unit at its cap is one the species occupies.
latent_N_saturation( object, newdata = NULL, threshold = 0.05, ndraws = NULL, draw_ids = NULL )latent_N_saturation( object, newdata = NULL, threshold = 0.05, ndraws = NULL, draw_ids = NULL )
object |
|
newdata |
Optional |
threshold |
Number in |
ndraws, draw_ids
|
The number of posterior draws to use, or
their indices. Give at most one. |
A data.frame with one row per closure unit:
unitThe unit's index.
labelThe unit's key values, joined by _.
K_maxThe unit's cap.
p_saturatedThe posterior probability that the latent
state equals K_max.
saturatedp_saturated > threshold.
## Not run: set.seed(5) simdat <- sim_closure_unit_data(family = nmix(), n_species = 1L, n_sites = 50L, n_visits = 4L, type = 1L) # A cap of 3 is low for these counts dat <- simdat$data_train dat$cap <- pmax(3L, ave(dat$y, dat$series, dat$time, FUN = max)) mod <- mvgam(bf(y ~ env, p ~ tod_c), data = dat, family = nmix(), chains = 2, silent = 2) saturation <- latent_N_saturation(mod) saturation[saturation$saturated, ] # Next, raise 'cap' for the saturated units and refit ## End(Not run)## Not run: set.seed(5) simdat <- sim_closure_unit_data(family = nmix(), n_species = 1L, n_sites = 50L, n_visits = 4L, type = 1L) # A cap of 3 is low for these counts dat <- simdat$data_train dat$cap <- pmax(3L, ave(dat$y, dat$series, dat$time, FUN = max)) mod <- mvgam(bf(y ~ env, p ~ tod_c), data = dat, family = nmix(), chains = 2, silent = 2) saturation <- latent_N_saturation(mod) saturation[saturation$saturated, ] # Next, raise 'cap' for the saturated units and refit ## End(Not run)
Scores a model on its forecasts. The model is fitted to the times up
to min_t and scored on the next fc_horizon observed times. The
origin then steps forward one time at a time. Pareto smoothed
importance sampling (PSIS) reweights the posterior to each new
origin. The model is refitted only where the Pareto k exceeds
pareto_k_threshold. The algorithm is that of Burkner, Gabry and
Vehtari (2020), as in the
loo PSIS-LFO vignette.
The ELPD of each fold is higher for the better model. CRPS and the
other scores of score.mvgam_forecast() are lower for the better
model. loo.mvgam() explains the ELPD and the Pareto k diagnostic.
lfo_cv(object, ...) ## S3 method for class 'mvgam' lfo_cv( object, newdata = NULL, min_t = NULL, fc_horizon = 1L, pareto_k_threshold = NULL, score = "elpd", save_log_lik = FALSE, silent = 1L, ..., data = NULL ) ## S3 method for class 'mvgam_lfo' plot(x, ...) ## S3 method for class 'mvgam_lfo' summary(object, ...) ## S3 method for class 'mvgam_lfo' print(x, ...)lfo_cv(object, ...) ## S3 method for class 'mvgam' lfo_cv( object, newdata = NULL, min_t = NULL, fc_horizon = 1L, pareto_k_threshold = NULL, score = "elpd", save_log_lik = FALSE, silent = 1L, ..., data = NULL ) ## S3 method for class 'mvgam_lfo' plot(x, ...) ## S3 method for class 'mvgam_lfo' summary(object, ...) ## S3 method for class 'mvgam_lfo' print(x, ...)
object |
A fitted mvgam object, or for
|
... |
Unused. Anything passed here is refused. |
newdata |
Optional |
min_t |
The time at which the first training window ends. It
must be a time present in the data, which need not be whole for an
irregular |
fc_horizon |
Integer number of observed times after each origin that are scored, whatever the gaps between them. Defaults to 1. |
pareto_k_threshold |
Numeric. An origin whose Pareto k exceeds
it triggers a refit. |
score |
Character vector of scores to compute at each origin,
from |
save_log_lik |
Logical. |
silent |
Integer in |
data |
Deprecated alias for |
x |
An |
A list of class mvgam_lfo, with one element per origin in
each vector.
elpds: the approximate ELPD of each origin, NULL unless
"elpd" is in score. sum_ELPD is their sum.
scores: a named list with one vector for each other score.
pareto_ks: the Pareto k of each origin's importance weights,
NA where the model was refitted.
eval_timepoints: the first scored time of each origin.
n_obs: the number of responses each origin scores.
refits_at: the last training time of each refit.
refit_triggered: TRUE at each origin scored on a refit.
pareto_k_threshold: the threshold used. TRUE in
pareto_k_threshold_adaptive marks the adaptive rule.
fc_horizon: the horizon.
log_lik: the held-out log densities when save_log_lik = TRUE,
otherwise NULL.
print() shows the horizon, the Pareto k threshold and the counts
of evaluations and refits, with each score's sum and mean over the
origins. summary() returns a tibble with one row per origin:
eval_time, refit_here, pareto_k (NA at a refit), n_obs
and one column per score. plot() draws the Pareto k of each
origin and each score. The dashed line marks the threshold above
which points are highlighted: the Pareto k threshold, the 15%
quantile of the ELPD (lower values highlighted) or the 85% quantile
of any other score.
Nicholas J Clark
Burkner, P.-C., Gabry, J. and Vehtari, A. (2020). Approximate leave-future-out cross-validation for Bayesian time series models. Journal of Statistical Computation and Simulation, 90(14):2499-2523. doi:10.1080/00949655.2020.1783262
Vehtari, A., Simpson, D., Gelman, A., Yao, Y. and Gabry, J. (2024). Pareto smoothed importance sampling. Journal of Machine Learning Research, 25(72):1-58. https://jmlr.org/papers/v25/19-556.html
loo_compare.mvgam_lfo() ranks models by their
leave-future-out ELPD. loo_model_weights.mvgam_lfo() weights
them. loo.mvgam() approximates leave-one-out cross-validation.
kfold.mvgam() runs grouped k-fold cross-validation. The
forecast evaluation article
runs lfo_cv() on rodent counts, with its Pareto k refits and
stacking weights.
Other forecasting:
compare_scores(),
ensemble.mvgam_forecast(),
forecast.mvgam(),
forecast_uncertainty(),
hindcast(),
score()
Other model comparison:
bridge_sampler.mvgam(),
compare_elpds(),
kfold.mvgam(),
log_lik.mvgam(),
loo.mvgam(),
loo_compare.mvgam_lfo(),
mvgam_loo_extras,
posterior_average.mvgam(),
waic.mvgam()
## Not run: set.seed(11) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam( y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, seed = 1, silent = 2 ) # Forecasts one time step after each origin from t = 60, scored by # ELPD and CRPS. The model is refitted only where the Pareto k is high. lfo <- lfo_cv(mod, min_t = 60L, score = c("elpd", "crps")) lfo # Pareto k, ELPD and CRPS at each origin. Points past the dashed # line are highlighted plot(lfo) # One row per origin, with the refits in 'refit_here' summary(lfo) # Next, rank models by their forecasts with loo_compare() ## End(Not run)## Not run: set.seed(11) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam( y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, seed = 1, silent = 2 ) # Forecasts one time step after each origin from t = 60, scored by # ELPD and CRPS. The model is refitted only where the Pareto k is high. lfo <- lfo_cv(mod, min_t = 60L, score = c("elpd", "crps")) lfo # Pareto k, ELPD and CRPS at each origin. Points past the dashed # line are highlighted plot(lfo) # One row per origin, with the refits in 'refit_here' summary(lfo) # Next, rank models by their forecasts with loo_compare() ## End(Not run)
List all registered trend types and their factor model support.
list_trend_types()list_trend_types()
Data frame with trend types and their properties
Other trend models:
LLT(),
PW(),
ZMVN(),
lv_axis(),
print.mvgam_trend()
A latent level that moves with a latent growth rate, the local linear trend of Harvey (1989). Each latent process carries a level and a slope:
The level innovations have scale sigma_trend and the
slope innovations scale sigma_slope_trend. A small
sigma_slope_trend gives a trend that keeps its direction. A zero
scale gives a random walk with a fixed drift. damped = TRUE
estimates on (0, 1) as ar1_slope_trend, which pulls
the growth rate back toward zero over the horizon (Gardner and
McKenzie 1985). The undamped trend has . Its
forecasts extend the current growth rate.
LLT( time = NA, series = NA, damped = FALSE, cor = NULL, gr = NA, subgr = NA, n_lv = NULL, trend_map = NULL, df = Inf, season = NULL, harmonics = NULL, centred = FALSE )LLT( time = NA, series = NA, damped = FALSE, cor = NULL, gr = NA, subgr = NA, n_lv = NULL, trend_map = NULL, df = Inf, season = NULL, harmonics = NULL, centred = FALSE )
time |
The unquoted name of the |
series |
The unquoted name of the |
damped |
Logical. Estimate a damping coefficient for the
slope? Default |
cor |
In a factor model with every loading sampled, the factors take
independent shocks. The loadings carry the correlation among
series, which |
gr |
An optional
Here Within a Two constraints apply to hierarchical trend models:
|
subgr |
A subgrouping For example, to model counts of several species (
A region |
n_lv |
The number of latent factors to estimate for dynamic
factor models. When |
trend_map |
Optional map of the series onto the latent processes, which fixes some or all loadings of a dynamic factor model. One of three forms:
Its columns set the number of factors, which an |
df |
Degrees of freedom for the latent process innovations.
Defaults to Finite degrees of freedom let the latent process absorb an
occasional large shock while When Three caveats apply:
|
season |
Optional numeric vector of seasonal periods in time
steps, each above 2, such as |
harmonics |
Optional integer vector with the number of trigonometric harmonics of each period, each below half its period. Fewer harmonics give a smoother seasonal shape. Defaults to the most each period allows, up to 10. |
centred |
Logical. Sample the latent states directly rather
than their innovations? Default |
The level shocks take the innovation structure of RW(): cor
correlates them across series, gr and subgr pool their
correlations hierarchically and df gives them a multivariate t.
The slope and seasonal shocks are Gaussian and take the level's
correlation matrix with scales of their own. residual_cor()
reports that one matrix.
The slope starts at a free value, init_slope_trend, damped or not,
as in the damped trends of exponential smoothing. Damping serves a
series that starts with fast growth and slows. The initial slope of
such a series can lie far outside the slope's stationary
distribution. The level starts at its first shock. The observation
intercept carries its mean.
Default priors scale with the number of time points and
with the factor that brms uses to widen its own default
scales, as get_prior() describes:
sigma_trend and sigma_slope_trend take gamma(2, .)
priors. At its prior median, each kind of shock alone moves the
trend by a standard deviation of over the series. The
slope prior allows for damping at the prior median of
ar1_slope_trend. A gamma(2, .) density is zero at zero. It
allows a nearly fixed level or slope and keeps the sampler off
that boundary.
init_slope_trend takes normal(0, 2 / r). Here
is how far a unit
initial slope moves the level by the end of the series. It is
without damping. One prior standard deviation then
gives growth of over the series.
ar1_slope_trend takes beta(18, 2), with median 0.91.
A factor model with every loading sampled measures these scales in
units of , the spread of its level over the series.
Its loadings carry . get_prior() prints the resolved values.
A smooth or linear function of time in either formula competes with
the slope for the same variation. mvgam() warns when the time
variable appears in one. The slope variance is weakly identified on
short series: LLT() warns below 20 time points and refuses fewer
than 5. On informative data, such as large counts, a chain started
at random can stall far from the posterior. init = "pathfinder"
in mvgam() starts every chain from Stan's Pathfinder
approximation.
In a factor model with every loading sampled, the loadings set
each factor's scale. The level shocks take a fixed scale of one.
Every factor keeps its level noise. The factors share one
sigma_slope_trend and one ar1_slope_trend. A rotation of the
factors then leaves the model unchanged. The QR rotation of RW()
factors identifies the loadings. A trend_map that fixes loadings
keeps one slope scale per factor. The factors' shocks are
independent, as cor describes.
Seasonality:
season adds a stochastic season to the level, the
trigonometric form of Harvey (1989) with the non-integer and multiple
periods of De Livera et al. (2011). The latent state is
. Harmonic of period
holds a state pair that turns by at
each step and takes Gaussian shocks of scale sigma_season_trend:
Common periods are 4 for quarterly data, 12 for monthly data, 52.18
for weekly data over years, 7 and 365.25 for daily data and 24 and
168 for hourly data. LLT(season = 12, harmonics = K) fits the
season that AddTrig(period = 12, frequencies = 1:K) specifies in
bsts.
The season is the sum of the first states over the harmonics. A
small sigma_season_trend keeps the seasonal shape nearly fixed. A
zero scale fixes it, as a cyclic smooth does. A larger scale lets
the shape drift. Every harmonic of a process shares one scale.
Each harmonic averages to zero over its period, which separates the
season from the level and the observation intercept. Two periods
sharing a harmonic, such as 6 and 12 with three or more harmonics,
are refused. A period longer than the data overlaps the slope and
draws a warning. The starting pairs init_season_trend are
estimated under one prior for both states of every harmonic. That
prior treats every phase at the first time point alike. Under cor
or gr each harmonic's shocks are correlated across series, as the
level shocks are. Series correlated in their shocks shift their
seasons together. In a factor model each factor has its own season,
mapped to the series through the loadings.
sigma_season_trend takes a gamma(2, .) prior whose median puts
the season's drift over the series at . A season that
drifts by its own size over the series would barely repeat. Each
starting state takes normal(0, s / sqrt(K)) over
harmonics, which gives the starting seasonal pattern a root mean
square of . get_prior() prints the resolved values.
Components:
hindcast.mvgam(), forecast.mvgam() and plot(type = "trend")
report the parts of the trend through component. "level" is the
stochastic level and "slope" its growth per time step. "season"
is the season. "predictor" holds the effects of the trend
formula's covariates. Several names add their components:
component = c("level", "predictor") gives the level with the
covariate effects it moves with. Level, season and predictor sum to
the trend. A factor model reports each component at the series
grain, through its loadings. A rotation of the factors leaves them
unchanged. seasonality() summarises the swing and peak of the
season in each cycle. It also reports how both changed over the
series.
An object of class mvgam_trend.
Harvey, A. C. (1989). Forecasting, Structural Time Series Models and the Kalman Filter. Cambridge University Press.
Gardner, E. S. and McKenzie, E. (1985). Forecasting trends in time series. Management Science, 31:1237-1246.
De Livera, A. M., Hyndman, R. J. and Snyder, R. D. (2011). Forecasting time series with complex seasonal patterns using exponential smoothing. Journal of the American Statistical Association, 106:1513-1527.
RW(), PW(), trend_constructors, get_prior() for the
scale of the default priors, hindcast.mvgam() and
forecast.mvgam() for the level, the slope and the season,
seasonality() for the swing and peak of each seasonal cycle,
series_to_mvgam() for the periods a ts, msts or tsibble
carries
Other trend models:
PW(),
ZMVN(),
list_trend_types(),
lv_axis(),
print.mvgam_trend()
## Not run: # A series that grows fast, then slows: its slope starts at 0.25 # and shrinks by a factor of 0.93 at each step set.seed(2) n_t <- 85 slope <- 0.25 * 0.93^(0:(n_t - 1)) dat <- data.frame( time = 1:n_t, series = factor("s1"), y = rpois(n_t, exp(1 + cumsum(slope) + cumsum(rnorm(n_t, 0, 0.03)))) ) # Fit the first 45 points, while the series is still growing mod <- mvgam( y ~ 1, trend_formula = ~ LLT(damped = TRUE), data = dat[1:45, ], family = poisson(), chains = 2, silent = 2 ) # The posterior for `ar1_slope_trend` covers the simulated 0.93 summary(mod) # The slope decays toward zero over the fitted times and the horizon plot(forecast(mod, newdata = dat[46:85, ], type = "trend", component = "slope")) # On the link scale the damped forecast levels off. An undamped slope # carries the last growth rate forward. plot(forecast(mod, newdata = dat[46:85, ], type = "link")) mod_undamped <- update(mod, trend_formula = ~ LLT()) plot(forecast(mod_undamped, newdata = dat[46:85, ], type = "link")) # Ten years of monthly counts: a slow rise, a seasonal swing that # widens from 0.3 to 0.9 on the log scale and a rainfall effect set.seed(3) n_t <- 120 season <- seq(0.3, 0.9, length.out = n_t) * sin(2 * pi * (1:n_t) / 12) dat_s <- data.frame(time = 1:n_t, series = factor("s1"), rain = rnorm(n_t)) dat_s$y <- rpois(n_t, exp(2.5 + 0.008 * dat_s$time + season + 0.3 * dat_s$rain)) # Two harmonics of a twelve-month season, with rainfall acting on the # latent state. The last year is held out. mod_s <- mvgam( y ~ 1, trend_formula = ~ rain + LLT(season = 12, harmonics = 2), data = dat_s[1:108, ], family = poisson(), chains = 2, silent = 2 ) # A small `sigma_season_trend` lets the seasonal shape drift slowly summary(mod_s) # Simulated counts match the distribution of the observed ones pp_check(mod_s, type = "ecdf_overlay") # The rainfall effect on the expected count conditional_effects(mod_s, type = "expected") # The fitted season widens over the years and carries its shape into # the held-out year fc_s <- forecast(mod_s, newdata = dat_s[109:120, ], type = "trend", component = "season") plot(fc_s) # The swing of each year's season and its peak month. Comparing the # first and last years gives the widening and its probability s <- seasonality(mod_s, newdata = dat_s[109:120, ]) s plot(s) summary(s)$change # Draws of the seasonal shock scale head(as.data.frame(mod_s, variable = "sigma_season_trend")) # Two regions whose levels move together, with shocks correlated at # 0.7. Counts near 20 pin the states down, which the centred form # samples fastest set.seed(4) n_t <- 60 z <- rnorm(n_t) shock <- 0.25 * cbind(z, 0.7 * z + sqrt(1 - 0.7^2) * rnorm(n_t)) dat_r <- data.frame( time = rep(1:n_t, 2), series = factor(rep(c("north", "south"), each = n_t)) ) dat_r$y <- rpois(2 * n_t, exp(3 + c(apply(shock, 2, cumsum)) + 0.5 * sin(2 * pi * dat_r$time / 12))) # `cor = TRUE` correlates the level, slope and seasonal shocks mod_r <- mvgam( y ~ 1, trend_formula = ~ LLT(season = 12, harmonics = 1, cor = TRUE, centred = TRUE), data = dat_r, family = poisson(), chains = 2, silent = 2 ) # The one correlation matrix the three kinds of shock share residual_cor(mod_r) ## End(Not run)## Not run: # A series that grows fast, then slows: its slope starts at 0.25 # and shrinks by a factor of 0.93 at each step set.seed(2) n_t <- 85 slope <- 0.25 * 0.93^(0:(n_t - 1)) dat <- data.frame( time = 1:n_t, series = factor("s1"), y = rpois(n_t, exp(1 + cumsum(slope) + cumsum(rnorm(n_t, 0, 0.03)))) ) # Fit the first 45 points, while the series is still growing mod <- mvgam( y ~ 1, trend_formula = ~ LLT(damped = TRUE), data = dat[1:45, ], family = poisson(), chains = 2, silent = 2 ) # The posterior for `ar1_slope_trend` covers the simulated 0.93 summary(mod) # The slope decays toward zero over the fitted times and the horizon plot(forecast(mod, newdata = dat[46:85, ], type = "trend", component = "slope")) # On the link scale the damped forecast levels off. An undamped slope # carries the last growth rate forward. plot(forecast(mod, newdata = dat[46:85, ], type = "link")) mod_undamped <- update(mod, trend_formula = ~ LLT()) plot(forecast(mod_undamped, newdata = dat[46:85, ], type = "link")) # Ten years of monthly counts: a slow rise, a seasonal swing that # widens from 0.3 to 0.9 on the log scale and a rainfall effect set.seed(3) n_t <- 120 season <- seq(0.3, 0.9, length.out = n_t) * sin(2 * pi * (1:n_t) / 12) dat_s <- data.frame(time = 1:n_t, series = factor("s1"), rain = rnorm(n_t)) dat_s$y <- rpois(n_t, exp(2.5 + 0.008 * dat_s$time + season + 0.3 * dat_s$rain)) # Two harmonics of a twelve-month season, with rainfall acting on the # latent state. The last year is held out. mod_s <- mvgam( y ~ 1, trend_formula = ~ rain + LLT(season = 12, harmonics = 2), data = dat_s[1:108, ], family = poisson(), chains = 2, silent = 2 ) # A small `sigma_season_trend` lets the seasonal shape drift slowly summary(mod_s) # Simulated counts match the distribution of the observed ones pp_check(mod_s, type = "ecdf_overlay") # The rainfall effect on the expected count conditional_effects(mod_s, type = "expected") # The fitted season widens over the years and carries its shape into # the held-out year fc_s <- forecast(mod_s, newdata = dat_s[109:120, ], type = "trend", component = "season") plot(fc_s) # The swing of each year's season and its peak month. Comparing the # first and last years gives the widening and its probability s <- seasonality(mod_s, newdata = dat_s[109:120, ]) s plot(s) summary(s)$change # Draws of the seasonal shock scale head(as.data.frame(mod_s, variable = "sigma_season_trend")) # Two regions whose levels move together, with shocks correlated at # 0.7. Counts near 20 pin the states down, which the centred form # samples fastest set.seed(4) n_t <- 60 z <- rnorm(n_t) shock <- 0.25 * cbind(z, 0.7 * z + sqrt(1 - 0.7^2) * rnorm(n_t)) dat_r <- data.frame( time = rep(1:n_t, 2), series = factor(rep(c("north", "south"), each = n_t)) ) dat_r$y <- rpois(2 * n_t, exp(3 + c(apply(shock, 2, cumsum)) + 0.5 * sin(2 * pi * dat_r$time / 12))) # `cor = TRUE` correlates the level, slope and seasonal shocks mod_r <- mvgam( y ~ 1, trend_formula = ~ LLT(season = 12, harmonics = 1, cor = TRUE, centred = TRUE), data = dat_r, family = poisson(), chains = 2, silent = 2 ) # The one correlation matrix the three kinds of shock share residual_cor(mod_r) ## End(Not run)
The log density of each observation under each posterior draw, as
brms::log_lik.brmsfit() returns it. loo.mvgam(), waic.mvgam(),
lfo_cv.mvgam() and kfold.mvgam() score models from it.
## S3 method for class 'mvgam' log_lik( object, newdata = NULL, re_formula = NULL, resp = NULL, ndraws = NULL, draw_ids = NULL, incl_autocor = TRUE, process_error = NULL, allow_new_levels = FALSE, sample_new_levels = "uncertainty", ... )## S3 method for class 'mvgam' log_lik( object, newdata = NULL, re_formula = NULL, resp = NULL, ndraws = NULL, draw_ids = NULL, incl_autocor = TRUE, process_error = NULL, allow_new_levels = FALSE, sample_new_levels = "uncertainty", ... )
object |
A fitted |
newdata |
Optional data frame holding the response and every
covariate of the model. |
re_formula |
Group-level terms to include: |
resp |
Optional name of one response of a multivariate model. |
ndraws |
Positive integer specifying number of posterior draws to use. NULL (default) uses all available draws. |
draw_ids |
Optional integer vector selecting a subset of posterior
draw indices to use. NULL (default) uses all draws (subject to
|
incl_autocor |
Logical. |
process_error |
Deprecated alias for |
allow_new_levels |
Logical. |
sample_new_levels |
How a new level's coefficients are drawn:
|
... |
Unused. Anything passed here is refused. |
Each family uses the brms parameterisation. For example,
negbinomial() takes a mean and shape, Beta() a mean and precision.
Hurdle and zero-inflated families mix a mass at zero with their base
family. The weights(), cens() and trunc() addition terms change
each row's contribution as they do in the Stan model.
The posterior_epred.mvgam() family of methods uses the covariate
part of the model by default. A covariate effect then has the same
meaning at every time. Those predictions describe no particular
observed series and do not give an ELPD.
A numeric [ndraws, nobs] matrix of log densities. A missing
response gives a column of NA. For a multivariate fit with
resp = NULL, each column sums the densities of the responses
measured in that row, as brms does. An occupancy, N-mixture or
composition family has one density per site, carried on the site's
first row.
loo.mvgam() and waic.mvgam() estimate the ELPD from this
matrix. hindcast.mvgam() returns the latent states it conditions
on. The
forecast evaluation article
compares models by cross-validation.
Other model comparison:
bridge_sampler.mvgam(),
compare_elpds(),
kfold.mvgam(),
lfo_cv.mvgam(),
loo.mvgam(),
loo_compare.mvgam_lfo(),
mvgam_loo_extras,
posterior_average.mvgam(),
waic.mvgam()
## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # One row per draw, one column per observation ll <- log_lik(mod) dim(ll) # Without the latent trend, the densities are far lower. The trend # explains most of the series ll_fixed <- log_lik(mod, incl_autocor = FALSE) c(with_trend = mean(rowSums(ll)), without = mean(rowSums(ll_fixed))) # Next, loo() estimates the ELPD from these densities ## End(Not run)## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # One row per draw, one column per observation ll <- log_lik(mod) dim(ll) # Without the latent trend, the densities are far lower. The trend # explains most of the series ll_fixed <- log_lik(mod, incl_autocor = FALSE) c(with_trend = mean(rowSums(ll)), without = mean(rowSums(ll_fixed))) # Next, loo() estimates the ELPD from these densities ## End(Not run)
The posterior mean of the summed log likelihood, with the df and
nobs attributes that stats::AIC() and stats::BIC() use.
## S3 method for class 'mvgam' logLik(object, pointwise = FALSE, ...)## S3 method for class 'mvgam' logLik(object, pointwise = FALSE, ...)
object |
A fitted |
pointwise |
Logical. |
... |
Further arguments to |
Each latent state counts as a parameter, which makes AIC and BIC
coarse for a state-space model. loo.mvgam() estimates the ELPD
with diagnostics for its reliability.
A logLik object. df counts the parameters variables()
lists. With pointwise = TRUE, the matrix of log_lik.mvgam().
log_lik.mvgam() returns the pointwise matrix.
Ranks two or more lfo_cv() results by their summed ELPD, in the
layout of loo::loo_compare(). The standard error of each
difference comes from the paired per-fold differences with the best
model. The results must share one evaluation grid, with the same
min_t, fc_horizon and data.
## S3 method for class 'mvgam_lfo' loo_compare(x, ..., model_names = NULL)## S3 method for class 'mvgam_lfo' loo_compare(x, ..., model_names = NULL)
x |
An |
... |
Further |
model_names |
Optional character vector of model names, one per forecast. It replaces the names taken from the call. |
A compare.loo table in the layout of loo::loo_compare(),
one row per model, best first.
modelThe model's name.
elpd_diffSummed ELPD difference from the best model, zero for the best.
se_diffStandard error of elpd_diff,
sqrt(N) * sd(fold_diff) over the N folds.
p_worseThe normal probability that the model forecasts
worse than the best one (Sivula et al. 2025). NA for the best
model and for a difference without spread.
diag_diff"N < 100" for fewer than 100 folds, else
"|elpd_diff| < 4" for a difference too small for its SE.
diag_elpdThe number of folds whose PSIS estimate was kept with a Pareto k above the threshold.
elpd_lfoSummed per-fold ELPD.
se_elpd_lfoStandard error of elpd_lfo.
Sivula, T., Magnusson, M., Matamoros, A. A. and Vehtari, A. (2025). Uncertainty in Bayesian leave-one-out cross-validation based model comparison. Bayesian Analysis. doi:10.1214/25-BA1569
lfo_cv(), loo_model_weights.mvgam_lfo(),
compare_elpds(), plot.mvgam_compare_elpds()
Other model comparison:
bridge_sampler.mvgam(),
compare_elpds(),
kfold.mvgam(),
lfo_cv.mvgam(),
log_lik.mvgam(),
loo.mvgam(),
mvgam_loo_extras,
posterior_average.mvgam(),
waic.mvgam()
## Not run: set.seed(1) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) # Two models of one count series: a smooth of x with and without # an AR(1) trend. The trend model samples with smaller steps # (adapt_delta = 0.95). That avoids divergent transitions when # lfo_cv() refits it to shorter stretches of the series mod_gam <- mvgam(y ~ s(x, k = 5), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) mod_ar <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2, control = list(adapt_delta = 0.95)) ## End(Not run) ## Not run: # Each origin after t = 70 forecasts the next time step. The # pointwise log densities feed stacking weights lfo_gam <- lfo_cv(mod_gam, min_t = 70L, save_log_lik = TRUE) lfo_ar <- lfo_cv(mod_ar, min_t = 70L, save_log_lik = TRUE) # The model with the higher summed ELPD comes first loo_compare(lfo_gam, lfo_ar, model_names = c("GAM", "AR")) # Next, compare_elpds() shows where along the series the models # part ways ## End(Not run)## Not run: set.seed(1) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) # Two models of one count series: a smooth of x with and without # an AR(1) trend. The trend model samples with smaller steps # (adapt_delta = 0.95). That avoids divergent transitions when # lfo_cv() refits it to shorter stretches of the series mod_gam <- mvgam(y ~ s(x, k = 5), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) mod_ar <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2, control = list(adapt_delta = 0.95)) ## End(Not run) ## Not run: # Each origin after t = 70 forecasts the next time step. The # pointwise log densities feed stacking weights lfo_gam <- lfo_cv(mod_gam, min_t = 70L, save_log_lik = TRUE) lfo_ar <- lfo_cv(mod_ar, min_t = 70L, save_log_lik = TRUE) # The model with the higher summed ELPD comes first loo_compare(lfo_gam, lfo_ar, model_names = c("GAM", "AR")) # Next, compare_elpds() shows where along the series the models # part ways ## End(Not run)
mvgam_lfo objectsWeights for combining models evaluated by lfo_cv()
on one rolling-origin grid, for example in
ensemble.mvgam_forecast(). Yao et al. (2018) describe both
methods.
"pseudo-BMA": the softmax of each model's summed ELPD.
A gap of more than about 10 ELPD units gives the better model
nearly all the weight.
"stacking": weights that maximise the log score of the
combined predictive over the held-out observations. They
spread weight more evenly. Each result needs the pointwise
matrix that lfo_cv(save_log_lik = TRUE) stores.
## S3 method for class 'mvgam_lfo' loo_model_weights(x, ..., method = "pseudo-BMA", model_names = NULL)## S3 method for class 'mvgam_lfo' loo_model_weights(x, ..., method = "pseudo-BMA", model_names = NULL)
x |
An |
... |
Further |
method |
|
model_names |
Optional character vector of model names, one per forecast. It replaces the names taken from the call. |
A named numeric vector of weights summing to 1, of class
"pseudobma_weights" or "stacking_weights".
Yao, Y., Vehtari, A., Simpson, D., Gelman, A. (2018). Using stacking to average Bayesian predictive distributions. Bayesian Analysis 13(3): 917-1003. doi:10.1214/17-BA1091
loo_compare.mvgam_lfo(), lfo_cv(),
ensemble.mvgam_forecast(), compare_elpds(),
plot.mvgam_compare_elpds()
## Not run: set.seed(2) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) # Two models of one count series: a smooth of x with and without # an AR(1) trend. The trend model samples with smaller steps # (adapt_delta = 0.95). That avoids divergent transitions when # lfo_cv() refits it to shorter stretches of the series mod_gam <- mvgam(y ~ s(x, k = 5), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) mod_ar <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2, control = list(adapt_delta = 0.95)) ## End(Not run) ## Not run: # Each origin after t = 70 forecasts the next time step. The # pointwise log densities feed stacking weights lfo_gam <- lfo_cv(mod_gam, min_t = 70L, save_log_lik = TRUE) lfo_ar <- lfo_cv(mod_ar, min_t = 70L, save_log_lik = TRUE) # Pseudo-BMA weights come from the summed ELPDs loo_model_weights(lfo_gam, lfo_ar, model_names = c("GAM", "AR")) # Stacking weights come from the pointwise log densities w <- loo_model_weights(lfo_gam, lfo_ar, method = "stacking", model_names = c("GAM", "AR")) w # The stacking weights combine the two forecasts fc <- ensemble(forecast(mod_gam, newdata = simdat$data_test), forecast(mod_ar, newdata = simdat$data_test), weights = w) plot(fc) ## End(Not run)## Not run: set.seed(2) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) # Two models of one count series: a smooth of x with and without # an AR(1) trend. The trend model samples with smaller steps # (adapt_delta = 0.95). That avoids divergent transitions when # lfo_cv() refits it to shorter stretches of the series mod_gam <- mvgam(y ~ s(x, k = 5), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) mod_ar <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2, control = list(adapt_delta = 0.95)) ## End(Not run) ## Not run: # Each origin after t = 70 forecasts the next time step. The # pointwise log densities feed stacking weights lfo_gam <- lfo_cv(mod_gam, min_t = 70L, save_log_lik = TRUE) lfo_ar <- lfo_cv(mod_ar, min_t = 70L, save_log_lik = TRUE) # Pseudo-BMA weights come from the summed ELPDs loo_model_weights(lfo_gam, lfo_ar, model_names = c("GAM", "AR")) # Stacking weights come from the pointwise log densities w <- loo_model_weights(lfo_gam, lfo_ar, method = "stacking", model_names = c("GAM", "AR")) w # The stacking weights combine the two forecasts fc <- ensemble(forecast(mod_gam, newdata = simdat$data_test), forecast(mod_ar, newdata = simdat$data_test), weights = w) plot(fc) ## End(Not run)
Estimates the expected log predictive density (ELPD) of each
observation had it been left out of the fit, with loo::loo(). The
ELPD measures how well a model predicts data it has not seen. Higher
is better. Each observation also takes a Pareto diagnostic.
Above 0.7 the approximation is unreliable for that observation.
## S3 method for class 'mvgam' loo( x, ..., compare = TRUE, resp = NULL, pointwise = FALSE, moment_match = FALSE, reloo = FALSE, k_threshold = 0.7, save_psis = FALSE, moment_match_args = list(), reloo_args = list(), model_names = NULL, incl_autocor = TRUE, incl_dynamics = NULL, by_series = FALSE ) ## S3 method for class 'mvgam' loo_compare( x, ..., criterion = c("loo", "waic"), model_names = NULL, incl_autocor = TRUE, incl_dynamics = NULL )## S3 method for class 'mvgam' loo( x, ..., compare = TRUE, resp = NULL, pointwise = FALSE, moment_match = FALSE, reloo = FALSE, k_threshold = 0.7, save_psis = FALSE, moment_match_args = list(), reloo_args = list(), model_names = NULL, incl_autocor = TRUE, incl_dynamics = NULL, by_series = FALSE ) ## S3 method for class 'mvgam' loo_compare( x, ..., criterion = c("loo", "waic"), model_names = NULL, incl_autocor = TRUE, incl_dynamics = NULL )
x |
A fitted |
... |
For |
compare, resp, pointwise, moment_match, reloo, k_threshold, save_psis, moment_match_args, reloo_args
|
The arguments of brms::loo.brmsfit. mvgam uses two of them.
|
model_names |
Character vector of row names for the comparison,
one per model. |
incl_autocor |
Logical, default |
incl_dynamics |
Deprecated alias for |
by_series |
Logical, default |
criterion |
|
Exact leave-one-out cross-validation would refit the model once per
observation. Pareto smoothed importance sampling (PSIS) avoids the
refits. It re-weights the posterior draws of the one fit to
approximate the posterior without each observation (Vehtari et al.
2017). loo::loo() describes the method.
The approximation often fails for a fit with a latent trend. Each
observation strongly informs the state at its own time. Removing it
changes that part of the posterior a great deal. The importance
weights then vary widely. Many observations get a Pareto
above 0.7. The effective number of parameters also climbs
towards the number of observations. Check the Pareto
diagnostics before trusting a comparison.
lfo_cv.mvgam() refits along the time axis and scores each window
against data the model has not seen. forecast.mvgam() with
score.mvgam_forecast() scores a held-out horizon.
For loo.mvgam, an object of class psis_loo (see
loo::loo()). For loo_compare.mvgam, the compare.loo table of
loo::loo_compare(), one row per model, best first. Its p_worse,
diag_diff and diag_elpd columns follow Sivula et al. (2025).
loo() or waic.mvgam(), ranked
with loo_compare.mvgam(). Trust it for a model without a trend,
or once the Pareto diagnostics are low.
lfo_cv.mvgam() on each model, ranked
with loo_compare.mvgam_lfo() and plotted with
compare_elpds().
forecast.mvgam() with
score.mvgam_forecast(), several models at once with
compare_scores().
kfold.mvgam()
with group.
The ELPD is higher for the better model. CRPS, DRPS and the other
scores of score.mvgam_forecast() are lower for the better model.
Nicholas J Clark
Vehtari, A., Gelman, A. and Gabry, J. (2017). Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC. Statistics and Computing, 27:1413-1432. doi:10.1007/s11222-016-9696-4
Burkner, P.-C., Gabry, J. and Vehtari, A. (2020). Approximate leave-future-out cross-validation for Bayesian time series models. Journal of Statistical Computation and Simulation, 90(14):2499-2523. doi:10.1080/00949655.2020.1783262
Sivula, T., Magnusson, M., Matamoros, A. A. and Vehtari, A. (2025). Uncertainty in Bayesian leave-one-out cross-validation based model comparison. Bayesian Analysis. doi:10.1214/25-BA1569
lfo_cv.mvgam() scores forecasts by refitting along the
time axis. kfold.mvgam() runs grouped k-fold cross-validation.
loo_model_weights.mvgam() weights models by their predictions.
The
forecast evaluation article
compares models by approximate and exact cross-validation.
Other model comparison:
bridge_sampler.mvgam(),
compare_elpds(),
kfold.mvgam(),
lfo_cv.mvgam(),
log_lik.mvgam(),
loo_compare.mvgam_lfo(),
mvgam_loo_extras,
posterior_average.mvgam(),
waic.mvgam()
## Not run: # A Poisson GAM without a latent trend. PSIS approximates each # held-out count of such a model well (see Details of ?loo.mvgam) set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = "None") mod <- mvgam(y ~ s(x), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) ## End(Not run) ## Not run: # The same smooth of x replaced by a linear effect mod_lin <- update(mod, formula. = y ~ x) # The ELPD estimate, with Pareto k diagnostics for each observation loo(mod) # The better model comes first, with elpd_diff = 0. The diagnostic # columns say how far the difference can be trusted loo_compare(mod, mod_lin) # Next: lfo_cv() scores each model's forecasts of data it has not # seen ## End(Not run)## Not run: # A Poisson GAM without a latent trend. PSIS approximates each # held-out count of such a model well (see Details of ?loo.mvgam) set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = "None") mod <- mvgam(y ~ s(x), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) ## End(Not run) ## Not run: # The same smooth of x replaced by a linear effect mod_lin <- update(mod, formula. = y ~ x) # The ELPD estimate, with Pareto k diagnostics for each observation loo(mod) # The better model comes first, with elpd_diff = 0. The diagnostic # columns say how far the difference can be trusted loo_compare(mod, mod_lin) # Next: lfo_cv() scores each model's forecasts of data it has not # seen ## End(Not run)
Use lv_axis() in a trend_formula in any position that takes a
factor variable, to give each latent factor its own effect. In a
model with no latent factors it gives each series its own effect.
Use it when a covariate should act differently on different series,
such as temperature raising one species and lowering another.
lv_axis()lv_axis()
For example:
trend_formula = ~ s(elev, by = lv_axis()) + AR(n_lv = 2) trend_formula = ~ temp:lv_axis() + AR(n_lv = 2) trend_formula = ~ (1 + temp | lv_axis()) + AR() trend_formula = ~ s(temp, lv_axis(), bs = "fs") + AR()
With n_lv set on the trend constructor, each factor
k = 1, ..., n_lv takes its own effect. The effect of a covariate
on series s is the sum over factors of the loading Z[s, k] times
the effect on factor k. This is constrained ordination, the model
jsdgam() fits. Every term of such a trend_formula is then
evaluated once per factor and time. Each covariate must take one
value per time.
With no n_lv, each series takes its own effect on the latent
state.
The series column itself is not supported in a trend_formula
term. Write lv_axis() for an effect that differs along the
trend's axis. An effect of the series on the observations belongs
in formula. by = trend is deprecated and is treated as
by = lv_axis().
NULL (invisibly). The function only marks a term in a
formula.
With no latent factors, lv_axis() is each series:
~ x:lv_axis() gives a slope of x per series.
~ lv_axis() gives a level per series.
~ (1 + x | lv_axis()) gives levels and slopes that are
partially pooled across series.
~ s(x, by = lv_axis()) gives a smooth of x per series,
and ~ s(x, lv_axis(), bs = "fs") gives smooths that share a
smoothness penalty.
With n_lv latent factors, each of these is estimated once per
factor. The coefficient of one factor has no scale of its own. The
loadings and the factor effects trade scale. The data identify
their product. conditional_effects.mvgam() and predict.mvgam()
report that product, the effect of the covariate on each series.
conditional_effects.mvgam() draws a panel per series. When every
lv_axis() term is a slope or a level, summary.mvgam() reports the
per-factor coefficients in the basis of the identified loadings
Z_tilde.
jsdgam() fits per-factor effects across species.
conditional_effects.mvgam() plots the effect on each series. The
dynamic factor vignette fits factor
models. The JSDM article fits
per-factor trait and covariate effects.
Other trend models:
LLT(),
PW(),
ZMVN(),
list_trend_types(),
print.mvgam_trend()
# `lv_axis()` marks a term in a formula. Called by itself it # returns NULL. lv_axis() ## Not run: # Proportions in three series whose seasonal effect on the logit # scale differs: 1, 0.5 and -1 set.seed(1) dat <- sim_mvgam(family = Beta(), n_series = 3L, n_timepoints = 60L)$data_train dat$season <- sin(2 * pi * dat$time / 12) dat$y <- plogis(qlogis(dat$y) + c(1, 0.5, -1)[as.integer(dat$series)] * dat$season) # One seasonal slope per series mod <- mvgam( formula = y ~ 1, trend_formula = ~ season:lv_axis() + AR(p = 1), data = dat, family = Beta(), chains = 2, silent = 2 ) summary(mod) conditional_effects(mod) # With two latent factors, each factor takes a seasonal slope. The # loadings carry the two slopes to the three series. The prior # table lists one coefficient per factor. A smooth takes the same # marker: `s(season, by = lv_axis())` get_prior( mvgam_formula(y ~ 1, trend_formula = ~ season:lv_axis() + AR(p = 1, n_lv = 2)), data = dat, family = Beta() ) ## End(Not run)# `lv_axis()` marks a term in a formula. Called by itself it # returns NULL. lv_axis() ## Not run: # Proportions in three series whose seasonal effect on the logit # scale differs: 1, 0.5 and -1 set.seed(1) dat <- sim_mvgam(family = Beta(), n_series = 3L, n_timepoints = 60L)$data_train dat$season <- sin(2 * pi * dat$time / 12) dat$y <- plogis(qlogis(dat$y) + c(1, 0.5, -1)[as.integer(dat$series)] * dat$season) # One seasonal slope per series mod <- mvgam( formula = y ~ 1, trend_formula = ~ season:lv_axis() + AR(p = 1), data = dat, family = Beta(), chains = 2, silent = 2 ) summary(mod) conditional_effects(mod) # With two latent factors, each factor takes a seasonal slope. The # loadings carry the two slopes to the three series. The prior # table lists one coefficient per factor. A smooth takes the same # marker: `s(season, by = lv_axis())` get_prior( mvgam_formula(y ~ 1, trend_formula = ~ season:lv_axis() + AR(p = 1, n_lv = 2)), data = dat, family = Beta() ) ## End(Not run)
Draws any bayesplot MCMC plot of the posterior, as
brms::mcmc_plot() does. Without variable, the plot shows the
parameters pairs.mvgam() shows: the population coefficients, the
trend parameters and the family parameters.
## S3 method for class 'mvgam' mcmc_plot(object, type = "intervals", variable = NULL, regex = FALSE, ...)## S3 method for class 'mvgam' mcmc_plot(object, type = "intervals", variable = NULL, regex = FALSE, ...)
object |
A fitted |
type |
The plot type, the name of a bayesplot |
variable |
Either a keyword shortcut, a character vector of
parameter names, or (when
|
regex |
Logical. When |
... |
Further arguments to the bayesplot function, such as
|
A ggplot object, or a bayesplot_grid for "pairs" and
"combo".
mvgam_draws lists the shortcuts variable accepts, such as
"trend_params". pairs.mvgam() plots the joint posterior. See
the bayesplot MCMC overview.
Other posterior summaries:
VarCorr.mvgam(),
bibtex(),
how_to_cite.mvgam(),
hypothesis.mvgam(),
index-mvgam,
methods_md(),
mvgam_draws,
pairs.mvgam(),
posterior_interval.mvgam(),
ranef.mvgam(),
smooths.mvgam(),
summary.mvgam()
## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # Posterior intervals of the trend parameters mcmc_plot(mod, variable = "trend_params", type = "intervals") # Rank histograms of the same parameters check that the chains mix mcmc_plot(mod, variable = "trend_params", type = "rank_overlay") # Next, pairs() shows how the parameters covary ## End(Not run)## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # Posterior intervals of the trend parameters mcmc_plot(mod, variable = "trend_params", type = "intervals") # Rank histograms of the same parameters check that the chains mix mcmc_plot(mod, variable = "trend_params", type = "rank_overlay") # Next, pairs() shows how the parameters covary ## End(Not run)
Writes the model in mathematical notation for a methods section. The
Data section names the response, the dimensions and the predictors.
The Model section holds the likelihood, the linear predictors and the
latent dynamics in one display equation, with a glossary of every
symbol. The Priors section states every prior the Stan program
applies. The Implementation section gives the call that fits the
model and the software versions the fit recorded. The equations are
LaTeX inside $$ fences, which Quarto, R Markdown and MathJax render.
methods_md(object, file = NULL, implementation = TRUE, ...) ## S3 method for class 'mvgam' methods_md(object, file = NULL, implementation = TRUE, heading_level = 2L, ...)methods_md(object, file = NULL, implementation = TRUE, ...) ## S3 method for class 'mvgam' methods_md(object, file = NULL, implementation = TRUE, heading_level = 2L, ...)
object |
A fitted |
file |
Optional path. The Markdown is written there and returned invisibly. |
implementation |
Logical. |
... |
Unused. Anything passed here is refused. |
heading_level |
Integer Markdown level of the section headings.
The default |
A character string of class mvgam_methods_md, which prints
as its Markdown.
Nicholas J Clark
how_to_cite() writes the matching methods paragraph and
its references. prior_summary() lists the priors as a table.
Other posterior summaries:
VarCorr.mvgam(),
bibtex(),
how_to_cite.mvgam(),
hypothesis.mvgam(),
index-mvgam,
mcmc_plot.mvgam(),
mvgam_draws,
pairs.mvgam(),
posterior_interval.mvgam(),
ranef.mvgam(),
smooths.mvgam(),
summary.mvgam()
## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # The equations, glossary and priors as Markdown md <- methods_md(mod) md # Written to a file, nested under a level-two heading methods_md(mod, file = tempfile(fileext = ".md"), heading_level = 3L) # Next, forecast(mod) predicts the times after the training data ## End(Not run)## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # The equations, glossary and priors as Markdown md <- methods_md(mod) md # Written to a file, nested under a level-two heading methods_md(mod, file = tempfile(fileext = ".md"), heading_level = 3L) # Next, forecast(mod) predicts the times after the training data ## End(Not run)
Returns the model's training data restricted to the response plus
the variables find_predictors() reports. Used by upstream
consumers (insight, marginaleffects::datagrid) when they walk
the model frame to build prediction grids.
## S3 method for class 'mvgam' model.frame(formula, trend_effects = FALSE, ...)## S3 method for class 'mvgam' model.frame(formula, trend_effects = FALSE, ...)
formula |
A fitted |
trend_effects |
Logical; if |
... |
Unused. Anything passed here is refused. |
A data frame.
For counts of several categories made together on each unit, such
as the sequence counts of several taxa in a sample. The data hold
one row per category at each unit. Each unit's vector of K counts
is multinomial with probabilities softmax(mu), where mu holds
the categories' linear predictors. A unit's total is the sum of its
counts and may differ between units.
multi()multi()
jsdgam() fits the family, taking the unit and category columns
and the number of latent factors n_lv. The constraints that
identify the model are those of diri().
A family object to pass to jsdgam() or mvgam().
The softmax is unchanged when the same constant is added to every component. The data then identify neither a shift of the linear predictors that every component shares nor a shift of the loadings that every component shares. mvgam removes both:
The first component is the reference. Its linear predictor
is subtracted from every component's before the softmax, as in
brms's dirichlet() family. A term that acts on every
component alike, such as Intercept or env in
y ~ env * series, then cancels. Its posterior is its prior,
student_t(3, 0, 2.5) by default. The series terms are
contrasts with the first component. jsdgam() warns when the
formula has no term that varies by component.
Each column of the loadings Z sums to zero, through
Stan's sum_to_zero_vector type.
A loadings_prior combines with that constraint.
The density is joint over a unit's components, which makes the unit
the grain of log_lik(), loo() and waic() (Vehtari et al.
2017). log_lik() gives each unit's log density on its first row
and NA on the others. loo() then counts each unit once.
loo_compare() needs every model it compares scored at that grain.
posterior_linpred() gives mu per row before the reference
subtraction. posterior_epred() gives the expected shares, which
sum to one within each unit.
species_effects(), variance_partition() and
forecast_uncertainty(scale = "link") report the predictor centred
across each unit's components, the centred log-ratio scale. A shift
shared by every component then drops out.
Warton, D. I., Blanchet, F. G., O'Hara, R. B., Ovaskainen, O., Taskinen, S., Walker, S. C. and Hui, F. K. C. (2015). So many variables: joint modeling in community ecology. Trends in Ecology and Evolution, 30(12):766-779. doi:10.1016/j.tree.2015.09.007
Other observation families:
beta_nb(),
categ(),
com_binomial(),
diri(),
mvgam_families,
mvn(),
mvt(),
nmix(),
occ(),
tweedie()
## Not run: # Counts of four categories at 60 sites, 30 per site simdat <- sim_jsdgam(family = multi(), n_species = 4L, n_sites = 60L, seed = 3L) fit <- jsdgam( formula = y ~ env * series, factor_formula = ~ -1, data = simdat$data_train, unit = time, species = series, family = multi(), n_lv = 1L, chains = 2L, silent = 2 ) # The probability of each category along the gradient conditional_effects(fit, effects = "env:series") # Next, residual_cor(fit) gives the correlations the factor implies ## End(Not run)## Not run: # Counts of four categories at 60 sites, 30 per site simdat <- sim_jsdgam(family = multi(), n_species = 4L, n_sites = 60L, seed = 3L) fit <- jsdgam( formula = y ~ env * series, factor_formula = ~ -1, data = simdat$data_train, unit = time, species = series, family = multi(), n_lv = 1L, chains = 2L, silent = 2 ) # The probability of each category along the gradient conditional_effects(fit, effects = "env:series") # Next, residual_cor(fit) gives the correlations the factor implies ## End(Not run)
Fits a state-space model in Stan. Each observation follows the
observation family. On the link scale its mean is the sum of the
effects in formula and a latent trend for series
at time . The data never record the trend directly.
trend_formula names how it moves from one time to the next, through
a trend constructor such as AR(). It also takes predictors of the
trend. With an AR(p = 1) trend:
Here is the link, the predictor from formula,
the predictor from trend_formula and
the trend's innovation at each time. The
overview article walks through
a full analysis.
mvgam( formula, trend_formula = NULL, data = NULL, newdata = NULL, loadings_prior = NULL, backend = default_backend(), combine = TRUE, family = gaussian(), threads = NULL, save_pars = brms::save_pars(), run_model = TRUE, ... )mvgam( formula, trend_formula = NULL, data = NULL, newdata = NULL, loadings_prior = NULL, backend = default_backend(), combine = TRUE, family = gaussian(), threads = NULL, save_pars = brms::save_pars(), run_model = TRUE, ... )
formula |
The observation model formula, in brms syntax:
smooths |
trend_formula |
A one-sided formula for the latent process:
a trend constructor such as |
data |
Data frame in long format, one row per series and time.
A model with a trend needs a numeric |
newdata |
Optional held-out |
loadings_prior |
Optional named list giving a structured prior
on the loadings of a factor model, such as species traits or a
phylogeny. Most models leave it |
backend |
|
combine |
Logical. With imputed |
family |
A description of the response distribution and link
function, given as a family function, a call to one or its name.
Supports most brms families, including the ordinal families
( A family written inside a univariate |
threads |
Positive integer number of threads per chain, or
A brms family with a |
save_pars |
A |
run_model |
Logical. |
... |
Further arguments for the model and its sampler.
Five arguments shape the Stan program and reach brms unchanged:
|
An object of class mvgam.
A factor trend loads each series on a few latent factors through the
matrix Z. By default each entry of Z takes an independent
student_t(3, 0, 0.5) prior. The static factors of ZMVN() take
normal(0, 1), as jsdgam() describes. Both scales widen with the
responses' spread on their link scale. loadings_prior replaces the
default with the
structured prior of Heaps and Jermyn (2024). Each column of Z
then follows a multivariate normal whose covariance Phi makes
similar series load alike. Phi is the product of a kernel over
series features and one factor exp(-d / theta) per distance
matrix. The argument requires a trend_formula whose trend has
latent factors.
The list takes these fields:
featuresPer-series features, as a numeric matrix, a data
frame or the name of an element of data2. Numeric, integer and
logical columns are z-scored. An ordered factor is z-scored on
its codes. An unordered factor or character column is one-hot
encoded with every level kept (Heaps and Jermyn 2024, Section
6.2). Each encoded column takes its own length-scale.
distancesPairwise distance matrices, as the names of
elements of data2, a matrix or a named list of matrices. Each is
rescaled to a largest entry of 1.
column_shrinkage"iid", the default, shrinks no column.
"mgp" shrinks later columns more strongly through the
multiplicative gamma process of Bhattacharya and Dunson (2011),
applied to the shared innovation scale. AR(), RW() and
ZMVN() trends accept it. A VAR() trend builds its own
innovation covariance. It takes "iid".
mgp_a1, mgp_a2
The hyperparameters of "mgp", by
default 2 and 4. Heaps and Jermyn used an mgp_a2 of 3 and 6 in
their two applications. A lower mgp_a2 shrinks less, for data
that weakly identify the number of active factors.
Each length-scale takes a lognormal(0, 1) prior. Distances are
rescaled to a largest entry of 1. A length-scale of 1 then gives a
correlation of exp(-1) between the two most distant series. Heaps
and Jermyn used the wider lognormal(0, sqrt(10)). A prior() on
theta_features or theta_dist_<name> replaces the default. They
rescaled a phylogeny to a root-to-tip distance of 1, which gives a
largest pairwise distance of 2. Rescale a distance matrix before
fitting to match their scale.
The prior applies to the sampled columns of Z. The reported
loadings Z_tilde come from a QR rotation of them. Each column of
Z_tilde mixes the sampled columns. shared_variation() and
residual_cor() use Z Z', which the rotation leaves unchanged. The
Identification section of trend_constructors describes the
rotation.
A trend_map with no fixed entries, NULL or a matrix of NA, is
compatible. A trend_map that
fixes any loading is refused. Its free entries take the default
prior of class Z, which the structured prior would duplicate.
The unobserved value
that the trend constructor evolves over time.
The random change the trend takes at each time
step, above. Other texts call it a process
error or a shock. cor = TRUE correlates the innovations of
different series.
The two versions of the trend
a prediction can use. The section 'Which prediction function?'
of predict.mvgam() defines them.
A distribution stating which values of a parameter
are plausible before the data are seen.
get_prior.mvgam_formula() lists the defaults.
One joint sample of every parameter from the posterior distribution. Summaries and predictions average over the draws.
Predictions at the training times and
after them. See hindcast.mvgam() and forecast.mvgam().
A site, or a site in one season, whose true
occupancy or abundance holds across its repeat visits. See
occ() and nmix().
The expected log predictive density scores
predictions of held-out data. Higher is better. A Pareto k
above 0.7 marks an observation whose leave-one-out approximation
is unreliable. See loo.mvgam().
A typical analysis takes these steps:
Check the data with mvgam_data().
Choose a family (mvgam_families) and a trend
(trend_constructors). Inspect the default priors with
get_prior.mvgam_formula().
Fit with mvgam(), then check convergence with
summary.mvgam() and mvgam_diagnostics.
Check the fit against the data with pp_check.mvgam() and
plot(fit, type = "residuals").
Interpret effects with conditional_effects.mvgam().
Forecast with forecast.mvgam(). Compare models with
lfo_cv.mvgam() or loo.mvgam().
Report the model with how_to_cite() and methods_md().
Clark, N. J. and Wells, K. (2023). Dynamic Generalized Additive Models for forecasting discrete ecological time series. Methods in Ecology and Evolution, 14:771-784. doi:10.1111/2041-210X.13974
Burkner, P.-C. (2017). brms: An R package for Bayesian multilevel models using Stan. Journal of Statistical Software, 80(1):1-28. doi:10.18637/jss.v080.i01
Wood, S. N. (2017). Generalized Additive Models: An Introduction with R (2nd edition). Chapman and Hall/CRC.
Heaps, S. E. and Jermyn, I. H. (2024). Structured prior distributions for the covariance matrix in latent factor models. Statistics and Computing, 34:143. doi:10.1007/s11222-024-10454-0
Bhattacharya, A. and Dunson, D. B. (2011). Sparse Bayesian infinite factor models. Biometrika, 98(2):291-306. doi:10.1093/biomet/asr013
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:1. doi:10.1007/s11222-022-10167-2
trend_constructors lists the latent trends.
mvgam_families lists the observation families mvgam adds to
those of brms. how_to_cite() writes a methods paragraph for a
fitted model. methods_md() writes its equations. jsdgam() fits
joint species distribution models. The
overview vignette introduces
the package. The data vignette sets out
the data format. The
forecast evaluation article
scores and compares forecasts. The
multivariate formula article fits
several responses at once. The
integrated distribution model article
ties several observation families to one latent process. The
cheatsheet summarises the main
functions on one page.
Other model fitting:
check_newdata(),
jsdgam(),
mvgam_data(),
mvgam_multiple(),
pivot_detection_array(),
pivot_species_matrix(),
print.mvgam_formula(),
series_to_mvgam(),
stancode.mvgam_formula(),
update.mvgam()
## Not run: # One count series with a smooth effect of a covariate x and an # AR(1) latent trend, split into training and test times set.seed(2) simdat <- sim_mvgam(family = poisson(), n_timepoints = 100L, trend_model = AR(), prop_trend = 0.5) head(simdat$data_train) # The parameters a model takes, with their default priors, before # any fitting. A `prior` argument to mvgam() replaces any of them get_prior( mvgam_formula(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1)), data = simdat$data_train, family = poisson() ) # A smooth of x in the observation model and an AR(1) latent trend. # The test data are stored on the fit for forecasting mod <- mvgam( y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, newdata = simdat$data_test, family = poisson(), chains = 2, silent = 2 ) summary(mod) # Do draws from the model resemble the observed counts? pp_check(mod) # The effect of x on the expected count conditional_effects(mod) # Forecasts of the test times, with the held-out counts overlaid plot(forecast(mod)) # A methods paragraph with its references how_to_cite(mod) # Next: a slope that drifts over time takes `s(time, by = x)` in the # formula. loo() and lfo_cv() compare models. The articles under # 'See Also' fit many series, factor models and VAR trends ## End(Not run)## Not run: # One count series with a smooth effect of a covariate x and an # AR(1) latent trend, split into training and test times set.seed(2) simdat <- sim_mvgam(family = poisson(), n_timepoints = 100L, trend_model = AR(), prop_trend = 0.5) head(simdat$data_train) # The parameters a model takes, with their default priors, before # any fitting. A `prior` argument to mvgam() replaces any of them get_prior( mvgam_formula(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1)), data = simdat$data_train, family = poisson() ) # A smooth of x in the observation model and an AR(1) latent trend. # The test data are stored on the fit for forecasting mod <- mvgam( y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, newdata = simdat$data_test, family = poisson(), chains = 2, silent = 2 ) summary(mod) # Do draws from the model resemble the observed counts? pp_check(mod) # The effect of x on the expected count conditional_effects(mod) # Forecasts of the test times, with the held-out counts overlaid plot(forecast(mod)) # A methods paragraph with its references how_to_cite(mod) # Next: a slope that drifts over time takes `s(time, by = x)` in the # formula. loo() and lfo_cv() compare models. The articles under # 'See Also' fit many series, factor models and VAR trends ## End(Not run)
mvgam
Runs the checks mvgam() applies to its data before compiling a
model. It tests the columns, factor levels, time spacing and
response support of a proposed model. A failure raises the error
mvgam() would raise. An optional plot shows each observed series.
mvgam_data( data, y = NULL, family = gaussian(), formula = NULL, trend_formula = NULL, data2 = NULL, plot = TRUE, newdata = NULL, series = NULL, lines = TRUE, n_bins = NULL, log_scale = FALSE )mvgam_data( data, y = NULL, family = gaussian(), formula = NULL, trend_formula = NULL, data2 = NULL, plot = TRUE, newdata = NULL, series = NULL, lines = TRUE, n_bins = NULL, log_scale = FALSE )
data |
Long-format |
y |
Optional name of the response column. |
family |
A |
formula |
Optional observation formula, as a |
trend_formula |
Optional trend formula (e.g.
|
data2 |
Optional named list of further model data, as passed
to |
plot |
Logical. |
newdata |
Optional held-out data in the long format of
|
series |
Series to plot: |
lines |
Logical. Plot lines (default) or points. |
n_bins |
Optional histogram bin count. |
log_scale |
Logical. Plot the response as |
Invisibly, an mvgam_data list with elements data (the
validated data), family (the resolved family), series_levels
(NULL when the data name no series), n_series, time_range,
n_obs, n_missing (the count of missing responses) and plot
(the ggplot or patchwork object when plot = TRUE, else
NULL). With plot = TRUE the plot is also drawn on the active
device.
Nicholas J Clark
mvgam(), mvgam_formula(), jsdgam(),
sim_mvgam(), sim_closure_unit_data(),
get_prior.mvgam_formula().
Other model fitting:
check_newdata(),
jsdgam(),
mvgam(),
mvgam_multiple(),
pivot_detection_array(),
pivot_species_matrix(),
print.mvgam_formula(),
series_to_mvgam(),
stancode.mvgam_formula(),
update.mvgam()
set.seed(1) simdat <- sim_mvgam(family = poisson(), n_series = 3L, n_timepoints = 60L) # Check the frame for a Poisson trend model and plot every series mvgam_data(simdat$data_train, family = poisson(), trend_formula = ~ AR()) # One series in four panels: time series, histogram, ACF and ECDF. # The test data follow the dashed line. mvgam_data(simdat$data_train, family = poisson(), series = 1L, newdata = simdat$data_test) # A response the family cannot take is refused before any Stan # compile. The error names the column, the values and the support. counts <- simdat$data_train counts$y[3L] <- -1 try(mvgam_data(counts, family = poisson(), plot = FALSE)) # AR() assumes evenly spaced times. CAR() models the gaps. gappy <- simdat$data_train[simdat$data_train$time != 5L, ] try(mvgam_data(gappy, family = poisson(), trend_formula = ~ AR(), plot = FALSE)) mvgam_data(gappy, family = poisson(), trend_formula = ~ CAR(), plot = FALSE)set.seed(1) simdat <- sim_mvgam(family = poisson(), n_series = 3L, n_timepoints = 60L) # Check the frame for a Poisson trend model and plot every series mvgam_data(simdat$data_train, family = poisson(), trend_formula = ~ AR()) # One series in four panels: time series, histogram, ACF and ECDF. # The test data follow the dashed line. mvgam_data(simdat$data_train, family = poisson(), series = 1L, newdata = simdat$data_test) # A response the family cannot take is refused before any Stan # compile. The error names the column, the values and the support. counts <- simdat$data_train counts$y[3L] <- -1 try(mvgam_data(counts, family = poisson(), plot = FALSE)) # AR() assumes evenly spaced times. CAR() models the gaps. gappy <- simdat$data_train[simdat$data_train$time != 5L, ] try(mvgam_data(gappy, family = poisson(), trend_formula = ~ AR(), plot = FALSE)) mvgam_data(gappy, family = poisson(), trend_formula = ~ CAR(), plot = FALSE)
The brms and bayesplot accessors for a fitted model.
fixef() and vcov() summarise the population-level coefficients
of the observation formula, or of the trend formula with
trend_effects = TRUE. coef() gives each level of each grouping
factor its coefficients: the population effect plus that level's
deviation, as brms::coef.brmsfit() does. posterior_summary()
summarises any parameters. rhat() and neff_ratio() report convergence.
nuts_params() and log_posterior() return the sampler's own
quantities.
bayes_R2() is the Bayesian R^2 of Gelman et al. (2019).
ndraws(), nchains(), niterations() and nvariables() count
the posterior.
## S3 method for class 'mvgam' coef(object, summary = TRUE, robust = FALSE, probs = c(0.025, 0.975), ...) ## S3 method for class 'mvgam' nuts_params(object, pars = NULL, ...) ## S3 method for class 'mvgam' log_posterior(object, ...) ## S3 method for class 'mvgam' rhat(x, pars = NULL, ...) ## S3 method for class 'mvgam' neff_ratio(object, pars = NULL, ...) ## S3 method for class 'mvgam' fixef( object, summary = TRUE, robust = FALSE, probs = c(0.025, 0.975), pars = NULL, trend_effects = FALSE, ... ) ## S3 method for class 'mvgam' bayes_R2( object, resp = NULL, summary = TRUE, robust = FALSE, probs = c(0.025, 0.975), by_series = FALSE, ... ) ## S3 method for class 'mvgam' prior_summary(object, ...) ## S3 method for class 'mvgam' ndraws(x, ...) ## S3 method for class 'mvgam' nchains(x, ...) ## S3 method for class 'mvgam' niterations(x, ...) ## S3 method for class 'mvgam' nvariables(x, ...) ## S3 method for class 'mvgam' posterior_summary( x, pars = NULL, variable = NULL, probs = c(0.025, 0.975), robust = FALSE, ... ) ## S3 method for class 'mvgam' getCall(x, ...) ## S3 method for class 'mvgam' vcov(object, correlation = FALSE, pars = NULL, trend_effects = FALSE, ...)## S3 method for class 'mvgam' coef(object, summary = TRUE, robust = FALSE, probs = c(0.025, 0.975), ...) ## S3 method for class 'mvgam' nuts_params(object, pars = NULL, ...) ## S3 method for class 'mvgam' log_posterior(object, ...) ## S3 method for class 'mvgam' rhat(x, pars = NULL, ...) ## S3 method for class 'mvgam' neff_ratio(object, pars = NULL, ...) ## S3 method for class 'mvgam' fixef( object, summary = TRUE, robust = FALSE, probs = c(0.025, 0.975), pars = NULL, trend_effects = FALSE, ... ) ## S3 method for class 'mvgam' bayes_R2( object, resp = NULL, summary = TRUE, robust = FALSE, probs = c(0.025, 0.975), by_series = FALSE, ... ) ## S3 method for class 'mvgam' prior_summary(object, ...) ## S3 method for class 'mvgam' ndraws(x, ...) ## S3 method for class 'mvgam' nchains(x, ...) ## S3 method for class 'mvgam' niterations(x, ...) ## S3 method for class 'mvgam' nvariables(x, ...) ## S3 method for class 'mvgam' posterior_summary( x, pars = NULL, variable = NULL, probs = c(0.025, 0.975), robust = FALSE, ... ) ## S3 method for class 'mvgam' getCall(x, ...) ## S3 method for class 'mvgam' vcov(object, correlation = FALSE, pars = NULL, trend_effects = FALSE, ...)
object, x
|
A fitted |
summary |
Logical. |
robust |
Logical. |
probs |
Numeric vector of the two interval probabilities,
|
... |
Further arguments. |
pars |
Optional character vector of parameter names, or of
sampler parameters such as |
trend_effects |
Logical. |
resp |
Optional name of one response of a multivariate model. |
by_series |
Logical, for |
variable |
Parameter names for |
correlation |
Logical. |
fixef(), posterior_summary() and bayes_R2() return a
matrix with columns Estimate, Est.Error and one per quantile,
or the draws with summary = FALSE. Under by_series = TRUE
bayes_R2() returns a data frame with one row per series and
measure, or draws in columns named <measure>[<series>], such as
AUC[sp1]. coef() returns a named list with one array per
grouping factor: levels, statistics and coefficients, or draws,
levels and coefficients with summary = FALSE. A fit without
group-level effects in its observation formula is refused. A
level's coefficient omits the terms of other covariates that
change it, such as env:size under jsdgam()'s trait_slopes.
species_effects() gives each species' full response.
vcov() returns the covariance matrix of the coefficients.
rhat() and neff_ratio() return a named vector with one value
per parameter. nuts_params() and log_posterior() return the
long data frames of bayesplot. The counting methods return
an integer.
Three checks come before any interpretation of a fit. Vehtari et al. (2021) give the thresholds for the first two.
Every Rhat should be below 1.01. max(rhat(mod)) gives the
largest. A higher value means the chains disagree about the
posterior. Longer chains, such as update(mod, iter = 4000),
often resolve it.
The bulk and tail effective sample sizes should exceed 400.
summary.mvgam() prints them as Bulk_ESS and Tail_ESS.
Longer chains raise them.
There should be no divergent transitions. The fit warns when
there are any. sum(nuts_params(mod, pars = "divergent__")$Value)
counts them. A divergence marks a region of the posterior the
sampler could not explore. Its draws may then be biased. Refit
with smaller sampler steps,
update(mod, control = list(adapt_delta = 0.95)).
Divergences that persist at a higher adapt_delta usually mean the
data cannot separate some of the parameters. A common cause is a
smooth with more flexibility than the series supports, competing
with the trend for the same variation. A smaller basis, such as
s(x, k = 5), or a more informative prior then helps.
Nicholas J Clark
Vehtari, A., Gelman, A., Simpson, D., Carpenter, B. and Burkner, P.-C. (2021). Rank-normalization, folding, and localization: An improved Rhat for assessing convergence of MCMC. Bayesian Analysis, 16(2):667-718. doi:10.1214/20-BA1221
Gelman, A., Goodrich, B., Gabry, J. and Vehtari, A. (2019). R-squared for Bayesian regression models. The American Statistician, 73(3):307-309. doi:10.1080/00031305.2018.1549100
summary.mvgam() prints these summaries for every
parameter. mcmc_plot.mvgam() plots the draws. mvgam_draws
extracts them. loo_R2.mvgam() is the leave-one-out R^2.
Other model checking:
plot.mvgam(),
pp_check.mvgam(),
residuals.mvgam()
## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # The population coefficients with 95% intervals fixef(mod) # Rhat below 1.01 and effective sample ratios above 0.1 suggest the # chains mixed rhat(mod, pars = c("ar1_trend", "sigma_trend")) neff_ratio(mod, pars = c("ar1_trend", "sigma_trend")) # The share of variance in the counts the model explains bayes_R2(mod) # Next, mcmc_plot() draws the posterior of these parameters ## End(Not run)## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # The population coefficients with 95% intervals fixef(mod) # Rhat below 1.01 and effective sample ratios above 0.1 suggest the # chains mixed rhat(mod, pars = c("ar1_trend", "sigma_trend")) neff_ratio(mod, pars = c("ar1_trend", "sigma_trend")) # The share of variance in the counts the model explains bayes_R2(mod) # Next, mcmc_plot() draws the posterior of these parameters ## End(Not run)
Extract posterior draws as a data frame, matrix or array, or as one
of the posterior::draws_* classes. Parameters take their brms
names, such as b_x and sd_grp__Intercept. A trend parameter
indexed by series takes the series name, as in
sigma_trend[series_1]. The
integrated data model article contrasts
intercepts drawn with as_draws_df().
## S3 method for class 'mvgam' as.data.frame( x, row.names = NULL, optional = TRUE, variable = NULL, draw = NULL, regex = FALSE, ... ) ## S3 method for class 'mvgam' as.matrix(x, variable = NULL, draw = NULL, regex = FALSE, ...) ## S3 method for class 'mvgam' as.array(x, variable = NULL, draw = NULL, regex = FALSE, ...) ## S3 method for class 'mvgam' as_draws(x, variable = NULL, regex = FALSE, inc_warmup = FALSE, ...) ## S3 method for class 'mvgam' as_draws_matrix(x, variable = NULL, regex = FALSE, inc_warmup = FALSE, ...) ## S3 method for class 'mvgam' as_draws_df(x, variable = NULL, regex = FALSE, inc_warmup = FALSE, ...) ## S3 method for class 'mvgam' as_draws_array(x, variable = NULL, regex = FALSE, inc_warmup = FALSE, ...) ## S3 method for class 'mvgam' as_draws_list(x, variable = NULL, regex = FALSE, inc_warmup = FALSE, ...) ## S3 method for class 'mvgam' as_draws_rvars(x, variable = NULL, regex = FALSE, inc_warmup = FALSE, ...)## S3 method for class 'mvgam' as.data.frame( x, row.names = NULL, optional = TRUE, variable = NULL, draw = NULL, regex = FALSE, ... ) ## S3 method for class 'mvgam' as.matrix(x, variable = NULL, draw = NULL, regex = FALSE, ...) ## S3 method for class 'mvgam' as.array(x, variable = NULL, draw = NULL, regex = FALSE, ...) ## S3 method for class 'mvgam' as_draws(x, variable = NULL, regex = FALSE, inc_warmup = FALSE, ...) ## S3 method for class 'mvgam' as_draws_matrix(x, variable = NULL, regex = FALSE, inc_warmup = FALSE, ...) ## S3 method for class 'mvgam' as_draws_df(x, variable = NULL, regex = FALSE, inc_warmup = FALSE, ...) ## S3 method for class 'mvgam' as_draws_array(x, variable = NULL, regex = FALSE, inc_warmup = FALSE, ...) ## S3 method for class 'mvgam' as_draws_list(x, variable = NULL, regex = FALSE, inc_warmup = FALSE, ...) ## S3 method for class 'mvgam' as_draws_rvars(x, variable = NULL, regex = FALSE, inc_warmup = FALSE, ...)
x |
A fitted |
row.names, optional
|
Ignored. |
variable |
Either a keyword shortcut, a character vector of
parameter names, or (when
|
draw |
Optional positive integer indices of the draws to keep,
counted across chains. |
regex |
Logical. When |
... |
Unused. Anything passed here is refused. |
inc_warmup |
Logical. Include warmup draws? Defaults to
|
A data.frame, matrix, array, or one of the
posterior::draws_* classes (draws_matrix, draws_array,
draws_df, draws_list, draws_rvars) depending on the method
dispatched.
Nicholas J Clark
mvgam_diagnostics for higher-level summaries derived from
these draws (rhat, neff_ratio, fixef, bayes_R2,
posterior_summary, ...),
variables.mvgam() to list every parameter name in the fit,
mcmc_plot.mvgam() for diagnostic visualisations,
summary.mvgam() for a printed model summary,
tidy.mvgam() for a tibble of parameter summaries,
posterior_epred.mvgam(), posterior_linpred.mvgam(),
posterior_predict.mvgam() for prediction-scale outputs,
posterior::draws for the underlying draws classes.
Other posterior summaries:
VarCorr.mvgam(),
bibtex(),
how_to_cite.mvgam(),
hypothesis.mvgam(),
index-mvgam,
mcmc_plot.mvgam(),
methods_md(),
pairs.mvgam(),
posterior_interval.mvgam(),
ranef.mvgam(),
smooths.mvgam(),
summary.mvgam()
## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # Trend-dynamics parameters as a data frame of draws head(as.data.frame(mod, variable = "trend_params")) # Regular expressions select by pattern, here the smooth's basis # coefficients and its smoothing SD colnames(as.matrix(mod, variable = c("^s_", "^sds_"), regex = TRUE)) # One random variable per parameter, printed as mean and SD as_draws_rvars(mod, variable = "trend_params") # Next, mcmc_plot(mod) plots the same draws ## End(Not run)## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # Trend-dynamics parameters as a data frame of draws head(as.data.frame(mod, variable = "trend_params")) # Regular expressions select by pattern, here the smooth's basis # coefficients and its smoothing SD colnames(as.matrix(mod, variable = c("^s_", "^sds_"), regex = TRUE)) # One random variable per parameter, printed as mean and SD as_draws_rvars(mod, variable = "trend_params") # Next, mcmc_plot(mod) plots the same draws ## End(Not run)
mvgam() and jsdgam() accept the observation families that
brms and stats define. mvgam adds families for
data that ecological and epidemiological series tend to produce.
They cover counts observed with imperfect detection, compositions
and counts whose dispersion a negative binomial cannot reach.
Pass a family as you would to brms::brm() or stats::glm(), for
example mvgam(y ~ x, trend_formula = ~ AR(p = 1), family = nmix()).
The N-mixture article fits nmix().
The JSDM article fits a joint species
distribution model.
Each fixes its link. com_binomial() takes a link argument that
accepts "logit" alone. The table lists every argument.
| Family | Link | Arguments |
tweedie() |
log | M, the truncation point of the
compound Poisson sum |
beta_nb() |
log | none |
com_binomial() |
logit | link, "logit" only |
nmix() |
log (state), logit (detection) | type, one of
"poisson_binomial", "royle_nichols" or
"poisson_poisson"; multi_season |
occ() |
logit (state and detection) | multi_season |
diri() |
softmax over each unit's categories | none |
multi() |
softmax over each unit's categories | none |
categ() |
softmax over each unit's categories | none |
mvn() |
identity | none |
mvt() |
identity | none |
stats::gaussian(), brms::student(),
brms::skew_normal(), brms::exgaussian(),
brms::asym_laplace() and brms::von_mises() for angles.
stats::Gamma(),
brms::lognormal(), brms::exponential(),
brms::weibull(), brms::frechet() and
stats::inverse.gaussian(). tweedie() takes continuous data
with a point mass at zero. With a trend, give these families
link = "log". Their mean must stay positive. Under the
identity, inverse or 1/mu^2 link it stays positive only
where the linear predictor is positive on every row. A latent
trend is centred near zero and takes negative values, where the
likelihood is undefined. stats::Gamma() defaults to the
inverse link. mvgam() warns when a trend meets one of these
links. lognormal() is the exception. Its mu is a log-scale
location that takes any sign. identity is the right link for
it.
(0, 1)
Beta(), with
brms::zero_inflated_beta() or
brms::zero_one_inflated_beta() when the bounds are
attainable.
diri() for
proportions summing to one, multi() for counts across
categories and categ() for one chosen category per unit.
stats::binomial(). brms::beta_binomial() takes overdispersed
trials. com_binomial() takes trials that are under- or
over-dispersed.
stats::poisson(),
brms::negbinomial(), brms::geometric() and their
zero-inflated and hurdle counterparts (see
brms::brmsfamily()). beta_nb() takes tails heavier than a
negative binomial reaches.
nmix() estimates latent
abundance from repeated counts. occ() estimates latent
occupancy from repeated detection histories.
mvn() and mvt(),
whose residual correlations come from a latent factor
structure.
brms::cumulative(), brms::sratio(),
brms::cratio() and brms::acat().
A brms or stats family takes a link argument as
usual. poisson(link = "sqrt") and Gamma(link = "log") both
work. The families mvgam adds each have the one link the table
gives.
nmix() and occ() are closure-unit families. A closure unit is a
site, or a site in one season, whose true occupancy or abundance
holds across its repeat visits. The families expect several rows
per closure unit, one per visit. They model the state and the
detection process with separate linear predictors. bf() supplies
the second, as in bf(y ~ elev, p ~ tod).
sim_closure_unit_data() simulates the layout they take.
pivot_detection_array() reshapes a site-by-visit array into it.
diri(), multi(), categ(), mvn() and mvt() also take
several rows per unit, one per category or response.
A closure-unit family adds predict(type = "latent_state") and
predict(type = "detection"). It supports
pp_check(type = "fit_stat"). It refuses the pp_check() types
that assume one observation per row.
brms::dirichlet(), brms::multinomial() and brms::categorical()
are refused with a pointer to diri(), multi() and categ().
These fit the same responses in mvgam's long-format layout.
brms::logistic_normal() is refused with a pointer to mvn(),
which fits the additive log-ratios of the proportions.
mvgam(), jsdgam(), brms::brmsfamily(),
get_prior(), posterior_predict.mvgam(),
sim_closure_unit_data()
Other observation families:
beta_nb(),
categ(),
com_binomial(),
diri(),
multi(),
mvn(),
mvt(),
nmix(),
occ(),
tweedie()
# Families are constructed, then passed to `family` nmix(type = "royle_nichols") com_binomial() tweedie(M = 40L) # A brms or stats family still takes its own link poisson(link = "sqrt") # The layout occ() takes: one row per visit to each site head(sim_closure_unit_data(family = occ())$data_train) # Next, get_prior() lists the priors a family's parameters take# Families are constructed, then passed to `family` nmix(type = "royle_nichols") com_binomial() tweedie(M = 40L) # A brms or stats family still takes its own link poisson(link = "sqrt") # The layout occ() takes: one row per visit to each site head(sim_closure_unit_data(family = occ())$data_train) # Next, get_prior() lists the priors a family's parameters take
mvgam_fevd object descriptionThe objects returned by fevd(). Run
methods(class = "mvgam_fevd") and
methods(class = "mvgam_fevd_summary") to see an overview of
available methods.
## S3 method for class 'mvgam_fevd' summary(object, probs = c(0.025, 0.975), ...) ## S3 method for class 'mvgam_fevd' plot(x, series = NULL, contributing = NULL, ...)## S3 method for class 'mvgam_fevd' summary(object, probs = c(0.025, 0.975), ...) ## S3 method for class 'mvgam_fevd' plot(x, series = NULL, contributing = NULL, ...)
object |
An |
probs |
The lower and upper percentiles of the interval.
Defaults to |
... |
Unused. Anything passed here is refused. |
x |
An |
series |
Optional positions or names of the target processes drawn as panels. Defaults to every process. |
contributing |
Optional positions or names of the source processes stacked in each panel. Their shares are renormalised to sum to one. Defaults to every process. |
A forecast error variance decomposition quantifies how much
of the forecast uncertainty in one series of a Vector
Autoregression is attributable to each of the others. It is built
from the orthogonalised impulse response coefficient matrices
, which give the contribution of series to the
h-step forecast error variance of series :
Dividing the orthogonalised responses by the forecast error variance
gives the proportion of the forecast error
variance for explained by an exogenous shock to .
These objects hold that proportion.
The orthogonalisation takes the lower Cholesky factor of the innovation covariance. The decomposition then depends on the order of the series. The first series takes all of its own one-step forecast error variance. Each later series shares its one-step variance with the series before it. The order is that of the levels of the series factor.
A decomposition is a K by K matrix per horizon per posterior
draw, which on a wide panel runs to hundreds of megabytes. A reader
needs only a median and an interval from them. fevd() returns
that summary. The two forms have different classes:
mvgam_fevd_summary, the default. A long-format tibble
inheriting from mvgam_var_surface_summary, with one row per
shock-response pair per horizon. shock names the pair as
"<from> -> <to>", taking the model's own series names where
the latent processes are the series and "Process_k" where a
factor VAR's processes are latent factors instead. horizon
counts the steps from the forecast origin. Three columns hold
the posterior median and the interval bounds, named for the
percentiles asked for: fevdQ50, fevdQ2.5 and fevdQ97.5 by
default.
mvgam_fevd, returned under summary = FALSE. A list with
one element per posterior draw, each holding the decomposition
matrices for that draw. Pass it to summary() to reach the form
above.
Both forms take ndraws and draw_ids. A subset of the posterior
computes faster.
summary() turns the draws into the mvgam_fevd_summary above, at
the percentiles probs sets. plot() stacks the median share of
each source in one panel per target, by horizon. A summary plots
through plot.mvgam_var_surface_summary().
Nicholas J Clark
Lutkepohl H (2005). New Introduction to Multiple Time Series Analysis. Springer, Berlin. doi:10.1007/978-3-540-27752-1
mvgam_forecast object descriptionA mvgam_forecast object returned by function hindcast
or forecast. Run
methods(class = "mvgam_forecast") to see an overview of available
methods.
## S3 method for class 'mvgam_forecast' summary(object, probs = c(0.025, 0.975), ...) ## S3 method for class 'mvgam_forecast' print(x, ...)## S3 method for class 'mvgam_forecast' summary(object, probs = c(0.025, 0.975), ...) ## S3 method for class 'mvgam_forecast' print(x, ...)
object |
An |
probs |
The lower and upper quantiles reported with the median.
Defaults to |
... |
Unused. Anything passed here is refused. |
x |
An |
A mvgam_forecast object contains the following elements:
family character description of the observation
distribution.
family_pars list containing draws of family-specific
parameters (e.g. shape, scale, overdispersion). Only returned when
type = "link"; otherwise NULL.
type The type of predictions included
("link", "response", "expected", or "trend").
series_names Factor of series names, taken from
levels(data$series) in the original model fit.
train_observations, train_times Lists of length n_series
holding the training responses and the time of each hindcast
column. A closure-unit family's "expected" and "response"
hindcasts have one column per visit. Their times repeat.
test_observations, test_times If forecast() produced the
object, the corresponding test response vectors and time grids.
NULL otherwise (e.g. from hindcast()).
hindcasts Named list of posterior hindcast draw matrices, one
(ndraws x n_train) matrix per series.
forecasts Named list of posterior forecast draw matrices when
produced by forecast(), otherwise NULL.
site_units TRUE when the fit came from jsdgam(). Its
units are sites, which plot() refuses to draw along a time
axis.
component The state components of the trend the draws hold,
such as "slope", or NULL for the summed trend. Set through
the component argument of hindcast.mvgam() and
forecast.mvgam().
print() gives the family, the number of series, the sizes of the
training and forecast windows and the number of draws. summary()
returns a long tibble with one row per series and time: the median
and the two quantiles of probs, the observed value for
type = "response" and the prediction type. Trend components add a
component column, their names joined by " + ". A multivariate
fit on a long frame adds a leading resp column. plot.mvgam_forecast()
draws the object.
Nicholas J Clark
mvgam, hindcast.mvgam, forecast.mvgam
mvgam_irf object descriptionThe objects returned by irf(). Run methods(class = "mvgam_irf")
and methods(class = "mvgam_irf_summary") to see an overview of
available methods.
## S3 method for class 'mvgam_irf' summary(object, probs = c(0.025, 0.975), ...) ## S3 method for class 'mvgam_irf' plot(x, series = 1, responses = NULL, ...)## S3 method for class 'mvgam_irf' summary(object, probs = c(0.025, 0.975), ...) ## S3 method for class 'mvgam_irf' plot(x, series = 1, responses = NULL, ...)
object |
An |
probs |
The lower and upper percentiles of the interval.
Defaults to |
... |
Unused. Anything passed here is refused. |
x |
An |
series |
Position or name of the process given the shock. |
responses |
Optional positions or names of the processes drawn as response panels. Defaults to every process. |
Generalized or Orthogonalized Impulse Response Functions
are computed from the posterior estimates of Vector Autoregressive
parameters. irf() applies a positive shock of one standard
deviation to one process and calculates how each process in the
latent VAR responds over h horizons, for every process in turn.
Horizon 1 is the time step of the shock. stability() computes
community-level metrics of stability from the same parameters.
A shock response is a K by K matrix per horizon per posterior
draw. On a wide panel the draws run to hundreds of megabytes,
where a median and an interval are what a reader uses. irf()
returns the summary by default. The two forms carry different
classes:
mvgam_irf_summary, the default. A long-format tibble
inheriting from mvgam_var_surface_summary, with one row per
shock-response pair per horizon. shock names the pair as
"<from> -> <to>", taking the model's own series names where
the latent processes are the series and "Process_k" where a
factor VAR's processes are latent factors instead. horizon
counts from 1, the time step of the shock. Three further
columns hold the posterior median and the interval bounds,
named for the percentiles asked for: irfQ50, irfQ2.5 and
irfQ97.5 by default. An
irf_type attribute records whether the responses are
orthogonalised.
mvgam_irf, returned under summary = FALSE. A list with one
element per posterior draw, each itself a list holding one
h by K matrix of responses per shocked process. Pass it to
summary() to reach the form above.
Both forms take ndraws and draw_ids. A subset of the posterior
shortens the computation.
summary() turns the draws into the mvgam_irf_summary above, at
the percentiles probs sets. plot() draws the response of each
process to a shock to series, with its median and interval by
horizon. A summary plots through plot.mvgam_var_surface_summary().
Nicholas J Clark
Pesaran HH and Shin Y (1998). Generalized impulse response analysis in linear multivariate models. Economics Letters 58, 17-29. doi:10.1016/S0165-1765(97)00214-0
The brms methods that take their weights from loo.mvgam().
loo_predict(),
loo_epred() and loo_linpred() reweight posterior predictions by
the PSIS weights of each observation, approximating the prediction
made without it. loo_predictive_interval() gives the
leave-one-out predictive interval. loo_R2() is the Bayesian R^2 of
Gelman et al. (2019) computed from leave-one-out predictions.
add_criterion() stores criteria on the fit. LOO() and WAIC()
are the brms aliases of loo.mvgam() and waic.mvgam().
## S3 method for class 'mvgam' LOO( x, ..., compare = TRUE, resp = NULL, pointwise = FALSE, moment_match = FALSE, reloo = FALSE, k_threshold = 0.7, save_psis = FALSE, moment_match_args = list(), reloo_args = list(), model_names = NULL ) ## S3 method for class 'mvgam' WAIC( x, ..., compare = TRUE, resp = NULL, pointwise = FALSE, model_names = NULL ) ## S3 method for class 'mvgam' loo_R2( object, resp = NULL, summary = TRUE, robust = FALSE, probs = c(0.025, 0.975), seed = NULL, args_epred = list(), args_loglik = list(), ... ) ## S3 method for class 'mvgam' loo_predict( object, type = c("mean", "var", "quantile"), probs = 0.5, psis_object = NULL, resp = NULL, ... ) ## S3 method for class 'mvgam' loo_epred( object, type = c("mean", "var", "quantile"), probs = 0.5, psis_object = NULL, resp = NULL, ... ) ## S3 method for class 'mvgam' loo_linpred( object, type = c("mean", "var", "quantile"), probs = 0.5, psis_object = NULL, resp = NULL, ... ) ## S3 method for class 'mvgam' loo_predictive_interval(object, prob = 0.9, psis_object = NULL, ...) ## S3 method for class 'mvgam' loo_subsample(x, ..., compare = TRUE, resp = NULL, model_names = NULL) ## S3 method for class 'mvgam' loo_moment_match( x, loo = NULL, k_threshold = 0.7, newdata = NULL, resp = NULL, check = TRUE, recompile = FALSE, ... ) ## S3 method for class 'mvgam' loo_model_weights(x, ..., model_names = NULL) ## S3 method for class 'mvgam' add_criterion( x, criterion, model_name = NULL, overwrite = FALSE, file = NULL, force_save = FALSE, ... )## S3 method for class 'mvgam' LOO( x, ..., compare = TRUE, resp = NULL, pointwise = FALSE, moment_match = FALSE, reloo = FALSE, k_threshold = 0.7, save_psis = FALSE, moment_match_args = list(), reloo_args = list(), model_names = NULL ) ## S3 method for class 'mvgam' WAIC( x, ..., compare = TRUE, resp = NULL, pointwise = FALSE, model_names = NULL ) ## S3 method for class 'mvgam' loo_R2( object, resp = NULL, summary = TRUE, robust = FALSE, probs = c(0.025, 0.975), seed = NULL, args_epred = list(), args_loglik = list(), ... ) ## S3 method for class 'mvgam' loo_predict( object, type = c("mean", "var", "quantile"), probs = 0.5, psis_object = NULL, resp = NULL, ... ) ## S3 method for class 'mvgam' loo_epred( object, type = c("mean", "var", "quantile"), probs = 0.5, psis_object = NULL, resp = NULL, ... ) ## S3 method for class 'mvgam' loo_linpred( object, type = c("mean", "var", "quantile"), probs = 0.5, psis_object = NULL, resp = NULL, ... ) ## S3 method for class 'mvgam' loo_predictive_interval(object, prob = 0.9, psis_object = NULL, ...) ## S3 method for class 'mvgam' loo_subsample(x, ..., compare = TRUE, resp = NULL, model_names = NULL) ## S3 method for class 'mvgam' loo_moment_match( x, loo = NULL, k_threshold = 0.7, newdata = NULL, resp = NULL, check = TRUE, recompile = FALSE, ... ) ## S3 method for class 'mvgam' loo_model_weights(x, ..., model_names = NULL) ## S3 method for class 'mvgam' add_criterion( x, criterion, model_name = NULL, overwrite = FALSE, file = NULL, force_save = FALSE, ... )
x, object
|
A fitted |
... |
Further arguments to the method each function calls.
|
compare, pointwise, moment_match, reloo, k_threshold, save_psis, moment_match_args, reloo_args
|
As in |
resp |
Optional name of one response of a multivariate model. |
model_names |
Optional character vector of model names, one per forecast. It replaces the names taken from the call. |
summary |
Logical. |
robust |
Logical. If |
probs |
Numeric vector of probabilities for quantile computation.
Default is |
seed |
Optional integer seed. The session's random state is restored when the call returns. |
args_epred, args_loglik
|
Lists of further arguments to
|
type |
The expectation: |
psis_object |
Optional |
prob |
Interval mass of |
loo, newdata, check, recompile
|
Accepted for the brms signature of
|
criterion |
Character vector of criteria for |
model_name |
Optional name stored in |
overwrite |
Logical. |
file |
Optional path without extension. The fit is saved to
|
force_save |
Unused. Accepted for the brms signature. |
loo_predict(), loo_epred() and loo_linpred() return a
matrix with one row per scored observation and a column per
expectation. loo_predictive_interval() returns its two quantile
columns. loo_R2() returns a one-row summary, or its draws with
summary = FALSE. add_criterion() returns x with the criteria
in x$criteria. loo_model_weights() returns the weights of
loo::loo_model_weights().
The weights and the predictions describe the observation the
likelihood scored. For most families that is a row of the data. The
detection families (occ(), nmix()) write their likelihood per
closure unit, marginalising its visits. loo_predict(),
loo_epred(), loo_predictive_interval() and loo_R2() then sum a
unit's visits and return one value per unit, in the column order of
log_lik.mvgam(). loo_linpred() is refused for them. A sum of
linear predictors over visits has no interpretation.
mvn() and mvt() keep one density per row. The composition
families (diri(), multi(), categ()) hold one joint density per
site. These methods refuse them.
Nicholas J Clark
Gelman, A., Goodrich, B., Gabry, J. and Vehtari, A. (2019). R-squared for Bayesian regression models. The American Statistician, 73(3):307-309. doi:10.1080/00031305.2018.1549100
loo.mvgam() estimates the ELPD these weights come from.
bayes_R2.mvgam() is the in-sample R^2. lfo_cv.mvgam() scores
forecasts of data the model has not seen.
Other model comparison:
bridge_sampler.mvgam(),
compare_elpds(),
kfold.mvgam(),
lfo_cv.mvgam(),
log_lik.mvgam(),
loo.mvgam(),
loo_compare.mvgam_lfo(),
posterior_average.mvgam(),
waic.mvgam()
## Not run: # A Poisson GAM without a latent trend. PSIS approximates each # held-out count of such a model well (see Details of ?loo.mvgam) set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = "None") mod <- mvgam(y ~ s(x), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) ## End(Not run) ## Not run: # The leave-one-out R^2 is lower than the in-sample one loo_R2(mod) bayes_R2(mod) # One PSIS object serves every leave-one-out prediction psis <- loo(mod, save_psis = TRUE)$psis_object head(loo_predict(mod, psis_object = psis)) head(loo_predictive_interval(mod, psis_object = psis)) # Next, loo_compare() ranks models by their ELPD ## End(Not run)## Not run: # A Poisson GAM without a latent trend. PSIS approximates each # held-out count of such a model well (see Details of ?loo.mvgam) set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = "None") mod <- mvgam(y ~ s(x), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) ## End(Not run) ## Not run: # The leave-one-out R^2 is lower than the in-sample one loo_R2(mod) bayes_R2(mod) # One PSIS object serves every leave-one-out prediction psis <- loo(mod, save_psis = TRUE)$psis_object head(loo_predict(mod, psis_object = psis)) head(loo_predictive_interval(mod, psis_object = psis)) # Next, loo_compare() ranks models by their ELPD ## End(Not run)
Fits one model to each of several imputed datasets and pools the
draws, as brms::brm_multiple() does. The pooled posterior holds
the uncertainty the imputations add. mvgam(data = ) takes the
same list and fits the same models.
mvgam_multiple(formula, trend_formula = NULL, data_list, combine = TRUE, ...)mvgam_multiple(formula, trend_formula = NULL, data_list, combine = TRUE, ...)
formula |
The observation model formula, in brms syntax:
smooths |
trend_formula |
A one-sided formula for the latent process:
a trend constructor such as |
data_list |
A list of at least two imputed data frames, or a
|
combine |
Logical. With imputed |
... |
Further arguments to |
The imputations must hold the same columns, of the same classes, in the same order, with the same number of rows. The columns that place each row on the time and series axes must match exactly. Impute only the response and the covariates.
rstan::sflist2stanfit() concatenates the chains of every
imputation fit. The pooled draws then hold both the within- and the
between-imputation variance. Because chains from different
imputations sample different posteriors, the R-hat of the pooled
chains measures disagreement between imputations. summary()
reports each parameter's largest R-hat and summed ESS over the
imputation fits. It also tabulates the convergence of each fit.
With combine = TRUE, a pooled fit of class mvgam_pooled,
which inherits the class of the imputation fits. Its attribute
individual_fits holds those fits. With combine = FALSE, the
list of imputation fits. With run_model = FALSE, one unfitted
model built from the first dataset. Pooling needs draws, which an
unfitted model lacks.
mvgam(), summary.mvgam_pooled()
Other model fitting:
check_newdata(),
jsdgam(),
mvgam(),
mvgam_data(),
pivot_detection_array(),
pivot_species_matrix(),
print.mvgam_formula(),
series_to_mvgam(),
stancode.mvgam_formula(),
update.mvgam()
## Not run: # A covariate with ten missing values, filled three ways. An # imputation model would draw the fills. This example draws them # from a normal distribution. set.seed(1) dat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 60L, trend_model = AR())$data_train missing_x <- sample(nrow(dat), 10L) dat$x[missing_x] <- NA imputed_list <- lapply(1:3, function(i) { filled <- dat filled$x[missing_x] <- rnorm(10L, mean(dat$x, na.rm = TRUE), sd(dat$x, na.rm = TRUE)) filled }) # One fit per imputation, with the posteriors pooled fit_pooled <- mvgam_multiple( formula = y ~ x, trend_formula = ~ AR(p = 1), data_list = imputed_list, family = poisson(), chains = 2, silent = 2 ) # The summary adds the convergence of each imputation fit summary(fit_pooled) # Next, `combine = FALSE` returns the three fits as a list ## End(Not run)## Not run: # A covariate with ten missing values, filled three ways. An # imputation model would draw the fills. This example draws them # from a normal distribution. set.seed(1) dat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 60L, trend_model = AR())$data_train missing_x <- sample(nrow(dat), 10L) dat$x[missing_x] <- NA imputed_list <- lapply(1:3, function(i) { filled <- dat filled$x[missing_x] <- rnorm(10L, mean(dat$x, na.rm = TRUE), sd(dat$x, na.rm = TRUE)) filled }) # One fit per imputation, with the posteriors pooled fit_pooled <- mvgam_multiple( formula = y ~ x, trend_formula = ~ AR(p = 1), data_list = imputed_list, family = poisson(), chains = 2, silent = 2 ) # The summary adds the convergence of each imputation fit summary(fit_pooled) # Next, `combine = FALSE` returns the three fits as a list ## End(Not run)
mvgam_residcor object descriptionA mvgam_residcor object returned by function residual_cor().
Run methods(class = "mvgam_residcor") to see the available
methods.
## S3 method for class 'mvgam_residcor' plot( x, type = c("correlation", "precision"), cluster = FALSE, rescale = FALSE, supported_only = FALSE, ... ) ## S3 method for class 'mvgam_residcor_list' plot( x, include_global = TRUE, ncol = NULL, rescale = FALSE, supported_only = FALSE, ... ) ## S3 method for class 'mvgam_residcor' summary(object, ...) ## S3 method for class 'mvgam_residcor' print(x, digits = 2L, ...)## S3 method for class 'mvgam_residcor' plot( x, type = c("correlation", "precision"), cluster = FALSE, rescale = FALSE, supported_only = FALSE, ... ) ## S3 method for class 'mvgam_residcor_list' plot( x, include_global = TRUE, ncol = NULL, rescale = FALSE, supported_only = FALSE, ... ) ## S3 method for class 'mvgam_residcor' summary(object, ...) ## S3 method for class 'mvgam_residcor' print(x, digits = 2L, ...)
x |
A summarised |
type |
Character. Which matrix to plot. |
cluster |
Logical. |
rescale |
Logical. By default colour spans |
supported_only |
Logical. |
... |
Unused. Anything passed here is refused. |
include_global |
Logical, for an |
ncol |
Optional number of facet columns. Defaults to
|
object |
A summarised |
digits |
Integer number of significant digits. Defaults to 2. |
In a latent factor model the residual covariance between series is
, where holds the factor
loadings and is the covariance of the latent states.
A strong residual correlation between two species can reflect a
species interaction (facilitation or competition), a missing
covariate, or any other association the predictors in formula
leave unexplained (Hui 2016).
The partial correlation between two series conditions on every other series (Ovaskainen et al. 2016). It is computed from the inverse of the correlation matrix, with the diagonal set to 1. Two species with a partial correlation near zero can still be correlated. They are then conditionally independent given the other species. Their association runs through those species. A larger partial correlation suggests a more direct association.
Objects of this class are structured as a list with the
following components:
cor, cor_se, cor_lower, cor_upper
|
Posterior summaries of
the |
cor_ess |
|
prob_positive, prob_negative, prob_nonzero
|
|
sig_cor |
The correlation matrix with every entry set to zero
where |
cov, cov_se, cov_lower, cov_upper, cov_ess
|
Posterior summaries of the residual covariance matrix, with per-entry ESS. |
mean_abs_offdiag |
A |
n_series, series_names
|
Dimensions of the matrix and the series labels. |
pattern, hierarchical, group_label
|
The residual structure that was summarised. |
covariance |
|
probs, prob_threshold
|
The credible interval levels and the
|
Passing partial = TRUE to residual_cor() adds the partial
correlations, with one field for each correlation field: prec,
prec_se, prec_lower, prec_upper, prec_ess,
prec_prob_positive, prec_prob_negative, prec_prob_nonzero
and the thresholded sig_prec. Partial correlations are bounded
like correlations. They are summarised on the same Fisher-z scale.
plot.mvgam_residcor() with type = "precision" requires them.
print() gives the source and kind of covariance, the mean absolute
correlation and the number of pairs whose prob_nonzero exceeds
prob_threshold. summary() returns a tibble with one row per pair
of series, sorted by prob_nonzero: series_1, series_2,
Estimate, Est.Error, Q_lower, Q_upper, ESS, the three sign
probabilities and sig. A low ESS marks a pair the chains sampled
poorly, however tight its interval.
plot() draws the lower triangle of the correlation matrix as a
heatmap of the point estimates. A black outline marks each pair
whose prob_nonzero exceeds prob_threshold, the pairs sig_cor
keeps. The mvgam_residcor_list of residual_cor(by_group = TRUE)
plots one facet per group, on shared colour limits.
Nicholas J Clark
Gruvaeus G and Wainer H (1972). Two additions to hierarchical
cluster analysis. British Journal of Mathematical and Statistical
Psychology, 25, 200-206.
Francis KC Hui (2016). BORAL - Bayesian ordination and regression
analysis of multivariate abundance data in R. Methods in Ecology and
Evolution. 7, 744-750.
Otso Ovaskainen et al. (2016). Using latent variable models to
identify large networks of species-to-species associations at
different spatial scales. Methods in Ecology and Evolution, 7,
549-555.
jsdgam(), residual_cor()
Every figure the package draws uses this theme, including the
figures it draws through bayesplot. It extends
ggplot2::theme_classic(). Apply it to a plot of your own to give it
the look of mvgam output.
mvgam's figures take their colours from the "red" scheme of
bayesplot, which bayesplot::color_scheme_get("red") returns.
The example colours its points with it.
mvgam_theme(base_size = 11, base_family = "")mvgam_theme(base_size = 11, base_family = "")
base_size |
Base font size in points. Defaults to |
base_family |
Base font family. Defaults to |
A ggplot2::theme() object.
Nicholas J Clark
library(ggplot2) ggplot(mtcars, aes(wt, mpg)) + geom_point(colour = bayesplot::color_scheme_get("red")$dark) + mvgam_theme()library(ggplot2) ggplot(mtcars, aes(wt, mpg)) + geom_point(colour = bayesplot::color_scheme_get("red")$dark) + mvgam_theme()
Every trend constructor, AR(), RW(), VAR(), CAR(), PW() and
ZMVN(), returns an object of class mvgam_trend. The object
records the arguments of the call. Model building adds the fields
that need the data.
The trend type, such as "AR". Stan code generation
and the registry look the type up by this name.
The names of the time and series columns,
"time" and "series" unless given.
The names of the grouping and subgrouping
columns of a hierarchical trend, or "NA".
TRUE for a moving-average term.
TRUE for correlated innovations. A grouped trend
always has them.
What the trend assumes about the data.
"requires_regular_intervals" marks a trend that indexes its
lags by position. Fitting it requires evenly spaced times.
CAR() and ZMVN() carry no rule.
The number of latent factors, or NULL for none.
The loadings as supplied to the constructor.
How AR() shares its coefficients across
series.
The degrees of freedom of the innovations: Inf for
Gaussian, NA to estimate them.
The arguments of PW().
TRUE for an LLT() whose slope is damped.
The seasonal periods of an LLT() and
the number of harmonics of each, NULL without a season.
The name of the carrying-capacity column that a
logistic PW() trend uses, "cap" unless given.
The loadings matrix a trend_map gives, with NA
marking a sampled entry. NULL when every loading is sampled.
The structured loadings prior built
from the loadings_prior argument of mvgam().
The series and time axes the data defines.
Which parameters a trend samples depends on its fields at the time
the model is built. A fully fixed trend_map samples no loadings.
A loadings prior with column shrinkage derives the innovation
scale. get_prior() lists the parameters for a given model.
Nicholas J Clark
New to mvgam? Start with mvgam, whose Workflow section lists the steps of an analysis and whose Terms section defines the vocabulary these pages use. mvgam_data checks a data frame before fitting. The overview article walks through a full analysis. The cheatsheet summarises the main functions on one page.
mvgam fits dynamic generalized additive models (GAMs) to one or many time series. Smooth functions of covariates sit beside a latent time-series process that carries the autocorrelation the covariates leave behind. Stan samples the posterior. Every prediction and forecast then carries the uncertainty of every parameter.
The links below lead to questions, blog posts, articles and videos where these models answered a practical problem. They cover counts and other non-Gaussian series, several series modelled together, and predictors such as seasonality that changes over time, monotonic effects and Gaussian processes.
Non-Gaussian time series modelling and forecasting
Counts, proportions and binary outcomes rarely suit a Gaussian model. A latent trend on the link scale handles their autocorrelation.
Uncertain serial autocorrelation in GAM count model residuals
Fitting an autoregressive model and Poisson process interdependently
Visualising autocorrelation in irregularly spaced count data
Video tutorial: Ecological forecasting with Dynamic Generalized Additive Models
Multivariate time series modelling and forecasting
Series measured together, such as several species at one site, can share latent trends or have trends that are correlated.
Ecological modelling: multivariate abundance time-series data
Chains stuck in a local optimum: correlated Poisson distributions
Blog post: Hierarchical distributed lag models in mgcv and mvgam
Article: One shared process, many sensors: multi-response mvgam
Video tutorial: Time series in R and Stan using the mvgam package: hierarchical GAMs
Seasonality and other complex predictors
Cyclic smooths model seasonal patterns. Gaussian processes, monotonic smooths and hierarchical smooths model other nonlinear effects.
Fitting a GAM with double seasonality to a daily time series
Blog post: Incorporating time-varying seasonality in forecast models
Video tutorial: Time series in R and Stan using the mvgam package: an introduction
Nicholas J Clark
mvgam, mvgam_data, trend_constructors, the cheatsheet
mvgam object descriptionA fitted mvgam object returned by function mvgam.
Run methods(class = "mvgam") to see an overview of available methods.
A fit from mvgam() has class c("mvgam", "brmsfit"). The
accessors are the supported way in. variables(), as_draws_df()
and as.data.frame() return the posterior. stancode() and
standata() return the program and its data. prior_summary()
returns the prior table. The elements are listed
below.
The fit and its inputs:
fit The stanfit object with the posterior draws of the
combined observation and trend model
formula The observation formula, as brms validated it
trend_formula The trend formula without its trend constructor.
brms builds the trend submodel from this formula. NULL when no
trend_formula was supplied
trend_call The trend formula as the user wrote it, constructor
included. update() rebuilds the model from it. NULL when no
trend_formula was supplied
family The observation family object
prior A brmsprior table of the priors in the compiled Stan
program
data The observation model frame
test_data The newdata supplied at fitting, or NULL
data.name The deparsed name of the data argument
codegen The knots, sample_prior, drop_unused_levels and
normalize settings the Stan program was generated under.
update() passes them to the refit
silent The verbosity of the call. update() passes it to the
refit
save_pars The brms::save_pars() object the posterior was
saved under
The Stan program:
stancode The combined Stan program as a character string
standata The Stan data list the program was fitted to
The model specification, used by prediction and forecasting:
mv_spec The parsed model specification, including the trend
specifications
trend_metadata The trend type, its lag orders, the number of
latent factors and the record of the model's axes. Prediction,
forecasting and plotting use axes for the series and times the
model was fitted on:
axes$series$levels The series, in the order of the trend
matrix columns. Summaries, plots and forecasts label series
with these
axes$series$source How mvgam built the series: explicit
from a series column, hierarchical from gr and subgr,
or multivariate from the responses of a wide formula
axes$series$n The number of series, equal to
N_series_trend in the Stan data
axes$series$groups The group of each series, in the same
order. NULL for a trend without gr
axes$series$last_time The last time each series was
observed, in the same order. A forecast for a series starts
after this time. A CAR() forecast starts after the last
fitted time for every series
axes$time$values The ordered times the model was fitted on,
in their original units. CAR() and Gaussian process terms
compute their time gaps from these
axes$time$n The number of time points
axes$time$step The spacing between time points, or NA for
irregular times. forecast() extends the time grid by this
step
axes$time$observation_gap The median gap between two
consecutive observations of one series. CAR() measures its
time gaps in this unit
axes$factor$n_lv The number of latent factors, equal to the
number of columns of the loadings and of lv_trend
axes$grain lv when a by = lv_axis() term puts the trend
design on the factor axis, otherwise series
axes$vars The column names for time, series, gr and
subgr: time_var, series_var, gr_var and subgr_var
axes$group_levels The training levels of the gr and
subgr columns. Prediction refuses new data with any other
level
trend_metadata is NULL for a model without a trend whose
data lack a time column or a series column.
obs_model A brmsfit of the observation model. Prediction at
new data builds design matrices from it
trend_model A brmsfit of the trend submodel, used the same
way. NULL when no trend_formula was supplied
How it was fitted:
backend Character, either rstan or cmdstanr
algorithm Character, one of sampling, laplace,
pathfinder, meanfield or fullrank
init The initial-value specification as supplied
("random", "0", "pathfinder", or a numeric value, list or
function)
criteria A named list of model-fit criteria that
add_criterion() has computed, empty on a new fit
call The matched call
brms_version, mvgam_version The package versions the model
was fitted under
stan_version The version of Stan the backend compiled with,
NA under the "mock" backend
creation_time A POSIXct timestamp
A fit from jsdgam() has class c("mvgam", "jsdgam", "brmsfit")
and one further element. Its data carries time and series
columns copied from the unit and species columns:
jsdgam_args The arguments of the jsdgam() call, with unit
and species as column names. update() refits through
jsdgam() with them. Prediction accepts a frame naming the
unit and species columns alone
Nicholas J Clark
For continuous responses measured together on each unit, such as the
biomass of several species at a site. The data hold one row per
response component at each unit. Latent factors shared by a unit's
components give their residuals the covariance
Z Z' + diag(Psi^2), where Z holds the factor loadings and Psi
each component's residual standard deviation (Hui et al. 2015; Niku
et al. 2019). Given the factors, each row is normal with mean mu
and standard deviation Psi.
mvn()mvn()
jsdgam() fits the family, taking the unit and component columns
and the number of factors n_lv. residual_cor() summarises the
residual correlations and shared_variation() the part the factors
share. Psi takes the prior inv_gamma(3, 1.07), with median
0.40 and no mass at zero, which suits responses near unit scale.
prior(..., class = Psi) sets another.
With K components the data separate the factor part from the
residual part only when (K - n_lv)^2 >= K + n_lv. Fewer factors or
more components meet the bound. jsdgam() warns when it fails.
A family object to pass to jsdgam() or mvgam().
Hui, F. K. C., Taskinen, S., Pledger, S., Foster, S. D. and Warton, D. I. (2015). Model-based approaches to unconstrained ordination. Methods in Ecology and Evolution, 6(4):399-411. doi:10.1111/2041-210X.12236
Niku, J., Brooks, W., Herliansyah, R., Hui, F. K. C., Taskinen, S. and Warton, D. I. (2019). Efficient estimation of generalized linear latent variable models. PLOS ONE, 14(5):e0216129. doi:10.1371/journal.pone.0216129
Heaps, S. E. and Jermyn, I. H. (2024). Structured prior distributions for the covariance matrix in latent factor models. Statistics and Computing, 34:143. doi:10.1007/s11222-024-10454-0
Other observation families:
beta_nb(),
categ(),
com_binomial(),
diri(),
multi(),
mvgam_families,
mvt(),
nmix(),
occ(),
tweedie()
## Not run: # Five species at 80 sites whose residuals share two latent # factors simdat <- sim_jsdgam(family = mvn(), n_species = 5L, n_sites = 80L, n_lv = 2L, seed = 1L) fit <- jsdgam( formula = y ~ env * series, factor_formula = ~ -1, data = simdat$data_train, unit = time, species = series, family = mvn(), n_lv = 2L, chains = 2L, silent = 2 ) summary(fit) # The species-by-species residual correlations, against the values # the simulation used round(residual_cor(fit)$cor, 2) round(simdat$truth$residual_cor, 2) # Next, shared_variation(fit) gives the part the factors share ## End(Not run)## Not run: # Five species at 80 sites whose residuals share two latent # factors simdat <- sim_jsdgam(family = mvn(), n_species = 5L, n_sites = 80L, n_lv = 2L, seed = 1L) fit <- jsdgam( formula = y ~ env * series, factor_formula = ~ -1, data = simdat$data_train, unit = time, species = series, family = mvn(), n_lv = 2L, chains = 2L, silent = 2 ) summary(fit) # The species-by-species residual correlations, against the values # the simulation used round(residual_cor(fit)$cor, 2) round(simdat$truth$residual_cor, 2) # Next, shared_variation(fit) gives the part the factors share ## End(Not run)
mvn() with heavy-tailed residuals. Given the latent factors, each
row follows a Student-t distribution with location mu, scale Psi
and degrees of freedom nu, which every component shares. An outlying
row then pulls less on the fit. The residual covariance is
Z Z' + diag(Psi^2 * nu / (nu - 2)). A unit's responses do not
follow a multivariate Student-t law. Their factors stay normal.
mvt()mvt()
nu is bounded below by 2, which keeps the residual variance finite.
Its prior is gamma(2, 0.1), as brms gives a Student-t nu. Above
the bound it places the median of nu at 17 and 95% of its mass
between 3.2 and 56. prior(..., class = nu) and
prior(..., class = Psi) set other priors. The data layout, the fit
and the bound on n_lv follow mvn().
A family object to pass to jsdgam() or mvgam().
Hui, F. K. C., Taskinen, S., Pledger, S., Foster, S. D. and Warton, D. I. (2015). Model-based approaches to unconstrained ordination. Methods in Ecology and Evolution, 6(4):399-411. doi:10.1111/2041-210X.12236
Other observation families:
beta_nb(),
categ(),
com_binomial(),
diri(),
multi(),
mvgam_families,
mvn(),
nmix(),
occ(),
tweedie()
## Not run: simdat <- sim_jsdgam(family = mvt(), n_species = 5L, n_sites = 80L, n_lv = 2L, seed = 1L) fit <- jsdgam( formula = y ~ env * series, factor_formula = ~ -1, data = simdat$data_train, unit = time, species = series, family = mvt(), n_lv = 2L, chains = 2L, silent = 2 ) # The degrees of freedom, against 5 in the simulation posterior_summary(fit, variable = "nu") ## End(Not run)## Not run: simdat <- sim_jsdgam(family = mvt(), n_species = 5L, n_sites = 80L, n_lv = 2L, seed = 1L) fit <- jsdgam( formula = y ~ env * series, factor_formula = ~ -1, data = simdat$data_train, unit = time, species = series, family = mvt(), n_lv = 2L, chains = 2L, silent = 2 ) # The degrees of freedom, against 5 in the simulation posterior_summary(fit, variable = "nu") ## End(Not run)
The number of levels of each grouping factor of the observation
formula, as brms::ngrps.brmsfit() gives it.
## S3 method for class 'mvgam' ngrps(object, ...)## S3 method for class 'mvgam' ngrps(object, ...)
object |
A fitted |
... |
Unused. Anything passed here is refused. |
A named list of integers, one per grouping factor, or
NULL for a model without group-level effects.
Nicholas J Clark
brms::ngrps.brmsfit(), ranef.mvgam(),
VarCorr.mvgam().
For counts made on repeated visits to sites whose abundance stays
fixed across the visits, such as bird point counts within a season.
The data hold one row per visit. The visits sharing a series and a
time belong to one closure unit, whose latent abundance N is
Poisson with mean mu. Each visit's count depends on N and the
detection parameter p. The likelihood sums over N from the
unit's largest count up to the cap K_max (Royle 2004).
nmix( type = c("poisson_binomial", "royle_nichols", "poisson_poisson"), multi_season = FALSE )nmix( type = c("poisson_binomial", "royle_nichols", "poisson_poisson"), multi_season = FALSE )
type |
The variant, |
multi_season |
Logical. |
bf(y ~ elev, p ~ tod) models abundance and detection, each with
its own formula. mu takes the log link. predict() with
type = "latent_state" gives the expected abundance of each unit
given its counts. type = "detection" gives the detection
probability of each visit.
A family object to pass to mvgam() or jsdgam().
All three variants take N ~ Poisson(mu) and differ in what a visit
records.
"poisson_binomial" (Royle 2004)Counts
y ~ Binomial(N, p), which never exceed N. Point counts,
removal passes and plot tallies fit this design. p is the
detection probability of each individual, on the logit link.
"royle_nichols" (Royle and Nichols 2003)Detections
y ~ Bernoulli(1 - (1 - p)^N) in 0 / 1. Camera-trap or eDNA
detections scored as present or absent fit this design. p is
the detection probability of each individual, on the logit
link. A visit's detection probability rises with N.
"poisson_poisson" (Neyman 1939)Counts
y ~ Poisson(N * p), which can exceed N. Camera-trap events
and acoustic detections, where one individual is recorded
several times, fit this design. p is the encounter rate of
each individual per visit, on the log link.
A detection probability p on the logit link takes beta(1, 1) as
a scalar. With a formula, its intercept takes normal(0, 1.5),
which puts most of the probability between 0.05 and 0.95. The
encounter rate of "poisson_poisson" takes lognormal(0, 1) as a
scalar. With a formula, its intercept takes std_normal(). Either
puts most of the rate between 0.14 and 7.4 encounters per visit.
get_prior() lists these defaults. prior(..., dpar = "p")
replaces one. A rare species might take
prior(normal(-2, 0.5), class = Intercept, dpar = "p").
The counts identify abundance and detection apart through repeated
visits and through covariates that act on one of them. With one
visit per unit and no covariate, the data identify only the product
mu * p. nmix() refuses that model. More than 30% of units
visited once raises a warning. A "poisson_poisson" model with
intercepts alone separates mu from p only through the extra
variance of its counts. It warns. An informative prior on one
intercept separates them.
Overdispersed abundance, such as negative binomial counts fitted by
a Poisson N, biases abundance up and detection down, leaving their
product close to the truth (Knape et al. 2018). pp_check() with
type = "fit_stat" tests the per-unit totals for such misfit.
A cap column, constant within each unit and at least its largest
count, sets the cap K_max. Without one, "poisson_binomial" and
"poisson_poisson" take each unit's largest count plus 100, as
unmarked::pcount() does. "royle_nichols" takes a fixed 25, as
unmarked::occuRN() does. Its 0 / 1 detections carry no count to
build a cap from.
A lower cap shortens the sum and speeds sampling. A cap that binds
biases abundance down. latent_N_saturation() reports, for each
unit, the posterior probability that N equals its cap. A
prediction frame may carry its own cap.
jsdgam() with nmix() or occ() fits several species at once.
Latent factors shared by the species enter the state mu. p
keeps its own formula. factor_formula = ~ s(env, by = lv_axis())
lets each factor follow an environmental gradient.
Detection histories from unmarked, spOccupancy or
ubms come as a site-by-visit matrix, an array with species or
seasons as further dimensions, or a list of matrices.
pivot_detection_array() converts any of these to the long format,
broadcasting site, season and visit covariates to their rows.
The density sums over units through Stan's reduce_sum(). Fitting
with threads = 2 or more splits the units across threads.
Royle, J. A. (2004). N-mixture models for estimating population size from spatially replicated counts. Biometrics, 60, 108-115. doi:10.1111/j.0006-341X.2004.00142.x
Royle, J. A. and Nichols, J. D. (2003). Estimating abundance from repeated presence-absence data or point counts. Ecology, 84, 777-790. doi:10.1890/0012-9658(2003)084[0777:EAFRPA]2.0.CO;2
Neyman, J. (1939). On a new class of "contagious" distributions, applicable in entomology and bacteriology. Annals of Mathematical Statistics, 10, 35-57. doi:10.1214/aoms/1177732245
Knape, J., Arlt, D., Barraquand, F., Berg, A., Chevalier, M., Part, T., Ruete, A. and Zmihorski, M. (2018). Sensitivity of binomial N-mixture models to overdispersion. Methods in Ecology and Evolution, 9, 2102-2114. doi:10.1111/2041-210X.13062
occ() for the related joint-occupancy family and
pp_check.mvgam() for closure-unit goodness-of-fit checks. The
N-mixture article fits N-mixture and
occupancy models from data preparation to inference. The
data article sets out the row layout
that nmix() expects.
Other observation families:
beta_nb(),
categ(),
com_binomial(),
diri(),
multi(),
mvgam_families,
mvn(),
mvt(),
occ(),
tweedie()
## Not run: # Counts at 50 sites, each visited four times. The state `mu` is # the expected abundance and `p` the detection probability. set.seed(5) simdat <- sim_closure_unit_data(family = nmix(), n_species = 1L, n_sites = 50L, n_visits = 4L, type = 1L) mod <- mvgam( bf(y ~ env, p ~ tod_c), data = simdat$data_train, family = nmix(), chains = 2, silent = 2 ) summary(mod) # Abundance and detection, separated by the model head(predict(mod, type = "latent_state")) head(predict(mod, type = "detection")) plot(hindcast(mod, type = "latent_state")) # A goodness-of-fit test on the per-site totals. A Bayesian p-value # near 0 or 1 marks a misfit. pp_check(mod, type = "fit_stat", stat = "freeman_tukey", ndraws = 200L) ## End(Not run)## Not run: # Counts at 50 sites, each visited four times. The state `mu` is # the expected abundance and `p` the detection probability. set.seed(5) simdat <- sim_closure_unit_data(family = nmix(), n_species = 1L, n_sites = 50L, n_visits = 4L, type = 1L) mod <- mvgam( bf(y ~ env, p ~ tod_c), data = simdat$data_train, family = nmix(), chains = 2, silent = 2 ) summary(mod) # Abundance and detection, separated by the model head(predict(mod, type = "latent_state")) head(predict(mod, type = "detection")) plot(hindcast(mod, type = "latent_state")) # A goodness-of-fit test on the per-site totals. A Bayesian p-value # near 0 or 1 marks a misfit. pp_check(mod, type = "fit_stat", stat = "freeman_tukey", ndraws = 200L) ## End(Not run)
Extract number of observations from mvgam object
## S3 method for class 'mvgam' nobs(object, ...)## S3 method for class 'mvgam' nobs(object, ...)
object |
mvgam object |
... |
Unused. Anything passed here is refused. |
Integer count of the rows the model was given, matching
nrow(model.frame(object)). A frame mvgam fits is rectangular,
so an unobserved cell is part of the design and is counted.
For detections recorded on repeated visits to sites whose occupancy
stays fixed across the visits, such as camera-trap or call surveys
within a season. The data hold one row per visit with a 0 / 1
response. The visits sharing a series and a time belong to one
closure unit, which is occupied with probability mu. A visit to an
occupied unit detects the species with probability p. The
likelihood sums over the unit's two states. A unit with a detection
is occupied for certain (MacKenzie et al. 2002).
occ(multi_season = FALSE)occ(multi_season = FALSE)
multi_season |
Logical. |
bf(y ~ elev, p ~ tod) models occupancy and detection, each with
its own formula on the logit link. predict() with
type = "latent_state" gives the probability that each unit is
occupied given its detections. type = "detection" gives the
detection probability of each visit. The data need no cap column.
A family object to pass to mvgam() or jsdgam().
The occupancy intercept takes brms's student_t(3, 0, 2.5) on the
logit scale. A scalar p takes beta(1, 1). With a formula, its
intercept takes normal(0, 1.5). get_prior() lists the defaults,
and prior(..., dpar = "p") replaces one.
The detections identify occupancy and detection apart through
repeated visits and through covariates that act on one of them.
With one visit per unit and no covariate, the data identify only
the product mu * p. Only the priors then set the two apart (Royle
and Dorazio 2008). mvgam() warns on such data. It also warns when
more than 30% of units have a single visit.
jsdgam() with nmix() or occ() fits several species at once.
Latent factors shared by the species enter the state mu. p
keeps its own formula. factor_formula = ~ s(env, by = lv_axis())
lets each factor follow an environmental gradient.
Detection histories from unmarked, spOccupancy or
ubms come as a site-by-visit matrix, an array with species or
seasons as further dimensions, or a list of matrices.
pivot_detection_array() converts any of these to the long format,
broadcasting site, season and visit covariates to their rows.
The density sums over units through Stan's reduce_sum(). Fitting
with threads = 2 or more splits the units across threads.
MacKenzie, D. I., Nichols, J. D., Lachman, G. B., Droege, S., Royle, J. A. and Langtimm, C. A. (2002). Estimating site occupancy rates when detection probabilities are less than one. Ecology, 83, 2248-2255. doi:10.1890/0012-9658(2002)083[2248:ESORWD]2.0.CO;2
Royle, J. A. and Dorazio, R. M. (2008). Hierarchical Modeling and Inference in Ecology. Academic Press.
nmix() for the related N-mixture family and
pp_check.mvgam() for closure-unit goodness-of-fit checks. The
N-mixture article fits occupancy and
N-mixture models from data preparation to inference. The
data article sets out the row layout
that occ() expects.
Other observation families:
beta_nb(),
categ(),
com_binomial(),
diri(),
multi(),
mvgam_families,
mvn(),
mvt(),
nmix(),
tweedie()
## Not run: # Detections at 50 sites, each visited four times, with covariates # on occupancy and on detection set.seed(6) simdat <- sim_closure_unit_data(family = occ(), n_species = 1L, n_sites = 50L, n_visits = 4L, type = 1L) mod <- mvgam( bf(y ~ env, p ~ tod_c), data = simdat$data_train, family = occ(), chains = 2, silent = 2 ) summary(mod) # Occupancy along the gradient and detection through the day conditional_effects(mod, effects = "env", type = "latent_state") conditional_effects(mod, effects = "tod_c", type = "detection") # Occupancy and detection, separated by the model head(predict(mod, type = "latent_state")) head(predict(mod, type = "detection")) # Next, pp_check(mod, type = "fit_stat") tests the fit of each unit ## End(Not run)## Not run: # Detections at 50 sites, each visited four times, with covariates # on occupancy and on detection set.seed(6) simdat <- sim_closure_unit_data(family = occ(), n_species = 1L, n_sites = 50L, n_visits = 4L, type = 1L) mod <- mvgam( bf(y ~ env, p ~ tod_c), data = simdat$data_train, family = occ(), chains = 2, silent = 2 ) summary(mod) # Occupancy along the gradient and detection through the day conditional_effects(mod, effects = "env", type = "latent_state") conditional_effects(mod, effects = "tod_c", type = "detection") # Occupancy and detection, separated by the model head(predict(mod, type = "latent_state")) head(predict(mod, type = "detection")) # Next, pp_check(mod, type = "fit_stat") tests the fit of each unit ## End(Not run)
Plots the site scores and series loadings of a factor model on two
axes. Sites are the points on the fit's unit or time axis, labelled
by their values. Series, such as the species of a jsdgam() fit,
are arrows from the origin. Series that point the same way share
their residual variation. Arrows are tapered when ggarrow and
ggpp are installed.
ordinate(object, ...) ## S3 method for class 'mvgam' ordinate( object, which_lvs = c(1L, 2L), biplot = TRUE, alpha = 0.5, rotation = c("svd", "varimax", "promax", "none"), label_sites = TRUE, label_species = c("longest", "all", "none"), traits = NULL, trait_arrow_scale = 1, ... )ordinate(object, ...) ## S3 method for class 'mvgam' ordinate( object, which_lvs = c(1L, 2L), biplot = TRUE, alpha = 0.5, rotation = c("svd", "varimax", "promax", "none"), label_sites = TRUE, label_species = c("longest", "all", "none"), traits = NULL, trait_arrow_scale = 1, ... )
object |
A fitted |
... |
Unused. Anything passed here is refused. |
which_lvs |
Two distinct integers: the axes to plot |
biplot |
Logical. |
alpha |
Number in |
rotation |
The basis of the axes:
Varimax and promax axes carry no variance order. Any two of them
make a valid |
label_sites |
Logical. |
label_species |
The series arrows to label. |
traits |
|
trait_arrow_scale |
Positive number. The longest trait arrow is
|
The plot starts from the posterior medians of the identified factors
and loadings. Factors with shared dynamics are identified by a
rotation to lower-triangular loadings, Z_tilde and
lv_trend_tilde (Heaps and Jermyn 2024). Factors with their own
dynamics are identified by an ordering and orientation of Z and
lv_trend. The Identification section of trend_constructors
describes both. Every rotation keeps the product LV %*% t(Z) the
model fitted.
The medians carry no posterior uncertainty into the plot. Axis signs
are arbitrary. Two fits may need an axis flipped before they agree.
compare_loadings() aligns the loadings of two fits.
A trend_map supplies the loadings as data. A rotation other than
"none" replaces them and warns on every call.
plot(object, type = "factors") shows the loadings the map declared.
A ggplot object. attr(p, "rotation") holds the rotated
scores and loadings, the rotation matrix rotmat (NULL for
"svd" and "none"), the method and n_lv.
Nicholas J Clark
Hui, F. K. C. (2016). boral: Bayesian ordination and regression analysis of multivariate abundance data in R. Methods in Ecology and Evolution, 7, 744-750. doi:10.1111/2041-210X.12514
Heaps, S. E. and Jermyn, I. H. (2024). Structured prior distributions for the covariance matrix in latent factor models. Statistics and Computing, 34, 143. doi:10.1007/s11222-024-10454-0
plot.mvgam() with type = "factors" plots each factor's
path. residual_cor() gives the correlations among series the
factors imply. community() gives how often species occur together.
The
JSDM article interprets a biplot
of species loadings.
Other latent dynamics:
active_factors(),
compare_loadings(),
fevd.mvgam(),
irf.mvgam(),
posterior_transition_matrix(),
residual_cor(),
shared_variation(),
stability.mvgam()
## Not run: # Presence and absence of 10 species at 60 sites, driven by two # latent factors simdat <- sim_jsdgam(family = bernoulli(), n_species = 10L, n_sites = 60L, n_lv = 2L, seed = 3L) mod <- jsdgam(y ~ env * series, data = simdat$data_train, family = bernoulli(), n_lv = 2L, chains = 2, silent = 2) # Sites as points and species loadings as arrows ordinate(mod) # Varimax axes, on which each species loads on as few as it can p <- ordinate(mod, rotation = "varimax", label_sites = FALSE) p attr(p, "rotation")$loadings # Next, residual_cor(mod) gives the species correlations the # factors imply ## End(Not run)## Not run: # Presence and absence of 10 species at 60 sites, driven by two # latent factors simdat <- sim_jsdgam(family = bernoulli(), n_species = 10L, n_sites = 60L, n_lv = 2L, seed = 3L) mod <- jsdgam(y ~ env * series, data = simdat$data_train, family = bernoulli(), n_lv = 2L, chains = 2, silent = 2) # Sites as points and species loadings as arrows ordinate(mod) # Varimax axes, on which each species loads on as few as it can p <- ordinate(mod, rotation = "varimax", label_sites = FALSE) p attr(p, "rotation")$loadings # Next, residual_cor(mod) gives the species correlations the # factors imply ## End(Not run)
Scatters the posterior draws of each pair of parameters, with each
parameter's marginal posterior on the diagonal, as
bayesplot::mcmc_pairs() draws them. Divergent transitions are
marked. A ridge or a funnel between two parameters shows that the
data separate them poorly.
## S3 method for class 'mvgam' pairs(x, variable = NULL, regex = FALSE, ...)## S3 method for class 'mvgam' pairs(x, variable = NULL, regex = FALSE, ...)
x |
A fitted |
variable |
Either a keyword shortcut, a character vector of
parameter names, or (when
|
regex |
Logical. When |
... |
Further arguments to |
Without variable, the plot shows the parameters
mcmc_plot.mvgam() shows: the population coefficients, the family
parameters, the variance components and the trend's dynamics and
loadings. The per-basis smooth coefficients (s_*) and the
group-level deviations (r_*) run to hundreds on a spline or
hierarchical fit. They are drawn when variable names them.
A bayesplot_grid object
mcmc_plot.mvgam() draws the other bayesplot MCMC plots.
mvgam_draws lists the shortcuts variable accepts.
Other posterior summaries:
VarCorr.mvgam(),
bibtex(),
how_to_cite.mvgam(),
hypothesis.mvgam(),
index-mvgam,
mcmc_plot.mvgam(),
methods_md(),
mvgam_draws,
posterior_interval.mvgam(),
ranef.mvgam(),
smooths.mvgam(),
summary.mvgam()
## Not run: set.seed(13) simdat <- sim_mvgam(family = gaussian(), n_series = 1L, n_timepoints = 120L, trend_model = AR(), prop_trend = 0.5) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = gaussian(), chains = 2, silent = 2) # A Gaussian response adds white noise to the latent AR(1) process. # The data split the total variance between the observation noise # `sigma` and the process noise `sigma_trend` through the # autocorrelation alone. A larger `sigma` leaves less variance for # `sigma_trend`. The pair then forms a negative ridge. Divergences # gather where `sigma` nears zero. pairs(mod, variable = c("obs_params", "trend_params")) # Next, mcmc_plot(mod, type = "rank_overlay") checks that the chains # mix ## End(Not run)## Not run: set.seed(13) simdat <- sim_mvgam(family = gaussian(), n_series = 1L, n_timepoints = 120L, trend_model = AR(), prop_trend = 0.5) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = gaussian(), chains = 2, silent = 2) # A Gaussian response adds white noise to the latent AR(1) process. # The data split the total variance between the observation noise # `sigma` and the process noise `sigma_trend` through the # autocorrelation alone. A larger `sigma` leaves less variance for # `sigma_trend`. The pair then forms a negative ridge. Divergences # gather where `sigma` nears zero. pairs(mod, variable = c("obs_params", "trend_params")) # Next, mcmc_plot(mod, type = "rank_overlay") checks that the chains # mix ## End(Not run)
Occupancy and N-mixture packages such as unmarked,
ubms, flocker and spOccupancy store detection
histories as matrices or arrays, with one dimension for sites and
one for visits. mvgam() and jsdgam() with occ() or nmix()
take a long data frame instead, with one row per species, site,
season and visit. This function converts the one to the other and
copies the covariates onto the matching rows.
Data from one season give time = site. Each site is then one
closure unit. Data from several seasons take one of two layouts,
chosen by multi_season:
"fused" (the default) gives each site in each season its
own closure unit, with time = (site - 1) * T + season for
seasons. Use it when the seasons are independent given
the covariates.
"hierarchical" keeps time = season. Fit it with
occ(multi_season = TRUE) or nmix(multi_season = TRUE). Name
site in the observation formula, as in
s(site, bs = "re"). The latent trend then runs over seasons.
The model has no explicit colonisation or extinction rates.
pivot_detection_array( y, site_covs = NULL, season_covs = NULL, site_season_covs = NULL, obs_covs = NULL, species = NULL, site_col = "site", season_col = "season", visit_col = "visit", time_col = "time", series_col = "series", y_col = "y", multi_season = c("fused", "hierarchical") )pivot_detection_array( y, site_covs = NULL, season_covs = NULL, site_season_covs = NULL, obs_covs = NULL, species = NULL, site_col = "site", season_col = "season", visit_col = "visit", time_col = "time", series_col = "series", y_col = "y", multi_season = c("fused", "hierarchical") )
y |
One of four layouts:
|
site_covs |
Optional |
season_covs |
Optional |
site_season_covs |
Optional named list of
|
obs_covs |
Optional visit-level covariates:
|
species |
Optional character vector of species names with
|
site_col |
Name of the site identifier in the output.
Defaults to |
season_col |
Name of the season identifier in the output.
Defaults to |
visit_col |
Name of the visit identifier. Defaults to
|
time_col |
Name of the time column in the output. Defaults to
|
series_col |
Name of the species column. Defaults to
|
y_col |
Name of the detection / count column. Defaults to
|
multi_season |
|
A long data.frame with the columns series, site,
season, visit, time and y, followed by the covariates.
Data from one species have no series column. Data from one
season have no season column. Rows where y is NA are
dropped. Units may then differ in their number of visits.
Nicholas J Clark
occ() and nmix() for the families that take this
layout. pivot_species_matrix() converts a site-by-species
matrix.
Other model fitting:
check_newdata(),
jsdgam(),
mvgam(),
mvgam_data(),
mvgam_multiple(),
pivot_species_matrix(),
print.mvgam_formula(),
series_to_mvgam(),
stancode.mvgam_formula(),
update.mvgam()
# Detections of one species at four sites over three visits, laid out # as the `y` slot of an unmarked frame. NA marks a missed visit y <- matrix(c(0, 1, 1, 0, 0, NA, 1, 1, 0, 0, 0, 0), nrow = 4, byrow = TRUE) long <- pivot_detection_array( y, site_covs = data.frame(forest = c(0.2, 0.8, 0.5, 0.1)), obs_covs = list(wind = matrix(seq(0.1, 1.2, by = 0.1), nrow = 4)) ) # One row per observed visit. The missed visit is dropped long # Three species in a [species, site, visit] array, as spOccupancy # stores them. Each row names its species in 'series' set.seed(1) y3 <- array(rbinom(36, size = 1, prob = 0.4), dim = c(3, 4, 3)) head(pivot_detection_array(y3, species = c("owl", "hawk", "kite"))) # Next, fit the long frame with mvgam(family = occ())# Detections of one species at four sites over three visits, laid out # as the `y` slot of an unmarked frame. NA marks a missed visit y <- matrix(c(0, 1, 1, 0, 0, NA, 1, 1, 0, 0, 0, 0), nrow = 4, byrow = TRUE) long <- pivot_detection_array( y, site_covs = data.frame(forest = c(0.2, 0.8, 0.5, 0.1)), obs_covs = list(wind = matrix(seq(0.1, 1.2, by = 0.1), nrow = 4)) ) # One row per observed visit. The missed visit is dropped long # Three species in a [species, site, visit] array, as spOccupancy # stores them. Each row names its species in 'series' set.seed(1) y3 <- array(rbinom(36, size = 1, prob = 0.4), dim = c(3, 4, 3)) head(pivot_detection_array(y3, species = c("owl", "hawk", "kite"))) # Next, fit the long frame with mvgam(family = occ())
Convert the wide [J sites, N species] response matrix used by
Hmsc (and any single-visit JSDM workflow) into the long-format
(series, time, y, ...) layout that mvgam() / jsdgam() with
a simplex (diri(), multi(), categ()), continuous-response
(mvn(), mvt()), or bernoulli / binomial / poisson family
expects.
pivot_species_matrix( Y, site_covs = NULL, traits = NULL, site_id_name = "time", series_name = "series", values_to = "y" )pivot_species_matrix( Y, site_covs = NULL, traits = NULL, site_id_name = "time", series_name = "series", values_to = "y" )
Y |
A |
site_covs |
Optional |
traits |
Optional |
site_id_name |
Name of the site identifier in the output.
Defaults to |
series_name |
Name of the species column. Defaults to
|
values_to |
Name of the response column. Defaults to |
A long-format data.frame with J * N rows, each
carrying series, time, y, site covariates broadcast
across species and species traits broadcast across sites.
Nicholas J Clark
Other model fitting:
check_newdata(),
jsdgam(),
mvgam(),
mvgam_data(),
mvgam_multiple(),
pivot_detection_array(),
print.mvgam_formula(),
series_to_mvgam(),
stancode.mvgam_formula(),
update.mvgam()
# Counts of three species at five sites, one column per species Y <- matrix(c(3, 0, 5, 2, 7, 1, 1, 0, 4, 2, 0, 6, 2, 3, 1), nrow = 5, dimnames = list(NULL, c("ant", "bee", "wasp"))) long <- pivot_species_matrix( Y, site_covs = data.frame(elev = c(120, 340, 560, 780, 910)), traits = data.frame(body_size = c(2.1, 11.5, 16.0)) ) # One row per site and species, each carrying its site's elevation # and its species' body size head(long) # Next, fit the long frame with jsdgam(unit = time, species = series)# Counts of three species at five sites, one column per species Y <- matrix(c(3, 0, 5, 2, 7, 1, 1, 0, 4, 2, 0, 6, 2, 3, 1), nrow = 5, dimnames = list(NULL, c("ant", "bee", "wasp"))) long <- pivot_species_matrix( Y, site_covs = data.frame(elev = c(120, 340, 560, 780, 910)), traits = data.frame(body_size = c(2.1, 11.5, 16.0)) ) # One row per site and species, each carrying its site's elevation # and its species' body size head(long) # Next, fit the long frame with jsdgam(unit = time, species = series)
Draws one of the standard views of a fitted model, chosen by type.
## S3 method for class 'mvgam' plot( x, type = c("residuals", "smooths", "trend", "factors", "series", "latent_state"), series = NULL, resp = NULL, ndraws = NULL, component = NULL, ... )## S3 method for class 'mvgam' plot( x, type = c("residuals", "smooths", "trend", "factors", "series", "latent_state"), series = NULL, resp = NULL, ndraws = NULL, component = NULL, ... )
x |
A fitted |
type |
The plot to draw:
|
series |
A series index or name. |
resp |
Character specifying which response variable for multivariate models. NULL (default) returns predictions for all responses. |
ndraws |
The number of posterior draws, or |
component |
|
... |
Further arguments to the function that draws the plot,
such as |
A ggplot object, or a patchwork of several.
Nicholas J Clark
forecast.mvgam() and its plot() method draw forecasts.
conditional_effects.mvgam() draws covariate effects.
mcmc_plot.mvgam() draws posterior diagnostics.
Other model checking:
mvgam_diagnostics,
pp_check.mvgam(),
residuals.mvgam()
## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # Residual diagnostics, the default plot(mod) # The smooth of x and the latent AR(1) trend plot(mod, type = "smooths") plot(mod, type = "trend") # The slope of a local linear trend mod_llt <- update(mod, trend_formula = ~ LLT()) plot(mod_llt, type = "trend", component = "slope") # Next, plot(forecast(mod, newdata = simdat$data_test)) carries the # trend forward ## End(Not run)## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # Residual diagnostics, the default plot(mod) # The smooth of x and the latent AR(1) trend plot(mod, type = "smooths") plot(mod, type = "trend") # The slope of a local linear trend mod_llt <- update(mod, trend_formula = ~ LLT()) plot(mod_llt, type = "trend", component = "slope") # Next, plot(forecast(mod, newdata = simdat$data_test)) carries the # trend forward ## End(Not run)
Plot method for mvgam_forecast objects returned by
hindcast.mvgam() and forecast.mvgam(). Draws one panel per
series (faceted by default) with nested quantile ribbons for the
forecast, a single grey ribbon for the hindcast, posterior median
lines and the observations as points. A dashed vertical line marks
the boundary between training and forecast times when both are
drawn.
## S3 method for class 'mvgam_forecast' plot( x, series = NULL, probs = c(0.5, 0.8, 0.95), hindcast = TRUE, forecast = TRUE, newdata_obs = TRUE, ... )## S3 method for class 'mvgam_forecast' plot( x, series = NULL, probs = c(0.5, 0.8, 0.95), hindcast = TRUE, forecast = TRUE, newdata_obs = TRUE, ... )
x |
An |
series |
Optional integer vector, character vector of
series names, or |
probs |
Numeric vector of credible interval widths for
the forecast ribbon. Defaults to |
hindcast, forecast
|
Logical. Whether the hindcast and the
forecast are drawn. Both default to |
newdata_obs |
Logical. When |
... |
Unused. Anything passed here is refused. |
The forecast takes the shades of the red bayesplot scheme. The hindcast band is light grey, which separates in-sample uncertainty from the nested forecast bands.
forecast.mvgam() and hindcast.mvgam() return the objects this
method draws. Predictions that leave out the fitted trend state
come from posterior_predict.mvgam() and
posterior_epred.mvgam().
A ggplot object.
Nicholas J Clark
forecast.mvgam(), hindcast.mvgam(),
score.mvgam_forecast(), summary.mvgam_forecast()
## Not run: set.seed(1) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) # Two models of one count series: a smooth of x with and without # an AR(1) trend. The trend model samples with smaller steps # (adapt_delta = 0.95). That avoids divergent transitions when # lfo_cv() refits it to shorter stretches of the series mod_gam <- mvgam(y ~ s(x, k = 5), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) mod_ar <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2, control = list(adapt_delta = 0.95)) ## End(Not run) ## Not run: fc <- forecast(mod_ar, newdata = simdat$data_test) # The grey hindcast band covers the training times. The red bands # are the 80% and 95% forecast intervals, with the held-out counts # as points plot(fc, probs = c(0.8, 0.95)) # The forecast alone plot(fc, hindcast = FALSE) ## End(Not run)## Not run: set.seed(1) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) # Two models of one count series: a smooth of x with and without # an AR(1) trend. The trend model samples with smaller steps # (adapt_delta = 0.95). That avoids divergent transitions when # lfo_cv() refits it to shorter stretches of the series mod_gam <- mvgam(y ~ s(x, k = 5), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) mod_ar <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2, control = list(adapt_delta = 0.95)) ## End(Not run) ## Not run: fc <- forecast(mod_ar, newdata = simdat$data_test) # The grey hindcast band covers the training times. The red bands # are the 80% and 95% forecast intervals, with the held-out counts # as points plot(fc, probs = c(0.8, 0.95)) # The forecast alone plot(fc, hindcast = FALSE) ## End(Not run)
An impulse response draws the posterior median and interval of each
shock-response pair against the forecast horizon, with a dashed
line at zero. A variance decomposition stacks the median shares of
its sources in one panel per target, as plot.mvgam_fevd() does.
## S3 method for class 'mvgam_var_surface_summary' plot( x, series = NULL, responses = NULL, contributing = NULL, shocks = NULL, ... )## S3 method for class 'mvgam_var_surface_summary' plot( x, series = NULL, responses = NULL, contributing = NULL, shocks = NULL, ... )
x |
A |
series |
Positions or names of the processes to keep. On an impulse response these are the processes a shock originates in. On a variance decomposition they are the targets whose forecast error is decomposed. Default keeps every process. |
responses |
Impulse responses only. Positions or names of the processes whose response to the shock is drawn. Default keeps every process. |
contributing |
Variance decompositions only. Positions or names of the source processes stacked in each bar. The shares of the sources drawn are renormalised to sum to one. |
shocks |
Optional character vector naming shock-response pairs directly, for a selection the index arguments cannot express. |
... |
Unused. Anything passed here is refused. |
A ggplot object
Monthly time series of rodent captures for selected species of the Portal Project, a long-term study of a Chihuahuan Desert ecosystem near Portal, Arizona. Captures are summed across all control plots.
portal_dataportal_data
A data.frame containing the following fields:
time of sampling, in lunar monthly cycles
factor identifying the species
total captures across all control plots at each time
12-month moving average of the mean Normalised Difference Vegetation Index, a measure of plant greenness
monthly mean of the minimum temperature
https://github.com/weecology/PortalData/blob/main/SiteandMethods/Methods.md
mvgam() for a state-space model of these counts and
mvgam_data() to check the data. The
overview article fits one.
data(portal_data) mvgam_data(portal_data, y = "captures", family = poisson())data(portal_data) mvgam_data(portal_data, y = "captures", family = poisson())
Bayesian model averaging of two or more mvgam fits, as in
brms::posterior_average.brmsfit() and brms::pp_average.brmsfit().
Each fit contributes draws in proportion to its model weight.
posterior_average() averages parameter draws. pp_average()
averages predictions.
## S3 method for class 'mvgam' posterior_average( x, ..., variable = NULL, pars = NULL, weights = "stacking", ndraws = NULL, nsamples = NULL, missing = NULL, model_names = NULL, control = list(), seed = NULL ) ## S3 method for class 'mvgam' pp_average( x, ..., weights = "stacking", method = "posterior_predict", ndraws = NULL, nsamples = NULL, summary = TRUE, probs = c(0.025, 0.975), robust = FALSE, model_names = NULL, control = list(), seed = NULL )## S3 method for class 'mvgam' posterior_average( x, ..., variable = NULL, pars = NULL, weights = "stacking", ndraws = NULL, nsamples = NULL, missing = NULL, model_names = NULL, control = list(), seed = NULL ) ## S3 method for class 'mvgam' pp_average( x, ..., weights = "stacking", method = "posterior_predict", ndraws = NULL, nsamples = NULL, summary = TRUE, probs = c(0.025, 0.975), robust = FALSE, model_names = NULL, control = list(), seed = NULL )
x |
A fitted |
... |
Further fitted |
variable |
Optional character vector of parameter names
to extract, as |
pars |
Deprecated brms alias for |
weights |
A numeric vector with one weight per fit, scaled to
sum to one, or one of |
ndraws |
Total number of model-averaged draws to return. Defaults to the number of draws in the first fit. |
nsamples |
Deprecated brms alias for |
missing |
Values for parameters some fits lack. |
model_names |
Optional character vector of model names, one per forecast. It replaces the names taken from the call. |
control |
A list of extra arguments passed to
|
seed |
Optional integer seed. The session's random state is restored when the call returns. |
method |
Which prediction function |
summary |
Logical. If |
probs |
Numeric vector of probabilities for quantile computation.
Default is |
robust |
Logical. If |
posterior_average() returns a data.frame of
model-averaged posterior draws. pp_average() returns a numeric
matrix of averaged predictions. With summary = TRUE its rows are
observations and its columns summary statistics. Otherwise its
rows are draws and its columns observations. Attribute weights
holds the weight of each fit. Attribute ndraws holds the number
of draws taken from each fit.
Nicholas J Clark
loo_model_weights.mvgam() computes the weights.
ensemble() averages forecasts. The
forecast evaluation article
weights and combines competing models.
Other model comparison:
bridge_sampler.mvgam(),
compare_elpds(),
kfold.mvgam(),
lfo_cv.mvgam(),
log_lik.mvgam(),
loo.mvgam(),
loo_compare.mvgam_lfo(),
mvgam_loo_extras,
waic.mvgam()
## Not run: # A Poisson GAM without a latent trend. PSIS approximates each # held-out count of such a model well (see Details of ?loo.mvgam) set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = "None") mod <- mvgam(y ~ s(x), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) ## End(Not run) ## Not run: # The same smooth of x replaced by a linear effect mod_lin <- update(mod, formula. = y ~ x) # Stacking weights from approximate leave-one-out cross-validation loo_model_weights(mod, mod_lin) # The intercept, averaged over both fits under those weights pa <- posterior_average(mod, mod_lin, variable = "b_Intercept") attr(pa, "weights") summary(pa) # Averaged expected counts, one row per observation head(pp_average(mod, mod_lin, method = "posterior_epred")) ## End(Not run)## Not run: # A Poisson GAM without a latent trend. PSIS approximates each # held-out count of such a model well (see Details of ?loo.mvgam) set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = "None") mod <- mvgam(y ~ s(x), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) ## End(Not run) ## Not run: # The same smooth of x replaced by a linear effect mod_lin <- update(mod, formula. = y ~ x) # Stacking weights from approximate leave-one-out cross-validation loo_model_weights(mod, mod_lin) # The intercept, averaged over both fits under those weights pa <- posterior_average(mod, mod_lin, variable = "b_Intercept") attr(pa, "weights") summary(pa) # Averaged expected counts, one row per observation head(pp_average(mod, mod_lin, method = "posterior_epred")) ## End(Not run)
Draws of , the mean of the response given each
posterior draw's parameters. The observation and trend predictors are
summed on the link scale. The family's mean then maps the sum onto
the response scale. posterior_predict.mvgam() adds the observation
noise around these means.
## S3 method for class 'mvgam' posterior_epred( object, newdata = NULL, process_error = FALSE, incl_autocor = FALSE, ndraws = NULL, draw_ids = NULL, re_formula = NULL, allow_new_levels = FALSE, sample_new_levels = "uncertainty", resp = NULL, dpar = NULL, ... )## S3 method for class 'mvgam' posterior_epred( object, newdata = NULL, process_error = FALSE, incl_autocor = FALSE, ndraws = NULL, draw_ids = NULL, re_formula = NULL, allow_new_levels = FALSE, sample_new_levels = "uncertainty", resp = NULL, dpar = NULL, ... )
object |
A fitted mvgam object from |
newdata |
Optional data frame with covariates for prediction. If NULL, uses original training data stored in the model object. |
process_error |
Logical. Each call draws new innovations. Two calls on one fit give different results. Set a seed to reproduce a result. |
incl_autocor |
Logical. Chooses which version of the trend each
prediction uses. An ELPD or an The default suits a model whose covariates explain most of the
signal. When most of the series-level variation lies in the trend,
as in a fit with few covariates and a strong autoregressive process,
the covariate part has little to say. |
ndraws |
Positive integer specifying number of posterior draws to use. NULL (default) uses all available draws. |
draw_ids |
Optional integer vector selecting a subset of posterior
draw indices to use. NULL (default) uses all draws (subject to
|
re_formula |
Group-level terms to include: |
allow_new_levels |
Logical. |
sample_new_levels |
How a new level's coefficients are drawn:
|
resp |
Character specifying which response variable for multivariate models. NULL (default) returns predictions for all responses. |
dpar |
Character naming a distributional parameter, such as
|
... |
Unused. Anything passed here is refused. |
For most families the mean is the inverse link of the predictor. A
binomial mean is trials * p, with the trials taken from the
trials() term evaluated against newdata. A zero-inflated or
hurdle mean scales the base mean by the probability of a non-zero
draw. A lognormal mean carries the correction
exp(mu + sigma^2 / 2). A trunc() term gives the mean of the
distribution truncated to its bounds.
The mean of an nmix() or occ() visit thins the latent abundance
or occupancy by that visit's detection probability. A composition
family normalises its means across the components of each unit.
An [ndraws, nobs] matrix of expected values on the response
scale, one row per draw and one column per row of newdata. An
ordinal response gives an [ndraws, nobs, ncat] array of category
probabilities. A multivariate model with
resp = NULL gives a named list, one element per response.
By default the trend enters through its covariate part, without the
state it took at each observed time. The brms counterparts of
this method use that fitted state. incl_autocor = TRUE uses it
here too, as fitted.mvgam() and pp_check.mvgam() do on the
training data. The section 'Which prediction function?' of
predict.mvgam() compares the prediction functions.
posterior_linpred.mvgam() returns the predictor on the
link scale. hindcast.mvgam() and forecast.mvgam() take the
trend from its fitted state, in and beyond the training times. The
forecast evaluation article
scores predictions of held-out times.
Other predictions:
conditional_effects.mvgam(),
conditional_smooths.mvgam(),
fitted.mvgam(),
hindcast(),
posterior_linpred.mvgam(),
posterior_predict.mvgam(),
posterior_smooths.mvgam(),
predict.mvgam(),
predictive_error.mvgam(),
predictive_interval.mvgam()
## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # One row per draw, one column per observation ep <- posterior_epred(mod) dim(ep) # Expected counts from the covariate part and from the fitted state, # against the observed counts ep_state <- posterior_epred(mod, incl_autocor = TRUE) library(ggplot2) ggplot(simdat$data_train, aes(time, y)) + geom_point(colour = "grey60") + geom_line(aes(y = colMeans(ep), colour = "Covariates")) + geom_line(aes(y = colMeans(ep_state), colour = "Fitted trend")) + scale_colour_manual(values = c("#DCBCBC", "#8F2727"), name = NULL) + labs(y = "Count") + mvgam_theme() # Sampling the trend's innovations raises the average of a log-link # prediction c(fixed = mean(ep), innovations = mean(posterior_epred(mod, process_error = TRUE))) # A site the fit never saw takes the spread of the fitted sites train <- simdat$data_train train$site <- rep(paste0("site", 1:6), length.out = nrow(train)) mod_site <- mvgam(y ~ (1 | site), trend_formula = ~ AR(p = 1), data = train, family = poisson(), chains = 2, silent = 2) new_site <- transform(train[1:3, ], site = "unseen") posterior_epred(mod_site, newdata = new_site, allow_new_levels = TRUE, sample_new_levels = "gaussian", ndraws = 3) # Next: posterior_predict() adds observation noise to these means ## End(Not run)## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # One row per draw, one column per observation ep <- posterior_epred(mod) dim(ep) # Expected counts from the covariate part and from the fitted state, # against the observed counts ep_state <- posterior_epred(mod, incl_autocor = TRUE) library(ggplot2) ggplot(simdat$data_train, aes(time, y)) + geom_point(colour = "grey60") + geom_line(aes(y = colMeans(ep), colour = "Covariates")) + geom_line(aes(y = colMeans(ep_state), colour = "Fitted trend")) + scale_colour_manual(values = c("#DCBCBC", "#8F2727"), name = NULL) + labs(y = "Count") + mvgam_theme() # Sampling the trend's innovations raises the average of a log-link # prediction c(fixed = mean(ep), innovations = mean(posterior_epred(mod, process_error = TRUE))) # A site the fit never saw takes the spread of the fitted sites train <- simdat$data_train train$site <- rep(paste0("site", 1:6), length.out = nrow(train)) mod_site <- mvgam(y ~ (1 | site), trend_formula = ~ AR(p = 1), data = train, family = poisson(), chains = 2, silent = 2) new_site <- transform(train[1:3, ], site = "unseen") posterior_epred(mod_site, newdata = new_site, allow_new_levels = TRUE, sample_new_levels = "gaussian", ndraws = 3) # Next: posterior_predict() adds observation noise to these means ## End(Not run)
Central quantile intervals of the posterior draws of parameters. The
parameters are chosen as in as.matrix.mvgam().
## S3 method for class 'mvgam' posterior_interval(object, pars = NULL, variable = NULL, prob = 0.95, ...)## S3 method for class 'mvgam' posterior_interval(object, pars = NULL, variable = NULL, prob = 0.95, ...)
object |
A fitted |
pars |
Deprecated alias for |
variable |
Either a keyword shortcut, a character vector of
parameter names, or (when
|
prob |
Numeric in |
... |
Further arguments of |
A numeric matrix with one row per parameter and two columns, the lower and upper bounds.
Nicholas J Clark
predictive_interval.mvgam() gives intervals of predictive
draws. summary.mvgam() reports intervals with convergence
diagnostics.
Other posterior summaries:
VarCorr.mvgam(),
bibtex(),
how_to_cite.mvgam(),
hypothesis.mvgam(),
index-mvgam,
mcmc_plot.mvgam(),
methods_md(),
mvgam_draws,
pairs.mvgam(),
ranef.mvgam(),
smooths.mvgam(),
summary.mvgam()
## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # 90 percent intervals of the autoregression and its innovation SD posterior_interval(mod, variable = c("ar1_trend", "sigma_trend"), prob = 0.9) # Next: summary() reports these with convergence diagnostics ## End(Not run)## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # 90 percent intervals of the autoregression and its innovation SD posterior_interval(mod, variable = c("ar1_trend", "sigma_trend"), prob = 0.9) # Next: summary() reports these with convergence diagnostics ## End(Not run)
Draws of the linear predictor , the sum of the observation
and trend predictors on the link scale. A Poisson predictor is on the
log scale and a binomial predictor on the logit scale.
posterior_epred.mvgam() maps it onto the response scale.
## S3 method for class 'mvgam' posterior_linpred( object, transform = FALSE, newdata = NULL, process_error = FALSE, incl_autocor = FALSE, ndraws = NULL, draw_ids = NULL, re_formula = NULL, allow_new_levels = FALSE, sample_new_levels = "uncertainty", resp = NULL, dpar = NULL, ... )## S3 method for class 'mvgam' posterior_linpred( object, transform = FALSE, newdata = NULL, process_error = FALSE, incl_autocor = FALSE, ndraws = NULL, draw_ids = NULL, re_formula = NULL, allow_new_levels = FALSE, sample_new_levels = "uncertainty", resp = NULL, dpar = NULL, ... )
object |
A fitted mvgam object from |
transform |
Logical. |
newdata |
Optional data frame with covariates for prediction. If NULL, uses original training data stored in the model object. |
process_error |
Logical. Each call draws new innovations. Two calls on one fit give different results. Set a seed to reproduce a result. |
incl_autocor |
Logical. Chooses which version of the trend each
prediction uses. An ELPD or an The default suits a model whose covariates explain most of the
signal. When most of the series-level variation lies in the trend,
as in a fit with few covariates and a strong autoregressive process,
the covariate part has little to say. |
ndraws |
Positive integer specifying number of posterior draws to use. NULL (default) uses all available draws. |
draw_ids |
Optional integer vector selecting a subset of posterior
draw indices to use. NULL (default) uses all draws (subject to
|
re_formula |
Group-level terms to include: |
allow_new_levels |
Logical. |
sample_new_levels |
How a new level's coefficients are drawn:
|
resp |
Character specifying which response variable for multivariate models. NULL (default) returns predictions for all responses. |
dpar |
Character naming a distributional parameter, such as
|
... |
Unused. Anything passed here is refused. |
The observation predictor holds the fixed, group-level, smooth and
Gaussian process terms of formula. The trend predictor holds the
terms of trend_formula. process_error = TRUE adds a sampled
deviation at each time and series, on the link scale.
posterior_epred.mvgam() and posterior_predict.mvgam() apply the
family's mean and noise to that same predictor.
An ordinal response's category-specific cs() terms give each
threshold its own shift. The predictor holds the terms every
threshold shares. posterior_epred.mvgam() and
posterior_predict.mvgam() subtract the shifts from the thresholds,
as brms does.
An [ndraws, nobs] matrix, one row per draw and one column
per row of newdata. It is on the link scale unless transform = TRUE or dpar names a scalar parameter. A multivariate model
with resp = NULL gives a named list, one element per response.
By default the trend enters through its covariate part, without the
state it took at each observed time. The brms counterparts of
this method use that fitted state. incl_autocor = TRUE uses it
here too, as fitted.mvgam() and pp_check.mvgam() do on the
training data. The section 'Which prediction function?' of
predict.mvgam() compares the prediction functions.
posterior_epred.mvgam() returns expected values.
posterior_predict.mvgam() returns predictive draws.
hindcast.mvgam() and forecast.mvgam() take the trend from its
fitted state. The
forecast evaluation article
scores predictions of held-out times.
Other predictions:
conditional_effects.mvgam(),
conditional_smooths.mvgam(),
fitted.mvgam(),
hindcast(),
posterior_epred.mvgam(),
posterior_predict.mvgam(),
posterior_smooths.mvgam(),
predict.mvgam(),
predictive_error.mvgam(),
predictive_interval.mvgam()
## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # Log rates, one row per draw and one column per observation lp <- posterior_linpred(mod, draw_ids = 1:50) dim(lp) # A Poisson mean is the inverse link of the predictor all.equal(exp(lp), posterior_epred(mod, draw_ids = 1:50)) # The predictor under the fitted trend state tracks the series lp_state <- posterior_linpred(mod, incl_autocor = TRUE) library(ggplot2) ggplot(simdat$data_train, aes(time, log1p(y))) + geom_point(colour = "grey60") + geom_line(aes(y = colMeans(lp_state)), colour = "#8F2727", linewidth = 1) + labs(y = "log(1 + count)") + mvgam_theme() # Next: posterior_epred() maps the predictor to expected counts ## End(Not run)## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # Log rates, one row per draw and one column per observation lp <- posterior_linpred(mod, draw_ids = 1:50) dim(lp) # A Poisson mean is the inverse link of the predictor all.equal(exp(lp), posterior_epred(mod, draw_ids = 1:50)) # The predictor under the fitted trend state tracks the series lp_state <- posterior_linpred(mod, incl_autocor = TRUE) library(ggplot2) ggplot(simdat$data_train, aes(time, log1p(y))) + geom_point(colour = "grey60") + geom_line(aes(y = colMeans(lp_state)), colour = "#8F2727", linewidth = 1) + labs(y = "log(1 + count)") + mvgam_theme() # Next: posterior_epred() maps the predictor to expected counts ## End(Not run)
Draws from the posterior predictive distribution: the family's
observation noise around the parameters of each posterior draw.
They predict new observations, for the training data or new data.
pp_check.mvgam() draws them under the fitted state to check a fit
against its data.
## S3 method for class 'mvgam' posterior_predict( object, newdata = NULL, process_error = FALSE, incl_autocor = FALSE, ndraws = NULL, draw_ids = NULL, re_formula = NULL, allow_new_levels = FALSE, sample_new_levels = "uncertainty", resp = NULL, ... )## S3 method for class 'mvgam' posterior_predict( object, newdata = NULL, process_error = FALSE, incl_autocor = FALSE, ndraws = NULL, draw_ids = NULL, re_formula = NULL, allow_new_levels = FALSE, sample_new_levels = "uncertainty", resp = NULL, ... )
object |
A fitted mvgam object from |
newdata |
Optional data frame with covariates for prediction. If NULL, uses original training data stored in the model object. |
process_error |
Logical. Each call draws new innovations. Two calls on one fit give different results. Set a seed to reproduce a result. |
incl_autocor |
Logical. Chooses which version of the trend each
prediction uses. An ELPD or an The default suits a model whose covariates explain most of the
signal. When most of the series-level variation lies in the trend,
as in a fit with few covariates and a strong autoregressive process,
the covariate part has little to say. |
ndraws |
Positive integer specifying number of posterior draws to use. NULL (default) uses all available draws. |
draw_ids |
Optional integer vector selecting a subset of posterior
draw indices to use. NULL (default) uses all draws (subject to
|
re_formula |
Group-level terms to include: |
allow_new_levels |
Logical. |
sample_new_levels |
How a new level's coefficients are drawn:
|
resp |
Character specifying which response variable for multivariate models. NULL (default) returns predictions for all responses. |
... |
Unused. Anything passed here is refused. |
Each family draws from its own distribution at the parameters
posterior_linpred.mvgam() and posterior_epred.mvgam() use. A
trunc() term restricts the draws to its bounds.
hindcast.mvgam() draws under the fitted latent states at the
training times. forecast.mvgam() propagates them to future times.
An [ndraws, nobs] matrix on the response scale, one row per
draw and one column per row of newdata. A multivariate model
with resp = NULL gives a named list, one element per response.
By default the trend enters through its covariate part, without the
state it took at each observed time. The brms counterparts of
this method use that fitted state. incl_autocor = TRUE uses it
here too, as fitted.mvgam() and pp_check.mvgam() do on the
training data. The section 'Which prediction function?' of
predict.mvgam() compares the prediction functions.
pp_check.mvgam() compares draws taken under the fitted
state with the data.
forecast.mvgam() predicts future times from the fitted state.
Other predictions:
conditional_effects.mvgam(),
conditional_smooths.mvgam(),
fitted.mvgam(),
hindcast(),
posterior_epred.mvgam(),
posterior_linpred.mvgam(),
posterior_smooths.mvgam(),
predict.mvgam(),
predictive_error.mvgam(),
predictive_interval.mvgam()
## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # Simulated counts, one row per draw and one column per observation pp <- posterior_predict(mod) dim(pp) # The share of observed counts inside their 90 percent predictive # intervals bounds <- apply(pp, 2, quantile, probs = c(0.05, 0.95)) y <- simdat$data_train$y mean(y >= bounds[1, ] & y <= bounds[2, ]) # Next: pp_check() plots the draws against the observed counts ## End(Not run)## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # Simulated counts, one row per draw and one column per observation pp <- posterior_predict(mod) dim(pp) # The share of observed counts inside their 90 percent predictive # intervals bounds <- apply(pp, 2, quantile, probs = c(0.05, 0.95)) y <- simdat$data_train$y mean(y >= bounds[1, ] & y <= bounds[2, ]) # Next: pp_check() plots the draws against the observed counts ## End(Not run)
Evaluates one smooth at the rows of newdata for each posterior
draw, in the shape brms::posterior_smooths() returns. The smooth
can be any s() or t2() term of the observation formula, a
distributional or non-linear parameter's formula, or the trend
formula, by factors included.
## S3 method for class 'mvgam' posterior_smooths( object, smooth, newdata = NULL, resp = NULL, dpar = NULL, nlpar = NULL, ndraws = NULL, draw_ids = NULL, ... )## S3 method for class 'mvgam' posterior_smooths( object, smooth, newdata = NULL, resp = NULL, dpar = NULL, nlpar = NULL, ndraws = NULL, draw_ids = NULL, ... )
object |
A fitted |
smooth |
The smooth term as the formula writes it, such as
|
newdata |
A |
resp |
The response the smooth belongs to, required on a model with several. |
dpar, nlpar
|
The distributional or non-linear parameter the
smooth belongs to. Name at most one. With both |
ndraws, draw_ids
|
The number of posterior draws, or their
indices. Give at most one. |
... |
Unused. Anything passed here is refused. |
The smooth's contribution is its unpenalised basis times its
fixed coefficients plus each penalised basis times its random
coefficients, per draw. The bases come from brms::standata()
evaluated on newdata. The coefficients come from the draws.
brms::posterior_smooths() adds a predictor's offsets to each of
its smooths. This method leaves them out.
A term written in both the observation and the trend formula is taken from the observation formula.
A numeric matrix with one row per draw and one column per
row of newdata: the smooth's contribution to the linear
predictor.
Nicholas J Clark
conditional_smooths.mvgam() summarises every smooth.
smooths.mvgam() lists the terms.
Other predictions:
conditional_effects.mvgam(),
conditional_smooths.mvgam(),
fitted.mvgam(),
hindcast(),
posterior_epred.mvgam(),
posterior_linpred.mvgam(),
posterior_predict.mvgam(),
predict.mvgam(),
predictive_error.mvgam(),
predictive_interval.mvgam()
## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # Twenty draws of s(x) over a grid of x grid <- data.frame(x = seq(-2, 2, length.out = 50)) sm <- posterior_smooths(mod, smooth = "s(x, k = 5)", newdata = grid) draws <- data.frame(x = rep(grid$x, each = 20), value = as.vector(sm[1:20, ]), draw = rep(1:20, times = 50)) library(ggplot2) ggplot(draws, aes(x, value, group = draw)) + geom_line(colour = "#8F2727", alpha = 0.4) + labs(y = "s(x)") + mvgam_theme() # Next, conditional_smooths(mod) summarises every smooth in one call ## End(Not run)## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # Twenty draws of s(x) over a grid of x grid <- data.frame(x = seq(-2, 2, length.out = 50)) sm <- posterior_smooths(mod, smooth = "s(x, k = 5)", newdata = grid) draws <- data.frame(x = rep(grid$x, each = 20), value = as.vector(sm[1:20, ]), draw = rep(1:20, times = 50)) library(ggplot2) ggplot(draws, aes(x, value, group = draw)) + geom_line(colour = "#8F2727", alpha = 0.4) + labs(y = "s(x)") + mvgam_theme() # Next, conditional_smooths(mod) summarises every smooth in one call ## End(Not run)
The coefficient matrix of lag of a VAR() trend.
Row holds the effects of the processes at time
on process at time . The diagonal holds each
process's persistence. The off-diagonal cells hold the effects of
one process on another.
posterior_transition_matrix( object, groups = NULL, summary = TRUE, robust = FALSE, probs = c(0.025, 0.975), prob_threshold = 0.95, lag = 1L ) ## S3 method for class 'mvgam_var_matrix' print(x, digits = 2L, ...) ## S3 method for class 'mvgam_var_matrix' plot(x, cluster = FALSE, supported_only = FALSE, ...) ## S3 method for class 'mvgam_var_matrix_list' print(x, ...) ## S3 method for class 'mvgam_var_matrix_list' plot( x, type = c("heatmap", "diagonal"), ncol = NULL, supported_only = FALSE, ... )posterior_transition_matrix( object, groups = NULL, summary = TRUE, robust = FALSE, probs = c(0.025, 0.975), prob_threshold = 0.95, lag = 1L ) ## S3 method for class 'mvgam_var_matrix' print(x, digits = 2L, ...) ## S3 method for class 'mvgam_var_matrix' plot(x, cluster = FALSE, supported_only = FALSE, ...) ## S3 method for class 'mvgam_var_matrix_list' print(x, ...) ## S3 method for class 'mvgam_var_matrix_list' plot( x, type = c("heatmap", "diagonal"), ncol = NULL, supported_only = FALSE, ... )
object |
A fitted |
groups |
The panels of a hierarchical VAR, by level or by
index, or |
summary |
Logical. |
robust |
Logical. If |
probs |
Numeric vector of probabilities for quantile computation.
Default is |
prob_threshold |
The posterior probability of its sign a cell
needs to count as supported, at least 0.5 and below 1. Defaults to
0.95. |
lag |
The lag of the matrix, at most the order |
x |
An |
digits |
Integer number of digits in the printed matrix. Defaults to 2. |
... |
Unused. Anything passed here is refused. |
cluster |
Logical. |
supported_only |
Logical. |
type |
For several panels, |
ncol |
The number of facet columns of the heatmaps, or |
A hierarchical VAR (VAR(gr = ...)) has one matrix per panel.
groups names a panel to return its matrix. With groups = NULL
the function returns the mean of the panels' matrices, computed in
each draw. The hyperparameters Amu_trend and Aomega_trend pool
unconstrained matrices, which the stationarity map of Heaps (2023)
turns into each panel's matrix. Their mean is no transition matrix.
The mean over panels summarises the pool on the scale of the
matrices.
Each cell is summarised as residual_cor() summarises a
correlation. The estimate is the posterior mean, or the median with
robust = TRUE. The interval takes the quantiles probs. The
effective sample size comes from posterior::ess_basic().
prob_positive, prob_negative and prob_nonzero are the shares of
draws above zero, below zero and away from zero.
With summary = TRUE, an mvgam_var_matrix: a list of the
matrices A, A_se, A_lower, A_upper, A_ess,
prob_positive, prob_negative and prob_nonzero, with
n_series, series_names, group_label, probs,
prob_threshold and lag. With summary = FALSE, the array of
draws. Several panels give a list of either, an
mvgam_var_matrix_list when summarised.
print() gives the panel, the dimension, the mean absolute
off-diagonal cell and the estimate of the matrix. For several
panels it lists each panel's mean absolute off-diagonal cell. The
panel with the largest has the strongest effects between processes.
plot() draws the matrix as a heatmap. Row , column
is the effect of process at time on
process at time . A black outline marks each cell
whose prob_nonzero exceeds prob_threshold. The colour scale is
symmetric about zero. Several panels share one scale. Under
type = "diagonal" they draw the persistence of each process as a
point with its interval.
Nicholas J Clark
Savage J (2016). Hierarchical Vector Autoregression. RPubs, 27 November 2016. https://rpubs.com/jimsavage/hierarchical_var
Heaps SE (2023). Enforcing stationarity through the prior in vector autoregressions. Journal of Computational and Graphical Statistics 32(1), 74-83. doi:10.1080/10618600.2022.2079648
VAR(), residual_cor(), irf(), fevd(),
stability(), print.mvgam_var_matrix(),
plot.mvgam_var_matrix().
Other latent dynamics:
active_factors(),
compare_loadings(),
fevd.mvgam(),
irf.mvgam(),
ordinate(),
residual_cor(),
shared_variation(),
stability.mvgam()
## Not run: # Ten years of monthly counts of a prey species and its predator. # Predators suppress the prey a month later. Prey raise the # predators a month later. set.seed(2025) n_months <- 120 A <- rbind(prey = c(0.6, -0.5), predator = c(0.4, 0.5)) z <- matrix(0, n_months, 2) for (t in 2:n_months) { z[t, ] <- A %*% z[t - 1, ] + rnorm(2, sd = 0.35) } predator_prey <- data.frame( time = rep(seq_len(n_months), 2), series = factor(rep(c("prey", "predator"), each = n_months), levels = c("prey", "predator")), y = rpois(2 * n_months, exp(c(2.5 + z[, 1], 1.5 + z[, 2]))) ) var_mod <- mvgam(y ~ series, trend_formula = ~ VAR(), data = predator_prey, family = poisson(), chains = 2, silent = 2) ## End(Not run) ## Not run: # Each series' persistence and its effects on the others A <- posterior_transition_matrix(var_mod) A plot(A) # Next, irf(var_mod) traces how a shock to one series spreads ## End(Not run)## Not run: # Ten years of monthly counts of a prey species and its predator. # Predators suppress the prey a month later. Prey raise the # predators a month later. set.seed(2025) n_months <- 120 A <- rbind(prey = c(0.6, -0.5), predator = c(0.4, 0.5)) z <- matrix(0, n_months, 2) for (t in 2:n_months) { z[t, ] <- A %*% z[t - 1, ] + rnorm(2, sd = 0.35) } predator_prey <- data.frame( time = rep(seq_len(n_months), 2), series = factor(rep(c("prey", "predator"), each = n_months), levels = c("prey", "predator")), y = rpois(2 * n_months, exp(c(2.5 + z[, 1], 1.5 + z[, 2]))) ) var_mod <- mvgam(y ~ series, trend_formula = ~ VAR(), data = predator_prey, family = poisson(), chains = 2, silent = 2) ## End(Not run) ## Not run: # Each series' persistence and its effects on the others A <- posterior_transition_matrix(var_mod) A plot(A) # Next, irf(var_mod) traces how a shock to one series spreads ## End(Not run)
Compares the observed response with replicates drawn from the fitted
model through the bayesplot ppc_* functions. Further types
plot randomised quantile residuals and, for nmix() and occ()
fits, a discrepancy statistic. Returns a ggplot2 object.
## S3 method for class 'mvgam' pp_check( object, type, ndraws = NULL, prefix = c("ppc", "ppd"), group = NULL, x = NULL, newdata = NULL, resp = NULL, draw_ids = NULL, per_obs = TRUE, series = NULL, ... ) ## S3 method for class 'mvgam_ppc_fit_stat' print(x, ...) ## S3 method for class 'mvgam_ppc_fit_stat' plot(x, ...)## S3 method for class 'mvgam' pp_check( object, type, ndraws = NULL, prefix = c("ppc", "ppd"), group = NULL, x = NULL, newdata = NULL, resp = NULL, draw_ids = NULL, per_obs = TRUE, series = NULL, ... ) ## S3 method for class 'mvgam_ppc_fit_stat' print(x, ...) ## S3 method for class 'mvgam_ppc_fit_stat' plot(x, ...)
object |
An object of class |
type |
Type of the check. A bayesplot |
ndraws |
Number of posterior draws to plot. |
prefix |
|
group |
Optional name of a factor variable in the model
by which to stratify the ppc plot. This argument is required for
ppc |
x |
An |
newdata |
Optional data frame of the variables in the model.
|
resp |
Optional names of response variables. If specified, predictions are performed only for the specified response variables. |
draw_ids |
Optional integer vector naming the posterior draws to
plot. |
per_obs |
Logical. For |
series |
For the residual types |
... |
Further arguments of |
Replicates of the training data are drawn under the latent trend
state the model inferred at each time, as residuals.mvgam() and
hindcast.mvgam() use. The check then compares the fitted
trajectory with the series that produced it. Replicates of newdata
use the covariate part of the model, as posterior_predict.mvgam()
does. Passing incl_autocor chooses between the two. The loo_*
types use the fitted state. Their importance weights come from it.
Overlay types default to 10 draws. Interval, ribbon and statistic
types use every draw. The residual histograms and ribbons default to
500 draws, the other residual types to 100 and fit_stat to 500. A
posterior with fewer draws gives all of them.
resid_hist draws one histogram per draw and shows the first eight.
resid_acf and resid_pacf count lags in rows. They refuse a series
observed at unevenly spaced times, such as one a CAR() trend
models. resid_variogram measures lags in time units. It plots half
the mean squared difference of two residuals against the time
between them. Residuals without serial dependence give a flat
semivariogram at their variance, the dashed line (Diggle et al.
2002). plot(type = "residuals") draws it in place of the ACF and pACF for
such a series.
The PPC documentation of
bayesplot describes each ppc_* type. A check restricted to
one series or covariate slice takes newdata filtered to those
rows. A group, such as group = "series", draws one panel per
group through the _grouped variant of the type, so
pp_check(fit, type = "dens_overlay", group = "series") draws
"dens_overlay_grouped". "fit_stat" sums the units of each group.
The single-series residual types ("resid_qq", "resid_vs_fitted",
"resid_acf", "resid_pacf", "resid_variogram") ignore group.
Any other type without a grouped variant refuses it.
A ggplot object. A multivariate model given no resp
returns one figure with a panel per response. type = "fit_stat"
returns an mvgam_ppc_fit_stat object. print() gives its
discrepancy and Bayesian p-value. plot() draws the discrepancy of
each draw's replicates against that of the observations, with the
1:1 line and the p-value.
diri(), multi(), categ(), mvn() and mvt() record several
outcomes per unit. A pooled density would merge them into one
curve. Without a group from the caller, pp_check() draws one
panel per species through the type's _grouped variant. The
default type is "ribbon" for a composition and "dens_overlay"
for mvn() and mvt(). Passing a column of newdata as group
draws the pooled plot.
nmix(), occ())The visits of a closure unit share one latent state. pp_check()
sums the observed and replicated visits of each unit and compares
the sums. The count types (bars, rootogram, hist,
freqpoly), the density and ECDF overlays, the statistic types,
intervals, ribbon, resid_hist and resid_qq apply. Types
that plot rows, residuals against fitted values or residuals over
time are refused. A group or x column must be constant within
each unit. type = "fit_stat" computes the chi-squared or
Freeman-Tukey discrepancy of Gelman et al. (1996) from the unit
sums.
Nicholas J Clark
Diggle, P. J., Heagerty, P., Liang, K.-Y. and Zeger, S. L. (2002). Analysis of Longitudinal Data, 2nd edition. Oxford University Press.
Gabry, J., Simpson, D., Vehtari, A., Betancourt, M. and Gelman, A. (2019). Visualization in Bayesian workflow. Journal of the Royal Statistical Society A, 182:389-402. doi:10.1111/rssa.12378
Gelman, A., Meng, X.-L. and Stern, H. (1996). Posterior predictive assessment of model fitness via realized discrepancies. Statistica Sinica, 6:733-760.
residuals.mvgam() returns the residuals the residual types
plot. CAR() models series observed at unevenly spaced times.
loo.mvgam() scores the fit. The
overview article explains a
rootogram. The N-mixture article runs
the discrepancy check.
Other model checking:
mvgam_diagnostics,
plot.mvgam(),
residuals.mvgam()
## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # A hanging rootogram, on the square-root scale. Each bar shows how # often a count was observed. It hangs from the curve of its expected # frequency under the model. A bar ending below zero marks a count the # model under-predicts pp_check(mod, type = "rootogram", style = "hanging") # Randomised quantile residuals over time. A trend the model missed # shows as serial structure pp_check(mod, type = "resid_ribbon") # Half the mean squared difference of residuals by the time between # them. A flat band at the dashed variance shows no dependence left pp_check(mod, type = "resid_variogram") # Next: plot(mod, type = "residuals") shows the residual grid ## End(Not run)## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # A hanging rootogram, on the square-root scale. Each bar shows how # often a count was observed. It hangs from the curve of its expected # frequency under the model. A bar ending below zero marks a count the # model under-predicts pp_check(mod, type = "rootogram", style = "hanging") # Randomised quantile residuals over time. A trend the model missed # shows as serial structure pp_check(mod, type = "resid_ribbon") # Half the mean squared difference of residuals by the time between # them. A flat band at the dashed variance shows no dependence left pp_check(mod, type = "resid_variogram") # Next: plot(mod, type = "residuals") shows the residual grid ## End(Not run)
Predicts new outcomes, their expectation or the linear predictor
from every posterior draw, for the training data or for new data.
The section 'Which prediction function?' compares predict() with
fitted.mvgam(), hindcast.mvgam() and forecast.mvgam().
## S3 method for class 'mvgam' predict( object, newdata = NULL, type = c("response", "link", "expected", "variance", "terms", "latent_state", "detection"), process_error = FALSE, incl_autocor = FALSE, ndraws = NULL, draw_ids = NULL, re_formula = NULL, allow_new_levels = FALSE, sample_new_levels = "uncertainty", resp = NULL, summary = TRUE, robust = FALSE, probs = c(0.025, 0.975), ... )## S3 method for class 'mvgam' predict( object, newdata = NULL, type = c("response", "link", "expected", "variance", "terms", "latent_state", "detection"), process_error = FALSE, incl_autocor = FALSE, ndraws = NULL, draw_ids = NULL, re_formula = NULL, allow_new_levels = FALSE, sample_new_levels = "uncertainty", resp = NULL, summary = TRUE, robust = FALSE, probs = c(0.025, 0.975), ... )
object |
An object of class |
newdata |
Optional data frame with covariates for prediction. If NULL, uses original training data stored in the model object. |
type |
Character; one of |
process_error |
Logical. Each call draws new innovations. Two calls on one fit give different results. Set a seed to reproduce a result. |
incl_autocor |
Logical. Chooses which version of the trend each
prediction uses. An ELPD or an The default suits a model whose covariates explain most of the
signal. When most of the series-level variation lies in the trend,
as in a fit with few covariates and a strong autoregressive process,
the covariate part has little to say. |
ndraws |
Positive integer specifying number of posterior draws to use. NULL (default) uses all available draws. |
draw_ids |
Optional integer vector selecting a subset of posterior
draw indices to use. NULL (default) uses all draws (subject to
|
re_formula |
Group-level terms to include: |
allow_new_levels |
Logical. |
sample_new_levels |
How a new level's coefficients are drawn:
|
resp |
Character specifying which response variable for multivariate models. NULL (default) returns predictions for all responses. |
summary |
Logical. If |
robust |
Logical. If |
probs |
Numeric vector of probabilities for quantile computation.
Default is |
... |
Unused. Anything passed here is refused. |
type selects the quantity returned:
"response" (default): draws from the posterior predictive
distribution on the outcome scale, from
posterior_predict.mvgam().
"link": the linear predictor on the link scale, from
posterior_linpred.mvgam().
"expected": the expectation E[Y | X] on the response
scale, from posterior_epred.mvgam().
"variance": the conditional variance Var[Y | theta] per
draw, from the family's mean-variance relation. It covers the
gaussian, student, lognormal, poisson, bernoulli, binomial,
negbinomial, gamma and beta families. Other families raise an
error. By default the variance is the observation noise around
the mean of the covariate part. process_error = TRUE also
conditions on each draw's sampled trend innovation.
"terms": refused with a pointer to the functions that
decompose a prediction. posterior_smooths.mvgam() returns
per-smooth draws. fixef.mvgam() and ranef.mvgam() return the
parametric and random-effect components.
"latent_state": for closure-unit families, the posterior of
the latent state of each closure unit given its detection
history:
nmix(): the latent abundance N given the observed
visit counts (Royle 2004).
occ(): the occupancy probability P(z = 1 | y_g).
incl_autocor = TRUE takes the state from the fitted latent
trend, which a joint model shares across species.
"detection": for nmix() and occ(), the per-visit
detection probability on the response scale.
With summary = FALSE, an [ndraws, nobs] matrix of
draws. With summary = TRUE, a matrix with one row per
observation and the columns:
Estimate: the posterior mean, or the median under
robust = TRUE.
Est.Error: the posterior SD, or the MAD under
robust = TRUE.
Q*: one quantile column per value of probs.
A multivariate model with resp = NULL gives a named list of
these, one per response.
Every prediction adds the latent trend to the observation model. The functions differ in the version of the trend they use and in whether they add observation noise.
| Function | Times | Trend by default | Observation noise |
fitted() |
training data | fitted state | no |
predict() |
any | covariate part | under type = "response" |
posterior_predict() |
any | covariate part | yes |
posterior_epred(), posterior_linpred() |
any | covariate part | no |
hindcast() |
training data | fitted state | under type = "response" |
forecast() |
after the training data | fitted state, carried forward | under type = "response" |
residuals(), pp_check() |
training data | fitted state | yes |
The fitted state is the value the trend took at each observed time,
as the model inferred it. The covariate part keeps the effects of the
observation and trend formulas and leaves out the trend's
innovations. Questions about covariates use it, as
conditional_effects.mvgam() and the marginaleffects functions
do. incl_autocor = TRUE switches predict() and the
posterior_*() methods to the fitted state, the default of their
brms counterparts. fitted() uses the covariate part for
newdata.
Royle, J. A. (2004). N-mixture models for estimating population size from spatially replicated counts. Biometrics, 60, 108-115. doi:10.1111/j.0006-341X.2004.00142.x
fitted.mvgam() returns expected values with the inferred
trend state. forecast.mvgam() predicts future times from the
fitted state. conditional_effects.mvgam() plots predictions
against a covariate.
Other predictions:
conditional_effects.mvgam(),
conditional_smooths.mvgam(),
fitted.mvgam(),
hindcast(),
posterior_epred.mvgam(),
posterior_linpred.mvgam(),
posterior_predict.mvgam(),
posterior_smooths.mvgam(),
predictive_error.mvgam(),
predictive_interval.mvgam()
## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # Predicted counts with their 95% intervals head(predict(mod)) # The same fit on the link scale, as an expected count and as the # variance of a count. A Poisson's variance equals its mean. head(predict(mod, type = "link")) head(cbind( expected = predict(mod, type = "expected")[, "Estimate"], variance = predict(mod, type = "variance")[, "Estimate"] )) # `summary = FALSE` returns the draws, one row per draw dim(predict(mod, summary = FALSE)) # Next: forecast() predicts beyond the training times from the # fitted trend state ## End(Not run)## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # Predicted counts with their 95% intervals head(predict(mod)) # The same fit on the link scale, as an expected count and as the # variance of a count. A Poisson's variance equals its mean. head(predict(mod, type = "link")) head(cbind( expected = predict(mod, type = "expected")[, "Estimate"], variance = predict(mod, type = "variance")[, "Estimate"] )) # `summary = FALSE` returns the draws, one row per draw dim(predict(mod, summary = FALSE)) # Next: forecast() predicts beyond the training times from the # fitted trend state ## End(Not run)
Posterior draws of the prediction error, observed minus predicted,
of each observation on the response scale. The arguments are those
of brms::predictive_error.brmsfit().
## S3 method for class 'mvgam' predictive_error( object, newdata = NULL, re_formula = NULL, re.form = NULL, method = "posterior_predict", resp = NULL, ndraws = NULL, draw_ids = NULL, sort = FALSE, ... )## S3 method for class 'mvgam' predictive_error( object, newdata = NULL, re_formula = NULL, re.form = NULL, method = "posterior_predict", resp = NULL, ndraws = NULL, draw_ids = NULL, sort = FALSE, ... )
object |
A fitted mvgam object from |
newdata |
Optional data frame with covariates for prediction. If NULL, uses original training data stored in the model object. |
re_formula |
Group-level terms to include: |
re.form |
The lme4 name for |
method |
|
resp |
Character specifying which response variable for multivariate models. NULL (default) returns predictions for all responses. |
ndraws |
Positive integer specifying number of posterior draws to use. NULL (default) uses all available draws. |
draw_ids |
Optional integer vector selecting a subset of posterior
draw indices to use. NULL (default) uses all draws (subject to
|
sort |
Logical. |
... |
Further arguments of the |
The errors are those residuals.mvgam() returns with
type = "ordinary". In sample, each prediction carries the latent
trend state the model inferred at that time. A prediction for
newdata uses the covariate part of the model, without the trend's
innovations.
An [ndraws, nobs] matrix of observed minus predicted
values.
Nicholas J Clark
brms::predictive_error.brmsfit(), residuals.mvgam(),
posterior_predict.mvgam(), posterior_epred.mvgam().
Other predictions:
conditional_effects.mvgam(),
conditional_smooths.mvgam(),
fitted.mvgam(),
hindcast(),
posterior_epred.mvgam(),
posterior_linpred.mvgam(),
posterior_predict.mvgam(),
posterior_smooths.mvgam(),
predict.mvgam(),
predictive_interval.mvgam()
## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # Observed minus predicted counts, one row per draw err <- predictive_error(mod, draw_ids = 1:200) dim(err) # The three observations with the largest mean absolute error mae <- colMeans(abs(err)) simdat$data_train[order(mae, decreasing = TRUE)[1:3], c("time", "y")] # Next: residuals(mod) returns randomised quantile residuals ## End(Not run)## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # Observed minus predicted counts, one row per draw err <- predictive_error(mod, draw_ids = 1:200) dim(err) # The three observations with the largest mean absolute error mae <- colMeans(abs(err)) simdat$data_train[order(mae, decreasing = TRUE)[1:3], c("time", "y")] # Next: residuals(mod) returns randomised quantile residuals ## End(Not run)
Central quantile intervals of the draws posterior_predict.mvgam()
returns, one per observation.
## S3 method for class 'mvgam' predictive_interval(object, prob = 0.9, ...)## S3 method for class 'mvgam' predictive_interval(object, prob = 0.9, ...)
object |
A fitted |
prob |
Numeric in |
... |
Arguments of |
A numeric matrix with one row per observation and two columns, the lower and upper bounds.
Nicholas J Clark
posterior_interval.mvgam() gives intervals of parameters.
pp_check.mvgam() plots predictive draws against the data.
Other predictions:
conditional_effects.mvgam(),
conditional_smooths.mvgam(),
fitted.mvgam(),
hindcast(),
posterior_epred.mvgam(),
posterior_linpred.mvgam(),
posterior_predict.mvgam(),
posterior_smooths.mvgam(),
predict.mvgam(),
predictive_error.mvgam()
## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # 90 percent intervals, one row per observation intervals <- predictive_interval(mod) head(intervals) # The share of observed counts the intervals cover y <- simdat$data_train$y mean(y >= intervals[, 1] & y <= intervals[, 2]) # Next: pp_check() plots the predictive draws against the data ## End(Not run)## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # 90 percent intervals, one row per observation intervals <- predictive_interval(mod) head(intervals) # The share of observed counts the intervals cover y <- simdat$data_train$y mean(y >= intervals[, 1] & y <= intervals[, 2]) # Next: pp_check() plots the predictive draws against the data ## End(Not run)
Print an mvgam object
## S3 method for class 'mvgam' print(x, ...)## S3 method for class 'mvgam' print(x, ...)
x |
|
... |
Unused. Anything passed here is refused. |
The mvgam object is returned invisibly.
summary.mvgam() summarises the posterior of each
parameter. methods_md() writes the model as equations.
how_to_cite() drafts its methods paragraph.
Holds the two formulas of a model before it is fitted.
get_prior.mvgam_formula(), stancode() and standata() take the
pair, with the data and family, to show the priors, the Stan program
and the data a fit would use. Nothing is compiled or sampled.
## S3 method for class 'mvgam_formula' print(x, ...) mvgam_formula(formula, trend_formula = NULL)## S3 method for class 'mvgam_formula' print(x, ...) mvgam_formula(formula, trend_formula = NULL)
x |
An |
... |
Unused. |
formula |
A |
trend_formula |
A one-sided formula for the latent trend, such
as |
The observation formula takes the brms syntax, with distributional
and non-linear sub-formulas through bf(). It refuses:
a trend constructor such as AR(). It belongs in
trend_formula.
., which would enter the time and series columns as
predictors
rate() and se(). Predictions leave them out. Write an
exposure as offset(log(area)).
subset() and index(). A response leaves rows out by
holding NA there.
the brms autocorrelation terms ar(), ma(), arma(),
cosy(), unstr() and autocor(). Predictions, forecasts and
loo() leave them out. The trend constructor models dependence
over time.
A trend formula holds one trend constructor (trend_constructors),
added as a term of its own, as in ~ x + AR() or
~ x + mvgam::AR(). It also holds covariates of the latent state:
smooths such as s() and
t2(), random effects such as (1 | group) and Gaussian processes
through gp(). lv_axis() in a term varies its effect by latent
factor, or by series in a model without factors. It refuses:
a response, a second trend constructor and bf()
sub-formulas
a constructor inside another term, as in x:AR() or
s(x, by = AR()), or subtracted, as in - AR()
the series column. lv_axis() takes its place.
a response of the observation formula as a covariate
offset() and addition terms such as weights(),
cens(), trunc(), trials() and thres(). They describe how
the response was observed.
mi(), which brms imputes as a response
cs(), which shifts an ordinal response's thresholds
the brms autocorrelation terms
An object of class mvgam_formula holding formula and
trend_formula.
print() shows the two formulas.
A multivariate model, written with mvbind() or bf() + bf(), takes
one trend constructor for all of its responses. Each response can
take its own family and its own observation terms, as in
bf(count ~ x, family = poisson()) + bf(biomass ~ x, family = Gamma(link = "log")). The gr argument of the trend constructor
pools the trends of groups. Responses that need different trend
types need separate models.
get_prior.mvgam_formula() lists the priors of the pair.
stancode() and standata() return its Stan program and data.
mvgam() fits it.
Other model fitting:
check_newdata(),
jsdgam(),
mvgam(),
mvgam_data(),
mvgam_multiple(),
pivot_detection_array(),
pivot_species_matrix(),
series_to_mvgam(),
stancode.mvgam_formula(),
update.mvgam()
f <- mvgam_formula(y ~ s(x), trend_formula = ~ AR(p = 1)) f # Observation weights belong in the observation formula mvgam_formula(y ~ x + weights(w), trend_formula = ~ AR(p = 1)) try(mvgam_formula(y ~ x, trend_formula = ~ AR() + weights(w))) ## Not run: simdat <- sim_mvgam(family = poisson(), n_series = 1L, trend_model = AR()) # The priors and the Stan program a fit would use get_prior(f, data = simdat$data_train, family = poisson()) stancode(f, data = simdat$data_train, family = poisson()) ## End(Not run)f <- mvgam_formula(y ~ s(x), trend_formula = ~ AR(p = 1)) f # Observation weights belong in the observation formula mvgam_formula(y ~ x + weights(w), trend_formula = ~ AR(p = 1)) try(mvgam_formula(y ~ x, trend_formula = ~ AR() + weights(w))) ## Not run: simdat <- sim_mvgam(family = poisson(), n_series = 1L, trend_model = AR()) # The priors and the Stan program a fit would use get_prior(f, data = simdat$data_train, family = poisson()) stancode(f, data = simdat$data_train, family = poisson()) ## End(Not run)
Specify the latent trend of a state-space model. Each constructor
goes inside trend_formula, as in trend_formula = ~ AR(p = 1). A
constructor records its arguments. The model evaluates them against
the data. The trends suit different series:
RW()A level that wanders with no pull back to a mean.
AR()Movement around a mean, with memory of the previous
p times. It is a common first choice.
VAR()Series whose past values drive one another, such as predators and prey.
CAR()An AR(1) for series observed at irregular times.
ZMVN()Correlated effects with no dependence on time, such as among sites or species.
LLT()A level with a slope that changes over time, with an optional season.
PW()Linear or logistic growth with changepoints.
Each trend moves by a random innovation at every time step. Other
texts call it a process error or a shock. The innovations are
independent across series unless cor = TRUE.
## S3 method for class 'mvgam_trend' print(x, ...) RW( time = NA, series = NA, ma = FALSE, cor = NULL, gr = NA, subgr = NA, n_lv = NULL, trend_map = NULL, df = Inf, centred = FALSE ) AR( time = NA, series = NA, p = 1, ma = FALSE, cor = NULL, gr = NA, subgr = NA, n_lv = NULL, trend_map = NULL, coef_sharing = c("none", "shared", "hierarchical"), df = Inf, centred = FALSE ) CAR( time = NA, series = NA, cor = FALSE, n_lv = NULL, trend_map = NULL, df = Inf, centred = FALSE ) VAR( time = NA, series = NA, p = 1, ma = FALSE, cor = TRUE, gr = NA, subgr = NA, n_lv = NULL, trend_map = NULL )## S3 method for class 'mvgam_trend' print(x, ...) RW( time = NA, series = NA, ma = FALSE, cor = NULL, gr = NA, subgr = NA, n_lv = NULL, trend_map = NULL, df = Inf, centred = FALSE ) AR( time = NA, series = NA, p = 1, ma = FALSE, cor = NULL, gr = NA, subgr = NA, n_lv = NULL, trend_map = NULL, coef_sharing = c("none", "shared", "hierarchical"), df = Inf, centred = FALSE ) CAR( time = NA, series = NA, cor = FALSE, n_lv = NULL, trend_map = NULL, df = Inf, centred = FALSE ) VAR( time = NA, series = NA, p = 1, ma = FALSE, cor = TRUE, gr = NA, subgr = NA, n_lv = NULL, trend_map = NULL )
x |
An |
... |
Unused. |
time |
The unquoted name of the |
series |
The unquoted name of the |
ma |
|
cor |
In a factor model with every loading sampled, the factors take
independent shocks. The loadings carry the correlation among
series, which |
gr |
An optional
Here Within a Two constraints apply to hierarchical trend models:
|
subgr |
A subgrouping For example, to model counts of several species (
A region |
n_lv |
The number of latent factors to estimate for dynamic
factor models. When |
trend_map |
Optional map of the series onto the latent processes, which fixes some or all loadings of a dynamic factor model. One of three forms:
Its columns set the number of factors, which an |
df |
Degrees of freedom for the latent process innovations.
Defaults to Finite degrees of freedom let the latent process absorb an
occasional large shock while When Three caveats apply:
|
centred |
Logical. Sample the latent states directly rather
than their innovations? Default |
p |
The autoregressive lags. The accepted form depends on the trend type:
|
coef_sharing |
How the coefficients of |
A trend_formula takes one trend constructor. The arguments of that
constructor express richer dynamics:
For seasonal patterns: AR(p = c(1, 12)). A sum such as
RW() + AR(p = 12) is refused
For several time scales: AR(p = c(1, 7, 30)) for daily,
weekly and monthly lags
For cross-series dynamics: VAR(p = 2)
Centred states: by default the sampler draws standard
innovations and builds the states from them. This suits data that
say little about each state, such as small counts, presence-absence
or short series. When the data pin the states down, as large counts
do, every innovation constrains every later state. The sampler then
takes long trajectories and can hit the maximum tree depth.
centred = TRUE samples each state as its distance from the first
and recovers the innovations from them. On large counts it ran two
to five times faster per effective draw. On small counts it ran ten
to a hundred times slower. ZMVN() factors with sampled loadings
draw their states directly either way. VAR() always does.
Stationarity of AR(p): a consecutive lag set with
p >= 2 is sampled as partial autocorrelations,
ar1_pacf_trend through ark_pacf_trend, each
declared on (-1, 1). The Levinson-Durbin recursion derives
ar1_trend through ark_trend from them. Every
summary, forecast and hypothesis test uses those coefficients.
Any vector of partial autocorrelations in (-1, 1) gives a
stationary process. Bounding the coefficients directly admits
explosive draws. With ar1_trend and ar2_trend both
at 0.9 the declared bounds hold, yet that process grows without
limit. Priors for these models name the ar{k}_pacf_trend
classes.
AR(p = 1) samples ar1_trend directly. At one lag
the declared interval is already the stationary region. A sparse
lag set such as AR(p = c(1, 12)) also samples
ar{k}_trend directly. It fixes its intermediate
coefficients at zero, a constraint the recursion cannot express. It
carries no stationarity guarantee. Both take priors on the
ar{k}_trend classes.
CAR() steps a continuous-time AR(1) over the gaps the data
records. A gap dt is measured in units of the median gap
between two consecutive observations of one series.
ar1_trend and sigma_trend then describe a typical
step. The model is the same whatever unit the time column records.
Across a gap dt the decay is
ar1_trend^dt and the innovation standard deviation is
sigma_trend * sqrt((1 - ar1_trend^(2 dt)) /
(1 - ar1_trend^2)). The decay and the innovation scale together.
The marginal variance is then
sigma_trend^2 / (1 - ar1_trend^2) at every occasion of an
irregular grid. The first state comes from that marginal.
CAR(cor = TRUE) correlates the innovations of several
series. Sigma_trend is their covariance over a gap of one.
Series a and b have stationary covariance
Sigma_trend[a, b] / (1 - ar1_trend[a] * ar1_trend[b]). The
innovations across a gap dt have that covariance times
1 - (ar1_trend[a] * ar1_trend[b])^dt. This is the exact
transition of the continuous-time process. A time point added
between two others leaves the model for the remaining times
unchanged. L_Omega_trend is the Cholesky factor of the
correlation between the series' shocks over an instant. Its prior
is placed there. The correlation of Sigma_trend is
closer to zero than that correlation when the series damp at
different rates. On a regular grid the likelihood is that of
AR(p = 1, cor = TRUE) with positive coefficients.
The series of a CAR() trend may be observed at their own
times. The trend has a state for every series at each time any
series was observed. A series contributes to the likelihood at the
times it has a row. This is the model a frame gives when every
unobserved time of a series has a row with a missing response.
forecast() takes each series at its own future times.
df needs the series on shared times. With one mixing scale
per time, a multivariate t would let the times of one series change
the trend of another.
An object of class mvgam_trend holding the
constructor's arguments. mvgam() builds the trend from it.
print() shows the label a fit would print, such as AR({1, 12}),
with the columns and the settings that differ from their defaults.
Each coef_sharing setting samples its own Stan parameters:
| coef_sharing | Stan parameters with priors |
"none" |
ar{lag}{stem}_trend per series |
"shared" |
shared_ar{lag}{stem}_trend (one per lag) |
"hierarchical" |
mu_ar{lag}{stem}_trend,
sigma_ar{lag}{stem}_trend
|
{stem} is _pacf for a contiguous lag set of two or more
lags, where the sampled quantity is a partial autocorrelation,
and empty for p = 1 and for a sparse lag set such as
p = c(1, 3). AR(p = 2) samples ar1_pacf_trend and
AR(p = 1) samples ar1_trend.
Every setting defines the same ar{lag}_trend[j] in
transformed parameters. Forecasting, IRF, FEVD and summaries use
that quantity whatever the setting. A prior on any sampled
parameter is set with brms::set_prior(class = "<name>").
get_prior(mvgam_formula(...)) lists the parameters the chosen
coef_sharing samples.
Every trend parameter carries a _trend suffix, which keeps it
distinct from an observation model parameter of the same name. The
innovation scale is sigma_trend, the moving-average
coefficient theta1_trend, the autoregressive coefficients
ar1_trend to ark_trend and the VAR coefficient
matrices Phi_trend. Priors take these class names, as in
prior(inv_gamma(5, 1), class = sigma_trend). Parameter
extraction takes the same names.
A factor model with sampled loadings fits equally well under any reordering or sign change of its factors. Some models also fit equally well under any rotation. mvgam reports one version, chosen by the dynamics of the factors:
AR() factors take their own coefficients, as do
RW() and AR() factors with ma = TRUE. A
rotation would mix those coefficients. After sampling, the
factors of every draw are reordered and signed to agree with one
reference. The loadings Z, the factor paths lv_trend and the
coefficients ar1_trend or theta1_trend move together.
Factors are numbered by the variance they explain, largest
first.
RW(), VAR() and ZMVN() factors
without a moving-average term are unchanged by rotation. So are
AR() factors with coef_sharing = "shared" and no
moving-average term.
Following Heaps & Jermyn (2024), generated quantities rotate each
draw to lower-triangular loadings Z_tilde with a non-negative
diagonal. The factor paths rotate to lv_trend_tilde. A VAR
factor model rotates its coefficients to Phi_trend_tilde.
Post-fit methods use the identified loadings and factor paths.
shared_variation() and residual_cor() are the same under every
version.
A trend_map keeps its fixed entries on Z exactly. A
by = lv_axis() smooth ties each factor to its own covariate
effect. Neither takes a rotation. For a model with every loading
sampled, the loadings_prior
argument of mvgam() replaces the default iid Student-t prior
on Z with a structured matrix-normal prior. That prior is built
from per-series features, pairwise distance matrices or both. See
mvgam for its arguments.
Setting loadings_prior = "mgp" (or
loadings_prior = list(column_shrinkage = "mgp")) switches
the column scaling to the multiplicative gamma process prior of
Bhattacharya & Dunson (2011), which shrinks later columns of Z
toward zero with increasing strength. n_lv is then a truncation
ceiling on the factor count. active_factors reports
the posterior distribution of the number of active factors.
VAR fits and init = 0: the stationary map of Heaps
(2023) takes matrix square roots by eigendecomposition. The
gradient of an eigendecomposition divides by differences between
eigenvalues. init = 0 in the call to mvgam() sets every raw
coefficient to zero and every innovation scale to one. Each matrix
the map decomposes is then the identity, with repeated eigenvalues,
and the first gradient is not finite. Leave init at its default
random draws for VAR() fits. AR(), RW(), CAR() and ZMVN()
are unaffected.
Nicholas J Clark
Heaps, S. E. and Jermyn, I. H. (2024). Structured prior distributions for the covariance matrix in latent factor models. Statistics and Computing, 34:143. doi:10.1007/s11222-024-10454-0
Heaps, S. E. (2023). Enforcing stationarity through the prior in vector autoregressions. Journal of Computational and Graphical Statistics, 32(1):74-83. doi:10.1080/10618600.2022.2079648
Clark NJ, Ernest SKM, Senyondo H, Simonis J, White EP, Yenni GM and Karunarathna KANK (2025). Beyond single-species models: leveraging multispecies forecasts to navigate the dynamics of ecological predictability. PeerJ, 13, e18929. https://doi.org/10.7717/peerj.18929
get_prior() lists the parameters a trend adds and their
default priors. residual_cor(), irf(), fevd() and
stability() interpret fitted latent dynamics. forecast()
propagates them forward. The
overview vignette compares
the trend types. The VAR article
interprets a fitted VAR() with irf(), fevd() and
stability(). The
hierarchical VAR article
fits gr and subgr. The
dynamic factor vignette fits n_lv and
trend_map.
Other trend models:
LLT(),
PW(),
ZMVN(),
list_trend_types(),
lv_axis()
## Not run: # A constructor records a trend before any data are seen. Printing # one shows the settings the model will use AR(p = c(1, 12)) VAR(p = 2, ma = TRUE) RW(gr = region, subgr = species) # A regularly spaced series usually starts with AR(p = 1). ?mvgam # fits one. The rest of this example handles irregular sampling. # Three Poisson series with a seasonal cycle, each surveyed at its # own irregular times. sim_mvgam(type = 6L) draws the gaps between # occasions. Every series keeps about 60 percent of the occasions set.seed(11) simdat <- sim_mvgam(type = 6L, family = poisson(), n_series = 3L, n_timepoints = 80L) keep_some <- function(d) d[runif(nrow(d)) < 0.6, ] own_times <- keep_some(simdat$data_train) # The parameters a trend adds, with their default priors, before # any fitting get_prior( mvgam_formula(y ~ s(season, bs = "cc", k = 6), trend_formula = ~ CAR(cor = TRUE)), data = own_times, family = poisson() ) # A continuous-time AR(1) steps each series over its own gaps mod <- mvgam( y ~ s(season, bs = "cc", k = 6), trend_formula = ~ CAR(cor = TRUE), data = own_times, family = poisson(), chains = 2, silent = 2 ) summary(mod) # Correlations among the series' latent states residual_cor(mod) # Residual checks. Each series has gaps of differing length. A # semivariogram by time lag replaces the ACF plot(mod, type = "residuals", series = 2) # Each series is forecast at its own future times plot(forecast(mod, newdata = keep_some(simdat$data_test)), series = 2) # Counts near 150 pin each latent state down. Sampled centred, this # random walk ran about five times faster per effective draw n_t <- 60 big <- data.frame(time = 1:n_t, series = factor("s1"), y = rpois(n_t, exp(5 + cumsum(rnorm(n_t, 0, 0.1))))) mod_big <- mvgam( y ~ 1, trend_formula = ~ RW(centred = TRUE), data = big, family = poisson(), chains = 2, silent = 2 ) summary(mod_big) # Next: hindcast() returns the fitted latent trends. The articles # under 'See Also' fit VAR, hierarchical and factor trends ## End(Not run)## Not run: # A constructor records a trend before any data are seen. Printing # one shows the settings the model will use AR(p = c(1, 12)) VAR(p = 2, ma = TRUE) RW(gr = region, subgr = species) # A regularly spaced series usually starts with AR(p = 1). ?mvgam # fits one. The rest of this example handles irregular sampling. # Three Poisson series with a seasonal cycle, each surveyed at its # own irregular times. sim_mvgam(type = 6L) draws the gaps between # occasions. Every series keeps about 60 percent of the occasions set.seed(11) simdat <- sim_mvgam(type = 6L, family = poisson(), n_series = 3L, n_timepoints = 80L) keep_some <- function(d) d[runif(nrow(d)) < 0.6, ] own_times <- keep_some(simdat$data_train) # The parameters a trend adds, with their default priors, before # any fitting get_prior( mvgam_formula(y ~ s(season, bs = "cc", k = 6), trend_formula = ~ CAR(cor = TRUE)), data = own_times, family = poisson() ) # A continuous-time AR(1) steps each series over its own gaps mod <- mvgam( y ~ s(season, bs = "cc", k = 6), trend_formula = ~ CAR(cor = TRUE), data = own_times, family = poisson(), chains = 2, silent = 2 ) summary(mod) # Correlations among the series' latent states residual_cor(mod) # Residual checks. Each series has gaps of differing length. A # semivariogram by time lag replaces the ACF plot(mod, type = "residuals", series = 2) # Each series is forecast at its own future times plot(forecast(mod, newdata = keep_some(simdat$data_test)), series = 2) # Counts near 150 pin each latent state down. Sampled centred, this # random walk ran about five times faster per effective draw n_t <- 60 big <- data.frame(time = 1:n_t, series = factor("s1"), y = rpois(n_t, exp(5 + cumsum(rnorm(n_t, 0, 0.1))))) mod_big <- mvgam( y ~ 1, trend_formula = ~ RW(centred = TRUE), data = big, family = poisson(), chains = 2, silent = 2 ) summary(mod_big) # Next: hindcast() returns the fitted latent trends. The articles # under 'See Also' fit VAR, hierarchical and factor trends ## End(Not run)
A trend that grows at a constant rate between changepoints, as in
Prophet (Taylor and Letham 2018). Linear growth is unbounded.
Logistic growth saturates at a carrying capacity that data
supplies. The constructor records its arguments. The model
evaluates them against the data.
PW( time = NA, series = NA, cap = NA, n_changepoints = 10, changepoint_range = 0.8, changepoint_scale = 0.3, growth = "linear", n_lv = NULL, trend_map = NULL )PW( time = NA, series = NA, cap = NA, n_changepoints = 10, changepoint_range = 0.8, changepoint_scale = 0.3, growth = "linear", n_lv = NULL, trend_map = NULL )
time |
The unquoted name of the |
series |
The unquoted name of the |
cap |
The unquoted name of the variable in |
n_changepoints |
A positive integer: the number of potential
changepoints, spaced evenly over the first |
changepoint_range |
A number in |
changepoint_scale |
A positive number: the typical change in
growth at one changepoint over the whole series, in link units for
linear growth and in logits for logistic growth. For a series of
|
growth |
|
n_lv, trend_map
|
Factor models are not supported for |
Intercepts:
A linear trend takes its level from the observation formula, as
every other trend in mvgam does. y ~ 1 is its ordinary
observation formula.
A logistic trend contributes cap * inv_logit(...) on the link
scale. Its offset m_trend places the inflection in time. The
expectation saturates at cap when the observation formula omits
its intercept (y ~ -1 or y ~ 0 + ...). An intercept raises the
ceiling above cap.
Priors:
Time runs in steps 1, ..., N. The base growth rate takes
k_trend ~ normal(0, 2 s / (N - 1)), two units of growth over the
series at one standard deviation. The logistic inflection takes
m_trend ~ normal((N + 1) / 2, N / 2), centred on the middle of the
series. get_prior() shows the values for a given model.
The carrying capacity:
A market size, a population size or an ecological carrying capacity
can bound a series. growth = 'logistic' takes it from the cap
column, which can vary by series and by time. Every observation
needs a value. Under a non-identity link the capacity is moved to
the link scale, such as its log under poisson() or
negbinomial(). Give it on the scale of the response.
An object of class mvgam_trend.
Nicholas J Clark
Taylor, S. J. and Letham, B. (2018). Forecasting at scale. The American Statistician, 72, 37-45. doi:10.1080/00031305.2017.1380080
LLT() for a trend whose growth changes continuously.
get_prior() lists the default priors. The
forecast evaluation article
compares a piecewise trend with other trends out of sample.
Other trend models:
LLT(),
ZMVN(),
list_trend_types(),
lv_axis(),
print.mvgam_trend()
## Not run: set.seed(2024) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L) mod <- mvgam( y ~ 1, trend_formula = ~ PW(growth = "linear"), data = simdat$data_train, family = poisson(), chains = 2, silent = 2 ) summary(mod) # The base growth rate and the rate change at each changepoint mcmc_plot(mod, variable = "trend_params") # The forecast continues the growth rate of the last changepoint plot(forecast(mod, newdata = simdat$data_test)) # Next, score() rates the forecast against the held-out points ## End(Not run)## Not run: set.seed(2024) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L) mod <- mvgam( y ~ 1, trend_formula = ~ PW(growth = "linear"), data = simdat$data_train, family = poisson(), chains = 2, silent = 2 ) summary(mod) # The base growth rate and the rate change at each changepoint mcmc_plot(mod, variable = "trend_params") # The forecast continues the growth rate of the last changepoint plot(forecast(mod, newdata = simdat$data_test)) # Next, score() rates the forecast against the held-out points ## End(Not run)
Posterior draws of each level's deviation for every group-level term
of the observation formula, summarised or raw. Each element is named
r_<group>[<level>,<coef>], as variables.mvgam() lists it.
## S3 method for class 'mvgam' ranef( object, summary = TRUE, robust = FALSE, probs = c(0.025, 0.975), pars = NULL, groups = NULL, ... )## S3 method for class 'mvgam' ranef( object, summary = TRUE, robust = FALSE, probs = c(0.025, 0.975), pars = NULL, groups = NULL, ... )
object |
A fitted |
summary |
Logical. |
robust |
Logical. If |
probs |
Two probabilities for the lower and upper bounds of the
credible interval. Default |
pars |
Optional character vector of coefficient names, such as
|
groups |
Optional character vector of grouping factors. |
... |
Unused. Anything passed here is refused. |
A group-level term in trend_formula is named with the _trend
suffix, as r_g_trend[a,Intercept]. as_draws.mvgam() returns its
draws.
A named list with one 3D array per grouping factor. With
summary = TRUE the dimensions are levels, statistics and
coefficients. The statistics are Estimate, Est.Error and one
quantile per element of probs. With summary = FALSE the
dimensions are draws, levels and coefficients, and the array
carries an nchains attribute. A grouping factor of a
distributional parameter or of one response of several is keyed
<group>__<parameter>.
Nicholas J Clark
VarCorr.mvgam() summarises the standard deviations and
correlations. fixef.mvgam() summarises the population-level
effects.
Other posterior summaries:
VarCorr.mvgam(),
bibtex(),
how_to_cite.mvgam(),
hypothesis.mvgam(),
index-mvgam,
mcmc_plot.mvgam(),
methods_md(),
mvgam_draws,
pairs.mvgam(),
posterior_interval.mvgam(),
smooths.mvgam(),
summary.mvgam()
## Not run: set.seed(14) simdat <- sim_mvgam(family = poisson(), n_series = 4L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5) + (1 | series), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # Each series' intercept deviation, one row per series ranef(mod)$series[, , "Intercept"] # Next: VarCorr() gives the standard deviation of these deviations ## End(Not run)## Not run: set.seed(14) simdat <- sim_mvgam(family = poisson(), n_series = 4L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5) + (1 | series), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # Each series' intercept deviation, one row per series ranef(mod)$series[, , "Intercept"] # Next: VarCorr() gives the standard deviation of these deviations ## End(Not run)
Posterior correlations, covariances and optional partial correlations
between the series' latent trends. Residual here means the
co-variation of the trends left once the covariate effects are
accounted for. residuals.mvgam() returns the observation
residuals. Three kinds of trend estimate these correlations:
A factor trend (n_lv on the trend constructor). Each draw
gives the series covariance Z Omega Z', with Z the loadings
and Omega the covariance of the latent states. mvn() and
mvt() add each series' residual variance to the diagonal:
Psi^2, or Psi^2 * nu / (nu - 2) under mvt().
A trend with correlated innovations: RW(), AR(), CAR()
or ZMVN() with cor = TRUE, or VAR().
A hierarchical trend (gr on the trend constructor).
residual_cor(object, ...) ## S3 method for class 'mvgam' residual_cor( object, covariance = c("stationary", "innovation"), by_group = FALSE, partial = FALSE, summary = TRUE, robust = FALSE, probs = c(0.025, 0.975), prob_threshold = 0.95, ndraws = NULL, draw_ids = NULL, ... )residual_cor(object, ...) ## S3 method for class 'mvgam' residual_cor( object, covariance = c("stationary", "innovation"), by_group = FALSE, partial = FALSE, summary = TRUE, robust = FALSE, probs = c(0.025, 0.975), prob_threshold = 0.95, ndraws = NULL, draw_ids = NULL, ... )
object |
A fitted |
... |
Unused. Anything passed here is refused. |
covariance |
Which covariance to summarise. |
by_group |
Logical, for a hierarchical trend. |
partial |
Logical. |
summary |
Logical. |
robust |
Logical. If |
probs |
Two probabilities for the lower and upper bounds of the
credible interval. Default |
prob_threshold |
The posterior probability of its sign a
correlation needs to count as supported, at least 0.5 and below 1.
Defaults to 0.95. It sets |
ndraws |
Positive integer specifying number of posterior draws to use. NULL (default) uses all available draws. |
draw_ids |
Optional integer vector selecting a subset of posterior
draw indices to use. NULL (default) uses all draws (subject to
|
A correlated-innovation trend gives each draw the covariance
diag(sigma) L_Omega L_Omega' diag(sigma). A VAR() trend takes the
leading block of Omega_trend, the stationary covariance the Stan
model derives from Phi_trend, Sigma_trend and, under ma = TRUE,
Theta_trend.
The stationary covariance describes the states over the whole series.
An AR(cor = TRUE) trend reports the stationary covariance of its
states, including any moving-average term. With one lag it is
Sigma[a, b] / (1 - ar_a * ar_b). A CAR()
trend holds it at every time of an irregular grid. A draw whose
autoregression is explosive has no stationary covariance and keeps
its innovation covariance. A warning gives the count once per session.
ZMVN() keeps no memory between times and RW() and LLT() have no
stationary distribution. Each reports its innovation covariance. The
level, slope and seasonal shocks of LLT() share its correlation. A
hierarchical AR() converts each group's scales to stationary scales
in the same way, before its global and group correlations are mixed.
Under covariance = "innovation" a VAR() fit reports the
contemporaneous shocks. Its transition matrix spreads each shock
across series at every step. The two correlations can differ
substantially.
Intervals and spreads of correlations are computed on the Fisher-z
scale, atanh(r), then back-transformed. The intervals stay inside
(-1, 1). The reported matrix summarises each entry
separately. It need not be positive semi-definite, most visibly when
a few factors drive many series. A computation that factorises the
matrix, such as chol(), takes summary = FALSE, whose per-draw
matrices are valid correlation matrices. prob_positive and
prob_negative are posterior sign probabilities. prob_nonzero is
the larger of the two. sig_cor keeps the correlations whose
prob_nonzero exceeds prob_threshold. Its other entries are zero.
jsdgam() fits the same factor model. Its species covariance follows
the factor rule above.
An mvgam_residcor object. Under by_group = TRUE on a
hierarchical trend, an mvgam_residcor_list of them: the population
matrix as "_global" and one per group.
plot.mvgam_residcor_list() draws them as faceted heatmaps.
Hui, F. K. C. (2016). boral - Bayesian Ordination and Regression Analysis of Multivariate Abundance Data in R. Methods in Ecology and Evolution, 7(6), 744-750. doi:10.1111/2041-210X.12514
plot.mvgam_residcor() draws the matrix as a heatmap.
community() gives the same associations as excess co-occurrence.
species_effects() gives the responses to the covariates these
correlations are net of.
summary.mvgam_residcor() lists the pairs. ordinate() draws the
loadings as a biplot. The example of trend_constructors takes
the correlations of a CAR(cor = TRUE) trend. The
joint species distribution article
interprets species correlations from a factor model.
Other latent dynamics:
active_factors(),
compare_loadings(),
fevd.mvgam(),
irf.mvgam(),
ordinate(),
posterior_transition_matrix(),
shared_variation(),
stability.mvgam()
## Not run: # Detections of 6 species whose occupancy shares two latent factors simdat <- sim_closure_unit_data(family = occ(), n_species = 6L, n_sites = 80L, n_visits = 4L, n_lv = 2L, seed = 1L) mod <- jsdgam(formula = bf(y ~ series * env, p ~ series + tod_c), factor_formula = ~ -1, data = simdat$data_train, family = occ(), n_lv = 2L, chains = 2, silent = 2) # Species correlations after the fixed effects rc <- residual_cor(mod) round(rc$cor, 2) plot(rc) # Next: summary(rc) lists the pairs by posterior sign probability ## End(Not run)## Not run: # Detections of 6 species whose occupancy shares two latent factors simdat <- sim_closure_unit_data(family = occ(), n_species = 6L, n_sites = 80L, n_visits = 4L, n_lv = 2L, seed = 1L) mod <- jsdgam(formula = bf(y ~ series * env, p ~ series + tod_c), factor_formula = ~ -1, data = simdat$data_train, family = occ(), n_lv = 2L, chains = 2, silent = 2) # Species correlations after the fixed effects rc <- residual_cor(mod) round(rc$cor, 2) plot(rc) # Next: summary(rc) lists the pairs by posterior sign probability ## End(Not run)
Posterior draws of the residuals of a fitted mvgam model, of two
types:
"quantile" (default): randomised quantile residuals (Dunn and
Smyth 1996), also called Dunn-Smyth or PIT residuals. Each
observation passes through the distribution function of its
predictive distribution, then through the standard normal quantile
function. Under a correctly specified model the residuals are
independent N(0, 1) draws for any response family.
"ordinary": the predictive error, y minus a
posterior_predict.mvgam() draw, per draw.
In sample, both types compare each observation with predictions that
condition on the latent trend state the model inferred at that time,
the state hindcast.mvgam() returns. For newdata the fit has no
such state. The predictions then use the covariate part of the
model, without the trend's innovations. Passing
process_error = TRUE adds them. pp_check.mvgam() and
predictive_error.mvgam() use the same predictions.
Pearson residuals are not supported. A Pearson residual of a count or a bounded response is skewed and discrete even under a correctly specified model.
## S3 method for class 'mvgam' residuals( object, newdata = NULL, type = c("quantile", "ordinary"), ndraws = NULL, draw_ids = NULL, summary = TRUE, robust = FALSE, probs = c(0.025, 0.975), ... )## S3 method for class 'mvgam' residuals( object, newdata = NULL, type = c("quantile", "ordinary"), ndraws = NULL, draw_ids = NULL, summary = TRUE, robust = FALSE, probs = c(0.025, 0.975), ... )
object |
A fitted |
newdata |
Optional |
type |
Character. Either |
ndraws |
Positive integer specifying number of posterior draws to use. NULL (default) uses all available draws. |
draw_ids |
Optional integer vector selecting a subset of posterior
draw indices to use. NULL (default) uses all draws (subject to
|
summary |
Logical. |
robust |
Logical. If |
probs |
Two probabilities for the lower and upper quantile
columns of the summary. Default |
... |
Further arguments of |
Each draw places an observation in a PIT interval
[lower, upper]. The residual is qnorm(u) for a u drawn
uniformly from that interval. Two routes give the interval.
The analytic route evaluates the family's distribution function at
each draw's parameters. A discrete family gives the interval of the
observed atom, [F(y - 1), F(y)]. A continuous family gives the
point F(y). A tweedie() zero gives [0, F(0)]. Censored rows
span their censoring interval. A truncated model renormalises over
its truncation bounds. log_lik.mvgam() takes its density from the
same parameterisation. The route covers gaussian, student,
asym_laplace, lognormal, gamma, weibull, exponential,
beta, bernoulli, binomial, beta_binomial, poisson,
negbinomial, geometric, com_binomial(), beta_nb(),
tweedie(), the ordinal families, and the multivariate mvn(),
mvt(), diri(), multi() and categ(). A composition family uses
the marginal of one component: a Beta for diri(), a Binomial
against the site's own total for multi() and a Bernoulli for
categ().
Every other family takes the empirical route, among them the
zero-inflated, hurdle and mixture families, occ() and nmix().
Under the model the observation and the n pooled
posterior_predict.mvgam() draws are exchangeable. The rank of the
observation among those n + 1 values, with ties broken at random,
is then uniform. The bounds are sum(yrep < y) / (n + 1) and
(sum(yrep <= y) + 1) / (n + 1). An observation beyond every draw
takes the top interval, [n / (n + 1), 1]. The pooled predictive
carries the posterior uncertainty in the latent state. Its residuals
are narrower than N(0, 1). A QQ-plot of them is conservative.
The PIT value is clamped to [eps, 1 - eps], with
eps = .Machine$double.eps, to keep the residual finite. The clamp
bounds a residual at about +/-8.13. On the analytic route one draw
can place an observation beyond that bound. Such isolated values
describe that draw. A misfit shifts the residual across most draws.
With summary = FALSE, an [ndraws, nobs] matrix of residual
draws. With summary = TRUE,
an [nobs, 2 + length(probs)] matrix. Its columns are Estimate
(the mean, or the median with robust = TRUE), Est.Error (the
standard deviation, or the MAD) and one quantile per probs.
mvn(), mvt(), diri())Each row of a unit gets its own residual. Residuals of mvn() and
mvt() condition on the latent factor scores and test the
observation model. They stay N(0, 1) when the fit has too few
factors. active_factors() and residual_cor.mvgam() judge the
number of factors.
A diri() residual is the exact marginal of one component,
Beta(alpha_j, alpha_0 - alpha_j). Each is N(0, 1) on its own.
Because the shares of a unit sum to one, the residuals of a unit of
K species are negatively dependent, with K - 1 degrees of
freedom. With K = 2 the two residuals are exactly antithetic.
Judge a QQ-plot or an ACF at the unit grain.
nmix(), occ())Visits within a closure unit (site by season) share the latent state,
N for nmix() and z for occ(). The visits are independent
given that state, but dependent marginally. Because residuals per
visit would carry that dependence into every diagnostic,
residuals() returns one residual per closure unit. The observed
counts or detections are summed within each unit. The visit-level
posterior_predict.mvgam() draws are summed the same way. Columns
(summary = FALSE) or rows (summary = TRUE) are labelled by the
unit's grouping values joined with _.
Each draw simulates the latent state from lambda or psi without
conditioning on the unit's detection history. The residuals then
test the model across the population of units.
predict(type = "latent_state") gives the state given each unit's
detection history.
Under occ() a unit sum takes values in 0, ..., n_rep. With few
visits the empirical PIT has coarse support. QQ-plot tails then look
heavier than N(0, 1) under a correctly specified model. A
once-per-session warning is raised when any unit has 4 or fewer visits.
Compare QQ-plots with envelopes simulated from N(0, 1) in that case.
Nicholas J Clark
Dunn, P. K. and Smyth, G. K. (1996). Randomized quantile residuals. Journal of Computational and Graphical Statistics, 5(3), 236-244.
augment.mvgam(), posterior_predict.mvgam(),
pp_check.mvgam()
Other model checking:
mvgam_diagnostics,
plot.mvgam(),
pp_check.mvgam()
## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # Quantile residuals summarised per observation r <- residuals(mod) head(r) # One draw of the residuals should look like N(0, 1) draws r1 <- residuals(mod, summary = FALSE, draw_ids = 1) qqnorm(r1[1, ]) qqline(r1[1, ]) # Next: plot(mod, type = "residuals") draws the QQ-plot, ACF and # residuals against fitted values over many draws. A series observed # at unevenly spaced times gets a semivariogram in place of the ACF ## End(Not run)## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # Quantile residuals summarised per observation r <- residuals(mod) head(r) # One draw of the residuals should look like N(0, 1) draws r1 <- residuals(mod, summary = FALSE, draw_ids = 1) qqnorm(r1[1, ]) qqline(r1[1, ]) # Next: plot(mod, type = "residuals") draws the QQ-plot, ACF and # residuals against fitted values over many draws. A series observed # at unevenly spaced times gets a semivariogram in place of the ACF ## End(Not run)
mvgam_forecast objectsScores the held-out forecasts of an mvgam_forecast object from
forecast.mvgam() or hindcast.mvgam() against the observations,
with one of eleven scoring rules. Lower scores are better.
score(object, ...) ## S3 method for class 'mvgam_forecast' score( object, score = "crps", interval_width = 0.9, quantile_level = 0.5, lower = -Inf, upper = Inf, log = FALSE, weights = NULL, ... ) ## S3 method for class 'mvgam_score' print(x, digits = 2L, ...)score(object, ...) ## S3 method for class 'mvgam_forecast' score( object, score = "crps", interval_width = 0.9, quantile_level = 0.5, lower = -Inf, upper = Inf, log = FALSE, weights = NULL, ... ) ## S3 method for class 'mvgam_score' print(x, digits = 2L, ...)
object |
An |
... |
Unused. Anything passed here is refused. |
score |
Character; one of the names under 'Available scores'.
|
interval_width |
Width of the central interval that sets the
per-series |
quantile_level |
Level of the |
lower, upper
|
Thresholds of |
log |
Logical. |
weights |
Optional numeric vector of non-negative weights, one
per series, for |
x |
An |
digits |
Integer number of significant digits. Defaults to 2. |
An object of class mvgam_score: a named list with one data
frame per series plus a trailing all_series summary. Its print()
method shows the mean score and interval coverage of each series.
A multivariate model gives one such object per response. Each
series' data frame has columns score, in_interval,
interval_width, eval_horizon and score_type, which names the
requested score. A joint score leaves the per-series score
column NA.
For a univariate score, all_series sums the scores over the
series at each forecast time, with score_type prefixed "sum_".
Series forecast at their own times, as CAR() allows, are summed at
the times they share. Its eval_horizon then counts the times any
series is forecast at. For a joint score, all_series holds the
score at each horizon. A joint score needs every series at the same
forecast times.
"crps"Continuous ranked probability score (Gneiting and Raftery 2007) of the empirical distribution of the draws.
"drps"Discrete ranked probability score, the CRPS of a count summed over its integer support.
"sis"Scaled interval score: the width of the central
interval plus a penalty for an observation outside it, scaled by
2 / (1 - interval_width).
"brier"Brier score of a binary outcome: the squared difference between the observation and the mean of the draws.
"logs"Log score, -log f(y) for a kernel density
estimate of the draws.
"dss"Dawid-Sebastiani score, which depends on the predictive mean and standard deviation alone.
"qs"Quantile (pinball) score at quantile_level.
"twcrps"Threshold-weighted CRPS, which scores the
forecast inside [lower, upper].
"energy"Energy score of the series jointly.
"variogram"Variogram score of order 0.5 of the series jointly (Scheuerer and Hamill 2015).
"twenergy"Threshold-weighted energy score.
Gneiting, T. and Raftery, A. E. (2007). Strictly Proper Scoring Rules, Prediction, and Estimation. Journal of the American Statistical Association, 102(477), 359-378. doi:10.1198/016214506000001437
Scheuerer, M. and Hamill, T. M. (2015). Variogram-based proper scoring rules for probabilistic forecasts of multivariate quantities. Monthly Weather Review, 143(4), 1321-1334. doi:10.1175/MWR-D-14-00269.1
forecast.mvgam() produces the forecast.
compare_scores() scores several forecasts with one rule.
ensemble.mvgam_forecast() combines forecasts. The
forecast evaluation article
compares models by their scores at each horizon.
Other forecasting:
compare_scores(),
ensemble.mvgam_forecast(),
forecast.mvgam(),
forecast_uncertainty(),
hindcast(),
lfo_cv.mvgam()
## Not run: set.seed(11) simdat <- sim_mvgam(family = poisson(), n_series = 2L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, seed = 3, silent = 2) # Forecast the held-out times, then score each series fc <- forecast(mod, newdata = simdat$data_test) sc <- score(fc, score = "drps") head(sc$series_1) # The DRPS summed over series at each forecast horizon library(ggplot2) ggplot(sc$all_series, aes(eval_horizon, score)) + geom_line(colour = "#8F2727") + geom_point(colour = "#8F2727") + labs(x = "Horizon", y = "DRPS summed over series") + mvgam_theme() # A joint score of both series at each horizon head(score(fc, score = "energy")$all_series) # Next: compare_scores() ranks several models by one rule ## End(Not run)## Not run: set.seed(11) simdat <- sim_mvgam(family = poisson(), n_series = 2L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, seed = 3, silent = 2) # Forecast the held-out times, then score each series fc <- forecast(mod, newdata = simdat$data_test) sc <- score(fc, score = "drps") head(sc$series_1) # The DRPS summed over series at each forecast horizon library(ggplot2) ggplot(sc$all_series, aes(eval_horizon, score)) + geom_line(colour = "#8F2727") + geom_point(colour = "#8F2727") + labs(x = "Horizon", y = "DRPS summed over series") + mvgam_theme() # A joint score of both series at each horizon head(score(fc, score = "energy")$all_series) # Next: compare_scores() ranks several models by one rule ## End(Not run)
Lays out the posterior season of an LLT() trend by position
within its period. It reports the size of the seasonal swing and
where in the period it peaks, cycle by cycle. With newdata the
season continues into the forecast horizon. The season is part of
the latent trend, on the link scale. scale reports it on the scale
of the expected value.
seasonality(object, ...) ## S3 method for class 'mvgam' seasonality( object, newdata = NULL, ..., ndraws = NULL, draw_ids = NULL, scale = c("link", "expected", "ratio"), resp = NULL ) ## S3 method for class 'mvgam_seasonality' summary(object, probs = c(0.025, 0.975), ...) ## S3 method for class 'mvgam_seasonality' print(x, digits = 2L, ...) ## S3 method for class 'mvgam_seasonality' plot( x, type = c("profile", "positions"), period = NULL, series = NULL, cycles = NULL, prob = 0.9, ... )seasonality(object, ...) ## S3 method for class 'mvgam' seasonality( object, newdata = NULL, ..., ndraws = NULL, draw_ids = NULL, scale = c("link", "expected", "ratio"), resp = NULL ) ## S3 method for class 'mvgam_seasonality' summary(object, probs = c(0.025, 0.975), ...) ## S3 method for class 'mvgam_seasonality' print(x, digits = 2L, ...) ## S3 method for class 'mvgam_seasonality' plot( x, type = c("profile", "positions"), period = NULL, series = NULL, cycles = NULL, prob = 0.9, ... )
object |
A fitted |
... |
Unused. Anything passed here is refused. |
newdata |
Optional data frame of future times, as
|
ndraws, draw_ids
|
The posterior draws to use, as
|
scale |
|
resp |
The response to report, needed on a model with several. |
probs |
Interval probabilities of the tables. Defaults to
|
x |
An |
digits |
Number of decimal places to print. Defaults to |
type |
|
period |
Which period to draw when the trend has several, by
its name such as |
series |
For |
cycles |
For |
prob |
For |
Positions. A position counts steps within one period. Data from
series_to_mvgam() carry a season column, or one season_<period>
column per period, counted from the calendar. Position 1 of a
twelve-month period is then January. A twelve-step period is
labelled by month and a four-step one by quarter. Without the
column, position 1 is the first fitted time and later times continue
from it.
Cycles. A cycle is one pass through the period. A cycle that holds every position is complete. Only complete cycles are summarised.
Amplitude and peak. The amplitude of a cycle is half the range of the season within it. Its peak is the position of the largest value. Both are computed draw by draw. A change between the first and the last complete cycle then comes with its posterior probability.
Strength. The strength of a fitted cycle is the season's share of
the variance of the link predictor over that cycle:
Var(season) / (Var(season) + Var(predictor less season)), computed
draw by draw. It runs from 0 to 1 on every scale. A cycle spans
little of the level's long-run drift, which leaves the season's
share visible in a series dominated by that drift. A cycle reaching
the forecast has no strength: its predictor mixes the season with
fresh innovations.
Scale. The expected value comes from the fit's own family, draw by draw, with every other part of the predictor at its fitted or forecast value. Under a non-linear link the response-scale season then moves with the level. Its amplitude can grow while the latent season stays fixed.
A trend with several periods, such as LLT(season = c(7, 365.25)),
reports each period's season separately.
An object of class mvgam_seasonality. print() gives each
series' amplitude and peak in its first and last complete cycles.
summary() returns five tables: profile, amplitude, peak,
strength and change, the last comparing the first and last
complete cycles.
plot() draws the profile by position, or one panel per position
over the cycles.
Nicholas J Clark
LLT() for the seasonal model, series_to_mvgam() for
the calendar positions, forecast.mvgam() with
component = "season" for the season along time
## Not run: # Monthly airline passengers, the final year held out. Counts in the # hundreds determine each month's state closely. Centred states then # sample better than the default non-centred ones. air <- series_to_mvgam(AirPassengers, h = 12) mod <- mvgam( y ~ 1, trend_formula = ~ LLT(season = 12, harmonics = 3, centred = TRUE), data = air$data_train, family = poisson(), chains = 2, seed = 1, silent = 2 ) # Amplitude and peak month, first and last complete year s <- seasonality(mod, newdata = air$data_test) s # The season by month in the first, last and forecast years plot(s) # Each month's effect over the years and into the forecast plot(s, type = "positions") # How the swing and its peak changed between the first and last year summary(s)$change # The season as a multiple of the expected passenger count plot(seasonality(mod, scale = "ratio")) ## End(Not run)## Not run: # Monthly airline passengers, the final year held out. Counts in the # hundreds determine each month's state closely. Centred states then # sample better than the default non-centred ones. air <- series_to_mvgam(AirPassengers, h = 12) mod <- mvgam( y ~ 1, trend_formula = ~ LLT(season = 12, harmonics = 3, centred = TRUE), data = air$data_train, family = poisson(), chains = 2, seed = 1, silent = 2 ) # Amplitude and peak month, first and last complete year s <- seasonality(mod, newdata = air$data_test) s # The season by month in the first, last and forecast years plot(s) # Each month's effect over the years and into the forecast plot(s, type = "positions") # How the swing and its peak changed between the first and last year summary(s)$change # The season as a multiple of the expected passenger count plot(seasonality(mod, scale = "ratio")) ## End(Not run)
Convert a tsibble, a ts, mts or msts object, or a wide
data.frame with a date column into the long data.frame that
mvgam() expects: one row per series and time, a series factor
and a time column counting steps from the first index value.
series_to_mvgam( series, freq = NULL, response = NULL, index = NULL, h = NULL, train_prop = NULL )series_to_mvgam( series, freq = NULL, response = NULL, index = NULL, h = NULL, train_prop = NULL )
series |
The data to convert. One of:
|
freq |
Optional numeric vector of seasonal periods, in time
steps. Each period above 1 adds a column giving the position of
each row within that period. Defaults to the periods the object
carries: |
response |
Name of the measured variable to use as the response
of a |
index |
Name of the date column of a wide |
h |
Optional number of final time steps to hold out as test data. |
train_prop |
Optional proportion of time steps to keep as
training data, between 0 and 1. Only one of |
time counts steps from 1 at the first index value. The
position within a seasonal period counts steps from the calendar
origin of the index. A monthly index with freq = 12 gives the
month number whatever month the data start in. A ts gives
cycle(). A single period produces a column named season. Several
periods produce season_<period> columns, such as season_7 and
season_365.25.
Rows for future times with a missing response, built for example
with tsibble::new_data() and bound to the observed data, receive
time values that continue the grid. Converting observed and
future rows together keeps the two aligned.
Seasonal periods take the same numbers across packages. Monthly
data carry frequency = 12 in a ts. A fable
season(period = "year") on a monthly tsibble resolves to 12
steps. Both take freq = 12. Daily data with
seasonal.periods = c(7, 365.25) in an msts take
freq = c(7, 365.25).
A season column feeds a fixed seasonal shape, such as
s(season, bs = "cc"). The same periods give LLT() a season
whose shape drifts over the years, as
trend_formula = ~ LLT(season = 12).
A long data.frame. Its columns are series (a factor),
time (an integer for regular data), the response and the original
index (index for a ts). Any tsibble key and covariate columns
follow, then one season column per period above 1. Rows are ordered
by time, then series. With h or train_prop, a list holding
data_train and data_test instead.
Nicholas J Clark
The
data article covers the long format
and its conversion in more depth. LLT() takes the same periods
for a season that drifts.
Other model fitting:
check_newdata(),
jsdgam(),
mvgam(),
mvgam_data(),
mvgam_multiple(),
pivot_detection_array(),
pivot_species_matrix(),
print.mvgam_formula(),
stancode.mvgam_formula(),
update.mvgam()
# Monthly airline passengers, holding out the final year air <- series_to_mvgam(AirPassengers, h = 12) head(air$data_train) # Two series in one mts deaths <- series_to_mvgam(cbind(male = mdeaths, female = fdeaths)) levels(deaths$series) # A wide data.frame with a date column. Converting dates needs the # tsibble package. if (requireNamespace("tsibble", quietly = TRUE)) { wide <- data.frame( date = seq(as.Date("2024-01-01"), by = "day", length.out = 28), site_a = rpois(28, 5), site_b = rpois(28, 8) ) head(series_to_mvgam(wide)) } # Next: fit the training data, for example with # mvgam(y ~ s(season, bs = "cc"), trend_formula = ~ AR(), # data = air$data_train)# Monthly airline passengers, holding out the final year air <- series_to_mvgam(AirPassengers, h = 12) head(air$data_train) # Two series in one mts deaths <- series_to_mvgam(cbind(male = mdeaths, female = fdeaths)) levels(deaths$series) # A wide data.frame with a date column. Converting dates needs the # tsibble package. if (requireNamespace("tsibble", quietly = TRUE)) { wide <- data.frame( date = seq(as.Date("2024-01-01"), by = "day", length.out = 28), site_a = rpois(28, 5), site_b = rpois(28, 8) ) head(series_to_mvgam(wide)) } # Next: fit the training data, for example with # mvgam(y ~ s(season, bs = "cc"), trend_formula = ~ AR(), # data = air$data_train)
Simulates single-season data for the closure-unit families, occ()
and the nmix() variants. Each covariate recipe holds per-site
covariates for the latent state and per-visit covariates for
detection. data_train is the long frame mvgam() and jsdgam()
take. y_array is the four-dimensional layout of
pivot_detection_array(). truth holds every generative parameter
for recovery checks.
sim_closure_unit_data( type = 1L, family = occ(), n_species = 1L, n_sites = 30L, n_visits = 4L, n_lv = 0L, K_max = 30L, seed = NULL ) ## S3 method for class 'mvgam_sim_closure_unit' summary(object, ...) ## S3 method for class 'mvgam_sim_closure_unit_summary' print(x, digits = 3L, ...)sim_closure_unit_data( type = 1L, family = occ(), n_species = 1L, n_sites = 30L, n_visits = 4L, n_lv = 0L, K_max = 30L, seed = NULL ) ## S3 method for class 'mvgam_sim_closure_unit' summary(object, ...) ## S3 method for class 'mvgam_sim_closure_unit_summary' print(x, digits = 3L, ...)
type |
Integer in |
family |
A closure-unit family: |
n_species |
Integer number of species. Defaults to |
n_sites |
Integer number of closure units per species. Defaults
to |
n_visits |
Integer number of visits to every closure unit.
Defaults to |
n_lv |
Integer number of latent factors shared by the species'
state intercepts. Defaults to |
K_max |
Integer cap on the latent abundance |
seed |
Optional integer seed. The session's random state is restored when the call returns. |
object |
A |
... |
Unused. Anything passed here is refused. |
x |
A |
digits |
Integer number of significant digits. Defaults to 3. |
type = 1State predictor b0 + b1 * env, with
env ~ N(0, 1) per site. Detection predictor c0 + c1 * tod_c,
with tod_c ~ U(-6, 6) per visit, a centred time of day.
type = 2State predictor b0 + b1 * env + b2 * elev, with
env and elev each N(0, 1) per site. Detection predictor
c0 + c1 * tod_c + c2 * effort, with tod_c ~ U(-6, 6) and
effort ~ U(0.5, 1.5) per visit.
Each predictor is on the scale of the family's own link. The state
predictor takes the logit for occ() and the log for every nmix()
variant, where it sets the Poisson abundance mean lambda. The
detection predictor takes the logit for occ(),
nmix("poisson_binomial") and nmix("royle_nichols"). It takes the
log for nmix("poisson_poisson"), whose encounter rate rho is
unbounded.
Each species draws an intercept from a normal with mean zero. Each covariate draws one community mean. Each species then draws its slope around that mean. The standard deviations are:
| Predictor | Intercept | Community mean | Species slope |
occ() state |
0.75 | 1.5 | 0.5 |
nmix() state |
0.5 | 0.4 | 0.3 |
| Detection | 0.5 | 0.2 | 0.15 |
The nmix() state scales keep lambda well below K_max. The
detection scales keep detection away from 0 and 1 across the range of
tod_c.
A list of class c("mvgam_sim_closure_unit", "mvgam_sim"):
data_trainLong data.frame. Its columns are series
(the species), site, time (the site, which identifies the
closure unit in a single season), visit, y, the site and
visit covariates, then cap: 1 for occ(), K_max for
nmix().
data_testNULL. Closure-unit data have no held-out
times.
y_arrayInteger array
[n_species, n_sites, 1, n_visits] for
pivot_detection_array().
family, type
The family and recipe.
n_species, n_sites, n_visits, n_lv
The simulation dimensions.
truthThe generative parameters. See Truth bundle.
With n_lv > 0L, the state predictor of species k at site i
gains sum_l Z[k, l] * lv[i, l]. The [n_species x n_lv]
loadings Z are normal with standard deviation 0.7. The
[n_sites x n_lv] factor scores lv are standard normal.
truth$loadings and truth$lv return both for comparison with
jsdgam() estimates and ordinate().
psi (occ) or lambda (nmix)[n_species x n_sites]
matrix of occupancy probabilities or expected abundances.
z (occ) or N (nmix)[n_species x n_sites] matrix of
the realised latent states that
predict(fit, type = "latent_state") estimates.
p[n_species x n_sites x n_visits] array of the
detection parameter that predict(fit, type = "detection")
estimates: the detection probability, the per-individual
probability r of nmix("royle_nichols") or the encounter
rate rho of nmix("poisson_poisson").
state_coefs, detection_coefs
The intercept and slopes
of each predictor. A named vector for one species, an
[n_species x (1 + p)] matrix for several.
loadings, lv
Z and the factor scores, when
n_lv > 0L.
summary() returns an mvgam_sim_closure_unit_summary list: the
dimensions, the recipe, the ranges of the true state and detection
parameters and the share of non-zero observations. A share of 0 or
1 marks data with no information on detection. print() shows it.
Nicholas J Clark
sim_mvgam() simulates state-space time series.
sim_jsdgam() simulates site-by-species data without a detection
process. The
N-mixture article fits occupancy and
N-mixture models to data of this layout.
Other simulation:
sim_jsdgam(),
sim_mvgam()
# Four species with two site and two visit covariates simdat <- sim_closure_unit_data( family = occ(), n_species = 4L, n_sites = 50L, n_visits = 4L, type = 2L, seed = 1L ) head(simdat$data_train) summary(simdat) # Next: fit these data with jsdgam(), as the shared_variation() # example does# Four species with two site and two visit covariates simdat <- sim_closure_unit_data( family = occ(), n_species = 4L, n_sites = 50L, n_visits = 4L, type = 2L, seed = 1L ) head(simdat$data_train) summary(simdat) # Next: fit these data with jsdgam(), as the shared_variation() # example does
Draws a site-by-species response matrix from a latent factor model
and returns it in the long format jsdgam() takes. Each species
gets its own intercept and its own slope on a site-level
covariate. The species share n_lv latent factors, whose loadings
set the residual correlation between them.
This is the non-detection counterpart to sim_closure_unit_data(),
which simulates the same latent factor structure for the
occupancy and N-mixture families.
sim_jsdgam( family = brms::negbinomial(), n_species = 5L, n_sites = 60L, n_lv = 2L, family_pars = list(), seed = NULL ) ## S3 method for class 'mvgam_sim_jsdgam' summary(object, ...) ## S3 method for class 'mvgam_sim_jsdgam_summary' print(x, digits = 3L, ...)sim_jsdgam( family = brms::negbinomial(), n_species = 5L, n_sites = 60L, n_lv = 2L, family_pars = list(), seed = NULL ) ## S3 method for class 'mvgam_sim_jsdgam' summary(object, ...) ## S3 method for class 'mvgam_sim_jsdgam_summary' print(x, digits = 3L, ...)
family |
Observation family. Any family mvgam's response
simulator draws from, plus |
n_species |
Number of species. Defaults to |
n_sites |
Number of sites. Defaults to |
n_lv |
Number of latent factors. Defaults to |
family_pars |
Optional named list of family parameters:
|
seed |
Optional integer seed. The session's random state is restored when the call returns. |
object |
A |
... |
Unused. Anything passed here is refused. |
x |
A |
digits |
Integer number of significant digits. Defaults to 3. |
The linear predictor for species k at site i is
intercept[k] + env_slope[k] * env[i] + Z[k, ] %*% lv[i, ], where
Z holds the loadings and lv the site scores. The residual
covariance the model targets is Z Z', plus a diagonal of squared
per-species scales for mvn() and mvt().
How that predictor becomes a response depends on the family.
Families whose species are drawn independently, such as
brms::negbinomial() or stats::poisson(), take one draw per
species. mvn() and mvt() add a per-species residual. The
composition families draw a site's species together. diri()
normalises gamma variates. multi() draws counts against a fixed
site total. categ() draws one species per site as a one-hot row.
A composition family identifies its loadings only up to a shift
shared by the species, which is the subspace mvgam's
sum_to_zero_vector parameterisation covers. The loadings are
centred for those families, which puts the simulated truth in the
same subspace a fit explores.
How much of the factor structure survives into the response
depends on the observation noise. The loadings are drawn with
standard deviation 0.7. mvn() and mvt() take their per-species
scale from Psi, which defaults to 0.5. Every other family takes
the scale its own simulator defaults to. A gaussian's sigma
defaults to 1, which can hide the species correlations from the
data. Pass family_pars = list(sigma = 0.5) for a gaussian whose
correlations a fit can recover.
An object of class mvgam_sim_jsdgam, inheriting
mvgam_sim, with elements:
data_trainLong data.frame with columns site,
env, series (the species), y and time (the unit
index jsdgam() keys on).
data_testNULL, kept for consistency with the other
simulators.
y_array[n_sites x n_species] response matrix.
familyThe family used.
n_species, n_sites, n_lv
The design.
truthList of the generative parameters: loadings,
lv, intercepts, env_slopes, env, residual_cov,
residual_cor and family_pars. For mvn(), mvt(),
diri() and multi() these include the defaults
Psi = 0.5, nu = 5, phi = 30 and unit_total = 30.
summary() returns an mvgam_sim_jsdgam_summary list: the design,
the per-species generative parameters and the range of the
residual correlations the loadings imply, which a fit of these data
is asked to recover. print() shows it.
jsdgam() fits the model these data come from.
sim_closure_unit_data() simulates occupancy and N-mixture data.
sim_mvgam() simulates time series. The
joint species distribution article
fits and interprets models of this kind.
Other simulation:
sim_closure_unit_data(),
sim_mvgam()
simdat <- sim_jsdgam( family = brms::negbinomial(), n_species = 4L, n_sites = 30L, n_lv = 2L, seed = 1L ) head(simdat$data_train) summary(simdat) # A composition family draws each site's species together comp <- sim_jsdgam(family = diri(), n_species = 4L, n_sites = 20L, seed = 2L) rowSums(comp$y_array)[1:3] # Next: fit with jsdgam(), then compare residual_cor() of the fit # with simdat$truth$residual_corsimdat <- sim_jsdgam( family = brms::negbinomial(), n_species = 4L, n_sites = 30L, n_lv = 2L, seed = 1L ) head(simdat$data_train) summary(simdat) # A composition family draws each site's species together comp <- sim_jsdgam(family = diri(), n_species = 4L, n_sites = 20L, seed = 2L) rowSums(comp$y_array)[1:3] # Next: fit with jsdgam(), then compare residual_cor() of the fit # with simdat$truth$residual_cor
mvgam-shaped time-series data with known truthSimulates training and test data from one of seven
observation-side recipes (type) combined with a latent trend
(trend_model). The recipes cover smooths, Gaussian processes and
random effects. Every generative quantity is returned for recovery
checks.
sim_mvgam( type = 1L, family = gaussian(), n_series = 1L, n_timepoints = 80L, trend_model = NULL, prop_trend = NULL, proportional_train = 0.75, prop_missing = 0, family_pars = list(), seed = NULL ) ## S3 method for class 'mvgam_sim' summary(object, ...) ## S3 method for class 'mvgam_sim_summary' print(x, digits = 3L, ...) ## S3 method for class 'mvgam_sim' print(x, ...)sim_mvgam( type = 1L, family = gaussian(), n_series = 1L, n_timepoints = 80L, trend_model = NULL, prop_trend = NULL, proportional_train = 0.75, prop_missing = 0, family_pars = list(), seed = NULL ) ## S3 method for class 'mvgam_sim' summary(object, ...) ## S3 method for class 'mvgam_sim_summary' print(x, digits = 3L, ...) ## S3 method for class 'mvgam_sim' print(x, ...)
type |
Integer in |
family |
The observation family: |
n_series |
Integer number of series. Defaults to |
n_timepoints |
Integer number of time points per series.
Defaults to |
trend_model |
A trend constructor such as |
prop_trend |
Share of the link-scale variance given to the
trend, in |
proportional_train |
Share of the time points kept in
|
prop_missing |
Share of the training responses set to |
family_pars |
Optional named list of family parameters:
|
seed |
Optional integer seed. The session's random state is restored when the call returns. |
object |
An |
... |
Unused. Anything passed here is refused. |
x |
An |
digits |
Integer number of significant digits. Defaults to 3. |
type = 1y ~ s(x) with an RW() trend.
type = 2y ~ s(x) + s(z) with an AR(p = 1) trend
whose coefficient is 0.7.
type = 3y ~ s(x) + (1 | grp) with an AR(p = 1)
trend whose coefficient is 0.7. The random intercept has five
levels.
type = 4y ~ gp(x) with an AR(p = 1) trend whose
coefficient is 0.7.
type = 5y ~ x with trend_formula = ~ s(z) and an
AR(p = 1) trend whose coefficient is 0.6. The smallest
prop_trend default keeps the autoregression separable from the
smooth.
type = 6y ~ s(season, bs = "cc") with a CAR() trend
on irregular gaps drawn from Uniform(1, 6). The autocorrelation
over the median gap is 0.7.
type = 7y ~ s(x) with a sparse AR(p = c(1, 12))
trend whose coefficients are 0.55 and 0.40. The covariate is not
periodic. All of the seasonal recurrence comes from the lag-12
coefficient.
Covariates are drawn independently for each row. Series are
independent unless the trend correlates them, as VAR(), ZMVN()
and cor = TRUE do. The trend and the observation-side terms are
each centred, then rescaled to their shares of a link-scale standard
deviation that keeps the response in a plausible range for the
family.
A list of class "mvgam_sim":
data_train, data_test
Long data frames with columns
y, series, time, the recipe's covariates and, for
binomial families, trials. data_test is NULL when
proportional_train = 1.
family, trend_model, type
The simulation settings.
true_betasNamed population-level coefficients.
true_smoothsNamed list of data frames holding each
true smooth on a grid of its covariate, in column f_true.
true_trend[n_timepoints, n_series] matrix of the
latent trend.
true_trend_sigmaStandard deviation of true_trend.
true_sigma_obsThe family's scale or dispersion, or
NA for a family without one.
summary() returns the design and these true parameters as an
mvgam_sim_summary list, with the number of series, time points,
training and test rows and the names of the true smooths.
print() shows that summary.
Nicholas J Clark
mvgam() fits the simulated data. sim_closure_unit_data()
simulates occupancy and N-mixture data. sim_jsdgam() simulates
site-by-species data. The
overview article fits a
model to data from sim_mvgam().
Other simulation:
sim_closure_unit_data(),
sim_jsdgam()
# Three Poisson series with an AR(1) latent trend simdat <- sim_mvgam( family = poisson(), n_series = 3L, n_timepoints = 120L, trend_model = AR(), seed = 0L ) head(simdat$data_train) simdat # The true smooth of x plot(f_true ~ x, data = simdat$true_smooths$`s(x)`, type = "l") # Next: mvgam(y ~ s(x), trend_formula = ~ AR(), # data = simdat$data_train, family = poisson())# Three Poisson series with an AR(1) latent trend simdat <- sim_mvgam( family = poisson(), n_series = 3L, n_timepoints = 120L, trend_model = AR(), seed = 0L ) head(simdat$data_train) simdat # The true smooth of x plot(f_true ~ x, data = simdat$true_smooths$`s(x)`, type = "l") # Next: mvgam(y ~ s(x), trend_formula = ~ AR(), # data = simdat$data_train, family = poisson())
Lists every s() and t2() term of every predictor. The
predictors are each response's mean, each distributional or
non-linear parameter with a formula and the trend.
posterior_smooths.mvgam() and conditional_smooths.mvgam() take
these labels.
## S3 method for class 'mvgam' smooths(x) smooths(x)## S3 method for class 'mvgam' smooths(x) smooths(x)
x |
A fitted |
A character vector of term labels, one per term of each
predictor, in the order of the panels of
conditional_smooths.mvgam(). Empty for a fit without smooths.
Nicholas J Clark
Other posterior summaries:
VarCorr.mvgam(),
bibtex(),
how_to_cite.mvgam(),
hypothesis.mvgam(),
index-mvgam,
mcmc_plot.mvgam(),
methods_md(),
mvgam_draws,
pairs.mvgam(),
posterior_interval.mvgam(),
ranef.mvgam(),
summary.mvgam()
## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5) + s(time, k = 6), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # The labels posterior_smooths() takes smooths(mod) # Next, posterior_smooths(mod, smooth = "s(x, k = 5)") draws one of # them ## End(Not run)## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5) + s(time, k = 6), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # The labels posterior_smooths() takes smooths(mod) # Next, posterior_smooths(mod, smooth = "s(x, k = 5)") draws one of # them ## End(Not run)
Gives each species' response to each named covariate, draw by draw,
with the posterior probability of its sign. A jsdgam() fit with
trait_slopes also gives each trait's effect on those responses,
the fourth-corner coefficients. The heatmaps show which species
respond positively, which negatively and which the data leave
uncertain.
species_effects(object, ...) ## S3 method for class 'mvgam' species_effects( object, variables, ..., prob_threshold = 0.95, probs = c(0.025, 0.975), robust = FALSE, ndraws = NULL, draw_ids = NULL, resp = NULL ) ## S3 method for class 'mvgam_species_effects' summary(object, type = c("species", "traits"), ...) ## S3 method for class 'mvgam_species_effects' print(x, digits = 2L, ...) ## S3 method for class 'mvgam_species_effects' plot(x, type = c("species", "traits"), supported_only = FALSE, ...)species_effects(object, ...) ## S3 method for class 'mvgam' species_effects( object, variables, ..., prob_threshold = 0.95, probs = c(0.025, 0.975), robust = FALSE, ndraws = NULL, draw_ids = NULL, resp = NULL ) ## S3 method for class 'mvgam_species_effects' summary(object, type = c("species", "traits"), ...) ## S3 method for class 'mvgam_species_effects' print(x, digits = 2L, ...) ## S3 method for class 'mvgam_species_effects' plot(x, type = c("species", "traits"), supported_only = FALSE, ...)
object |
A fitted |
... |
Unused. Anything passed here is refused. |
variables |
Character vector of the covariates to report, each a column of the data that a formula of the model uses. |
prob_threshold |
The posterior probability of its sign an effect
needs to count as supported, at least 0.5 and below 1. Defaults to
0.95. It sets the |
probs |
Two probabilities for the lower and upper bounds of the
credible interval. Defaults to |
robust |
Logical. |
ndraws, draw_ids
|
The posterior draws to use, as
|
resp |
The response to report, needed on a model with several. |
type |
|
x |
An |
digits |
Integer number of significant digits. Defaults to 2. |
supported_only |
Logical. |
Species effects. A species' response to a numeric covariate is the
average slope of its linear predictor, over the rows the species was
fitted to, as marginaleffects::avg_slopes() gives it with
type = "link". A linear term gives the species' own coefficient,
such as b_env plus b_env:seriessp_2 in y ~ env * series. A
smooth or an interaction gives the slope averaged over the species'
rows. A smooth that rises and falls can average to a slope near zero.
conditional_effects.mvgam() shows its shape. A covariate in
trend_formula, including one written with lv_axis(), reaches each
species through its loadings. A factor covariate gives one effect per
level, its difference from the reference level.
A diri(), multi() or categ() fit gives each species' share
through a softmax, which ignores a slope every species shares. Each
draw is then centred across the species. An effect is the slope of
the species' log share relative to the geometric mean of the shares,
the centred log-ratio scale.
An effect is on the link scale, per unit of the covariate. Effects of
covariates measured in different units compare better when the
covariates are standardised. A covariate that only a distributional
formula uses, such as the detection formula of occ(), moves no
species' linear predictor and is refused.
Trait effects. trait_slopes = ~ trait in jsdgam() makes each
species' response depend on its traits. A trait effect is how far the
response moves per unit of the trait, with each species' own deviation
held. A linear term gives its coefficient, such as b_env:size. A
smooth of the covariate or of the trait gives the effect averaged over
the fitted rows. A factor trait gives one effect per level, its
difference from the reference level. A covariate of factor_formula
reaches no trait. Its trait effects are zero.
Support. prob_nonzero is the larger of the posterior
probabilities that an effect is positive and that it is negative. An
effect is supported when prob_nonzero exceeds prob_threshold.
An object of class mvgam_species_effects. print() counts
the supported positive and negative responses to each covariate.
summary() returns a tibble of each effect's estimate, interval and
sign probabilities, with sig marking the supported ones.
plot() draws a heatmap of species by covariate, or of trait by
covariate with type = "traits". The species element holds the
summary matrices, [species, effect]. The draws element holds
the [draws, species, effect] array. A trait_slopes fit adds a
traits element of the same form.
Nicholas J Clark
Ovaskainen, O. and Abrego, N. (2020). Joint Species Distribution Modelling: With Applications in R. Cambridge University Press. doi:10.1017/9781108591720
residual_cor() for the associations the covariates leave,
conditional_effects.mvgam() for the shape of an effect,
variance_partition() for how much each source moves a species
## Not run: # Detections of 6 species at 80 sites, 4 visits each. Occupancy # responds to the site covariate `env` and detection to the time of # day `tod_c`. Two latent factors drive the species associations. simdat <- sim_closure_unit_data( family = occ(), n_species = 6L, n_sites = 80L, n_visits = 4L, n_lv = 2L, seed = 1L ) # A joint occupancy model. Each species has its own occupancy # intercept and `env` slope, plus its own detection intercept. Two # latent factors take up the residual association. mod <- jsdgam( formula = bf(y ~ series * env, p ~ series + tod_c), factor_formula = ~ -1, data = simdat$data_train, family = occ(), n_lv = 2L, chains = 2, silent = 2 ) summary(mod) # The effect of `env` on the chance of a detection, occupancy times # detection conditional_effects(mod) # Each species' response to env, outlined where its sign is clear plot(species_effects(mod, variables = "env")) # The residual correlations among species the factors imply plot(residual_cor(mod)) # Site scores and species loadings on the two factors ordinate(mod, rotation = "varimax") # Expected richness along `env`. The second plot marks the pairs of # species found together more often than `env` predicts. gradient <- datagrid(model = mod, env = seq(-2, 2, length.out = 20)) cm <- community(mod, newdata = gradient) plot(cm) plot(cm, type = "cooccurrence") # The draws, for any contrast: richness at the end of the gradient # less that at its start rv <- as_draws_rvars(cm) rv$richness[20] - rv$richness[1] # Next, compare n_lv = 1 with update(mod, n_lv = 1L) and loo() ## End(Not run)## Not run: # Detections of 6 species at 80 sites, 4 visits each. Occupancy # responds to the site covariate `env` and detection to the time of # day `tod_c`. Two latent factors drive the species associations. simdat <- sim_closure_unit_data( family = occ(), n_species = 6L, n_sites = 80L, n_visits = 4L, n_lv = 2L, seed = 1L ) # A joint occupancy model. Each species has its own occupancy # intercept and `env` slope, plus its own detection intercept. Two # latent factors take up the residual association. mod <- jsdgam( formula = bf(y ~ series * env, p ~ series + tod_c), factor_formula = ~ -1, data = simdat$data_train, family = occ(), n_lv = 2L, chains = 2, silent = 2 ) summary(mod) # The effect of `env` on the chance of a detection, occupancy times # detection conditional_effects(mod) # Each species' response to env, outlined where its sign is clear plot(species_effects(mod, variables = "env")) # The residual correlations among species the factors imply plot(residual_cor(mod)) # Site scores and species loadings on the two factors ordinate(mod, rotation = "varimax") # Expected richness along `env`. The second plot marks the pairs of # species found together more often than `env` predicts. gradient <- datagrid(model = mod, env = seq(-2, 2, length.out = 20)) cm <- community(mod, newdata = gradient) plot(cm) plot(cm, type = "cooccurrence") # The draws, for any contrast: richness at the end of the gradient # less that at its start rv <- as_draws_rvars(cm) rv$richness[20] - rv$richness[1] # Next, compare n_lv = 1 with update(mod, n_lv = 1L) and loo() ## End(Not run)
Compute reactivity, return rates and contributions of interactions to stationary forecast variance from mvgam models with Vector Autoregressive dynamics.
stability(object, ...) ## S3 method for class 'mvgam' stability( object, groups = NULL, ndraws = NULL, draw_ids = NULL, summary = TRUE, probs = c(0.025, 0.975), future = FALSE, ... ) ## S3 method for class 'mvgam_stability' summary(object, probs = c(0.025, 0.975), robust = TRUE, bins = 30L, ...) ## S3 method for class 'mvgam_stability_summary' plot( x, variables = c("reactivity", "mean_return_rate", "var_return_rate"), intervals = FALSE, ... ) ## S3 method for class 'mvgam_stability' plot( x, variables = c("reactivity", "mean_return_rate", "var_return_rate"), bins = 30L, ... )stability(object, ...) ## S3 method for class 'mvgam' stability( object, groups = NULL, ndraws = NULL, draw_ids = NULL, summary = TRUE, probs = c(0.025, 0.975), future = FALSE, ... ) ## S3 method for class 'mvgam_stability' summary(object, probs = c(0.025, 0.975), robust = TRUE, bins = 30L, ...) ## S3 method for class 'mvgam_stability_summary' plot( x, variables = c("reactivity", "mean_return_rate", "var_return_rate"), intervals = FALSE, ... ) ## S3 method for class 'mvgam_stability' plot( x, variables = c("reactivity", "mean_return_rate", "var_return_rate"), bins = 30L, ... )
object |
An object of class |
... |
Unused. Anything passed here is refused. |
groups |
Hierarchical VAR fits only. The panels to summarise,
by name or by index into the levels of |
ndraws |
Positive integer specifying number of posterior draws to use. NULL (default) uses all available draws. |
draw_ids |
Optional integer vector selecting a subset of posterior
draw indices to use. NULL (default) uses all draws (subject to
|
summary |
Logical. |
probs |
The lower and upper percentiles of the interval reported
with the median when |
future |
|
robust |
Logical, for |
bins |
Number of histogram bins, which |
x |
An |
variables |
Character vector of the metrics to draw. Defaults
to reactivity and the mean and variance return rates. Any column
of |
intervals |
Logical, for a summary. |
These measures describe how much the lagged interactions among the series contribute to the variability of the system. They also describe how the system responds to a perturbation (Ives et al. 2003). For a latent VAR(1)
the stationary covariance solves
. Each
posterior draw of and gives one draw of every
metric:
prop_int: the proportion of the volume of the stationary
distribution that the lagged interactions generate,
.
\item `prop_int_adj`: `prop_int` scaled by the number of series
\eqn{p}, \eqn{|\det(A)|^{2/p}}. It compares across systems of
different size.
\item `prop_int_offdiag`, `prop_int_diag`: the sensitivity of
`prop_int` to each cell of \eqn{A} is
\eqn{2 \det(A) (A^{-1})^\top}. `prop_int_offdiag` is the mean
absolute sensitivity of the off-diagonal cells (interactions
between series) as a share of that mean plus the mean absolute
sensitivity of the diagonal cells (self-regulation).
`prop_int_diag` is the remaining share.
\item `prop_cov_offdiag`, `prop_cov_diag`: the same split for the
sensitivity of \eqn{\det(\Sigma_{\infty})} to each cell of
\eqn{\Sigma_{\infty}}, \eqn{\det(\Sigma_{\infty})
(\Sigma_{\infty}^{-1})^\top}. Off-diagonal cells are counted
where \eqn{\Sigma} is estimated.
\item `reactivity`: the log of the largest singular value of
\eqn{A}, \eqn{\log \sigma_{max}(A)} (Neubert et al. 2009). A
positive value means some perturbation grows in the step after
it occurs, before the system returns to equilibrium.
\item `mean_return_rate`: the largest modulus of the eigenvalues
of \eqn{A}. The distance of the mean from its stationary value
shrinks by this factor each step, asymptotically. A value nearer
1 means a slower return.
\item `var_return_rate`: the same factor for the variance, the
largest modulus of the eigenvalues of \eqn{A \otimes A}, which
is `mean_return_rate` squared.
The prior on keeps every draw stationary (Heaps 2023).
and every metric then exist in every draw.
irf() and fevd() describe the same dynamics as responses to
shocks.
A data.frame with the posterior median and interval of
each stability metric, or under summary = FALSE an object of class
mvgam_stability holding one row of metrics per posterior draw.
summary() turns the draws into the summary, one row per metric,
or per panel and metric on a hierarchical VAR. plot() draws a
histogram of each metric, with a dashed line at zero on the
reactivity panel, above which the system amplifies a shock before
it decays. A hierarchical VAR draws a median and interval for each
panel. A summary plots the histograms from the bins it recorded, or
under intervals = TRUE a median and interval.
Nicholas J Clark
AR Ives, B Dennis, KL Cottingham & SR Carpenter (2003). Estimating community stability and ecological interactions from time-series data. Ecological Monographs, 73, 301-330.
MG Neubert, H Caswell & AR Solow (2009). Detecting reactivity. Ecology, 90, 2683-2688.
SE Heaps (2023). Enforcing stationarity through the prior in vector autoregressions. Journal of Computational and Graphical Statistics, 32, 74-83.
irf() and fevd() summarise the same VAR dynamics.
The VAR article runs stability() on
a plankton community. The
hierarchical VAR article
reports the metrics for each group of a hierarchical VAR.
Other latent dynamics:
active_factors(),
compare_loadings(),
fevd.mvgam(),
irf.mvgam(),
ordinate(),
posterior_transition_matrix(),
residual_cor(),
shared_variation()
## Not run: # Ten years of monthly counts of a prey species and its predator. # Predators suppress the prey a month later. Prey raise the # predators a month later. set.seed(2025) n_months <- 120 A <- rbind(prey = c(0.6, -0.5), predator = c(0.4, 0.5)) z <- matrix(0, n_months, 2) for (t in 2:n_months) { z[t, ] <- A %*% z[t - 1, ] + rnorm(2, sd = 0.35) } predator_prey <- data.frame( time = rep(seq_len(n_months), 2), series = factor(rep(c("prey", "predator"), each = n_months), levels = c("prey", "predator")), y = rpois(2 * n_months, exp(c(2.5 + z[, 1], 1.5 + z[, 2]))) ) var_mod <- mvgam(y ~ series, trend_formula = ~ VAR(), data = predator_prey, family = poisson(), chains = 2, silent = 2) ## End(Not run) ## Not run: # Posterior medians and intervals of the stability metrics stab <- stability(var_mod) stab[stab$metric %in% c("reactivity", "mean_return_rate"), ] # The full posterior of each metric plot(stability(var_mod, summary = FALSE)) # Next: irf() traces a shock through the system over time ## End(Not run)## Not run: # Ten years of monthly counts of a prey species and its predator. # Predators suppress the prey a month later. Prey raise the # predators a month later. set.seed(2025) n_months <- 120 A <- rbind(prey = c(0.6, -0.5), predator = c(0.4, 0.5)) z <- matrix(0, n_months, 2) for (t in 2:n_months) { z[t, ] <- A %*% z[t - 1, ] + rnorm(2, sd = 0.35) } predator_prey <- data.frame( time = rep(seq_len(n_months), 2), series = factor(rep(c("prey", "predator"), each = n_months), levels = c("prey", "predator")), y = rpois(2 * n_months, exp(c(2.5 + z[, 1], 1.5 + z[, 2]))) ) var_mod <- mvgam(y ~ series, trend_formula = ~ VAR(), data = predator_prey, family = poisson(), chains = 2, silent = 2) ## End(Not run) ## Not run: # Posterior medians and intervals of the stability metrics stab <- stability(var_mod) stab[stab$metric %in% c("reactivity", "mean_return_rate"), ] # The full posterior of each metric plot(stability(var_mod, summary = FALSE)) # Next: irf() traces a shock through the system over time ## End(Not run)
trend_formula
stancode() and standata() delegate a plain formula to
brms. A trend_formula in the same call, or a family mvgam
builds such as tweedie() or nmix(), names an mvgam model. These
methods then build the mvgam_formula that call
describes and generate its program.
## S3 method for class 'formula' stancode(object, ...) ## S3 method for class 'bform' stancode(object, ...) ## S3 method for class 'formula' standata(object, ...) ## S3 method for class 'bform' standata(object, ...)## S3 method for class 'formula' stancode(object, ...) ## S3 method for class 'bform' stancode(object, ...) ## S3 method for class 'formula' standata(object, ...) ## S3 method for class 'bform' standata(object, ...)
object |
A |
... |
Arguments for |
A character string of Stan code, or a list of Stan data.
mvgam_formula,
stancode.mvgam_formula,
standata.mvgam_formula
The Stan program and data list of an mvgam model. For an
mvgam_formula() they are generated without fitting, as mvgam()
would build them from the same arguments. For an mvgam model they
are the ones the model was built with. Pass the two to rstan
or cmdstanr to run the model outside mvgam. The program
shows how the trend enters the linear predictor.
## S3 method for class 'mvgam_formula' stancode( object, data, family = gaussian(), prior = NULL, data2 = NULL, sample_prior = "no", knots = NULL, drop_unused_levels = TRUE, backend = "rstan", threads = 1L, normalize = TRUE, save_model = NULL, silent = 1L, stanvars = NULL, validate = TRUE, ... ) ## S3 method for class 'mvgam_formula' standata( object, data, family = gaussian(), prior = NULL, data2 = NULL, sample_prior = "no", knots = NULL, drop_unused_levels = TRUE, backend = "rstan", threads = 1L, normalize = TRUE, save_model = NULL, silent = 1L, stanvars = NULL, ... ) ## S3 method for class 'mvgam' stancode(object, ...) ## S3 method for class 'mvgam' standata(object, ...) ## S3 method for class 'mvgamstancode' print(x, ...)## S3 method for class 'mvgam_formula' stancode( object, data, family = gaussian(), prior = NULL, data2 = NULL, sample_prior = "no", knots = NULL, drop_unused_levels = TRUE, backend = "rstan", threads = 1L, normalize = TRUE, save_model = NULL, silent = 1L, stanvars = NULL, validate = TRUE, ... ) ## S3 method for class 'mvgam_formula' standata( object, data, family = gaussian(), prior = NULL, data2 = NULL, sample_prior = "no", knots = NULL, drop_unused_levels = TRUE, backend = "rstan", threads = 1L, normalize = TRUE, save_model = NULL, silent = 1L, stanvars = NULL, ... ) ## S3 method for class 'mvgam' stancode(object, ...) ## S3 method for class 'mvgam' standata(object, ...) ## S3 method for class 'mvgamstancode' print(x, ...)
object |
An |
data |
A data frame holding every variable the formulas use. |
family |
A description of the response distribution and link
function, given as a family function, a call to one or its name.
Supports most brms families, including the ordinal families
( A family written inside a univariate |
prior |
A |
data2 |
A named list of objects the model uses that are not
variables in |
sample_prior |
|
knots |
Optional named list of knot positions for spline terms, used by the observation and trend formulas alike. |
drop_unused_levels |
Logical. |
backend |
|
threads |
Number of threads within each chain. Defaults to 1. |
normalize |
Logical. |
save_model |
File path to write the Stan program to, or |
silent |
Integer verbosity, as in |
stanvars |
Optional |
validate |
Logical. |
... |
For an |
x |
An |
stancode() returns the Stan program as a character string
of class mvgamstancode, which prints line by line. standata()
returns the named list of Stan data.
mvgam(), mvgam_formula(), get_prior.mvgam_formula().
methods_md() writes the same model as equations for a methods
section.
Other model fitting:
check_newdata(),
jsdgam(),
mvgam(),
mvgam_data(),
mvgam_multiple(),
pivot_detection_array(),
pivot_species_matrix(),
print.mvgam_formula(),
series_to_mvgam(),
update.mvgam()
set.seed(1) dat <- sim_mvgam(family = poisson(), n_series = 2L, n_timepoints = 40L, trend_model = AR())$data_train mf <- mvgam_formula(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1)) # The program of the model, before any fitting. The trend's # parameters carry a `_trend` suffix. code <- stancode(mf, data = dat, family = poisson()) code # The data passed to that program: 60 observations of 2 series # over 30 time points sdata <- standata(mf, data = dat, family = poisson()) sdata[c("N", "N_series_trend", "N_time_trend")] # Next, fit the model with mvgam(), which compiles this programset.seed(1) dat <- sim_mvgam(family = poisson(), n_series = 2L, n_timepoints = 40L, trend_model = AR())$data_train mf <- mvgam_formula(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1)) # The program of the model, before any fitting. The trend's # parameters carry a `_trend` suffix. code <- stancode(mf, data = dat, family = poisson()) code # The data passed to that program: 60 observations of 2 series # over 30 time points sdata <- standata(mf, data = dat, family = poisson()) sdata[c("N", "N_series_trend", "N_time_trend")] # Next, fit the model with mvgam(), which compiles this program
Provides posterior summary statistics for mvgam model parameters, organised by category (fixed effects, smooth terms, family parameters, trend parameters and factor loadings).
## S3 method for class 'mvgam' summary(object, probs = c(0.025, 0.975), robust = FALSE, matrices = FALSE, ...) ## S3 method for class 'mvgam_summary' print(x, digits = 2, ...)## S3 method for class 'mvgam' summary(object, probs = c(0.025, 0.975), robust = FALSE, matrices = FALSE, ...) ## S3 method for class 'mvgam_summary' print(x, digits = 2, ...)
object |
An object of class |
probs |
Two probabilities for the lower and upper bounds of the
credible interval. Default |
robust |
Logical. If |
matrices |
Logical; if |
... |
Unused. Anything passed here is refused. |
x |
An |
digits |
Integer number of decimal places. Defaults to 2. |
Each block has the columns:
EstimatePosterior mean, or median with
robust = TRUE.
Est.ErrorPosterior standard deviation, or MAD with
robust = TRUE.
l-95% CI, u-95% CI
Credible interval
bounds at probs, labelled by its coverage.
RhatPotential scale reduction factor on split chains, 1 at convergence.
Bulk_ESS, Tail_ESS
Bulk and tail effective sample sizes.
Vehtari et al. (2021) recommend an Rhat below 1.01 and bulk and tail effective sample sizes above 400 before a summary is used. A fit should also have no divergent transitions. The section 'Checking a fit' of mvgam_diagnostics says what to do when one of these checks fails.
An object of class mvgam_summary. Each block is a
data frame of the columns below, one row per parameter, named as
print() shows it. A block is absent when the model has no such
parameter. The observation model's blocks are:
smoothSmoothing standard deviations, one row per
penalty of each smooth. The basis coefficients are available by
name from as_draws(object, variable = "^s_", regex =
TRUE).
gpGaussian-process marginal standard deviations and length-scales.
randomGroup-level standard deviations and
correlations, as a list of tables named by grouping factor.
ngrps gives each factor's number of levels. ranef()
gives the per-level effects.
fixedRegression coefficients, those of every distributional parameter given a formula among them.
moThe simplex of each monotonic effect.
specFamily parameters without a formula of their
own, such as sigma or shape.
The trend model's blocks take the same names with the prefix
trend_, joined by trend_spec for the trend's
dynamics, loadings for the factor loadings and
loadings_prior for the hyperparameters of their prior. The
formula, family, draw counts and data dimensions are stored with
them.
print() sets the blocks out under their headings, followed by the
sampler diagnostics and suggested next steps.
Vehtari, A., Gelman, A., Simpson, D., Carpenter, B. and Burkner, P.-C. (2021). Rank-normalization, folding, and localization: an improved Rhat for assessing convergence of MCMC. Bayesian Analysis, 16(2):667-718. doi:10.1214/20-BA1221
mvgam_diagnostics checks convergence. pp_check.mvgam()
checks the fit against the data.
how_to_cite() drafts a methods paragraph for the model.
methods_md() writes its equations, glossary and priors.
mcmc_plot.mvgam() plots the draws of these parameters.
Other posterior summaries:
VarCorr.mvgam(),
bibtex(),
how_to_cite.mvgam(),
hypothesis.mvgam(),
index-mvgam,
mcmc_plot.mvgam(),
methods_md(),
mvgam_draws,
pairs.mvgam(),
posterior_interval.mvgam(),
ranef.mvgam(),
smooths.mvgam()
## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) summary(mod) # Each block is a data frame, such as the trend's dynamics round(summary(mod)$trend_spec, 2) # Next: pp_check(mod) compares draws from the model with the data ## End(Not run)## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) summary(mod) # Each block is a data frame, such as the trend's dynamics round(summary(mod)$trend_spec, 2) # Next: pp_check(mod) compares draws from the model with the data ## End(Not run)
The summary of a fit from mvgam_multiple(). The estimates come from
the pooled draws. Chains from different imputations sample different
posteriors, which raises the R-hat of the pooled chains. Each
parameter's Rhat is its largest over the imputation fits instead.
Bulk_ESS and Tail_ESS are the sums over those fits. A table gives
each fit's largest R-hat and smallest ESS over its parameters.
## S3 method for class 'mvgam_pooled' summary(object, probs = c(0.025, 0.975), robust = FALSE, matrices = FALSE, ...) ## S3 method for class 'mvgam_pooled_summary' print(x, digits = 2, ...)## S3 method for class 'mvgam_pooled' summary(object, probs = c(0.025, 0.975), robust = FALSE, matrices = FALSE, ...) ## S3 method for class 'mvgam_pooled_summary' print(x, digits = 2, ...)
object |
A fit of class |
probs |
Two probabilities for the lower and upper bounds of the
credible interval. Default |
robust |
Logical. If |
matrices |
Logical; if |
... |
Unused. Anything passed here is refused. |
x |
An object of class |
digits |
Integer number of decimal places to print. |
summary() returns an object of class
c("mvgam_pooled_summary", "mvgam_summary"). It holds the blocks of
summary.mvgam() and mi_diagnostics, a list of the number of
imputations, the draws per imputation and the per-imputation
convergence table. print() returns x invisibly.
mvgam_multiple(), summary.mvgam()
terms() reports a model's structure to a caller that does not know
its class. model.frame() is the accessor usually paired with it.
The object holds the model's responses on the left and the
covariates of both submodels on the right. stats::terms() has no
meaning for the bar syntax of group-level terms.
insight::find_random() returns those.
## S3 method for class 'mvgam' terms(x, ...)## S3 method for class 'mvgam' terms(x, ...)
x |
A fitted |
... |
Unused. Anything passed here is refused. |
An object of class terms.
mvgam object's parameter posteriorsPosterior summaries of the parameters of a fitted mvgam model, as
a tibble with the columns of broom.mixed: term, estimate,
std.error, conf.low and conf.high. A type column assigns
each parameter to the observation model or the trend.
## S3 method for class 'mvgam' tidy( x, effects = "all", robust = FALSE, conf.int = TRUE, conf.level = 0.95, rhat = FALSE, ess = FALSE, ... )## S3 method for class 'mvgam' tidy( x, effects = "all", robust = FALSE, conf.int = TRUE, conf.level = 0.95, rhat = FALSE, ess = FALSE, ... )
x |
A fitted |
effects |
|
robust |
Logical. If |
conf.int |
Logical. If |
conf.level |
Numeric. Probability covered by the
credible interval reported in |
rhat |
Logical. If |
ess |
Logical. If |
... |
Unused. Anything passed here is refused. |
The type column places every parameter into one of the
following categories, each with the effects class it belongs to:
"observation_family_extra_param" (ran_pars) – auxiliary
observation-family parameters such as sigma, shape,
nu, phi, zi, hu.
"observation_beta" (fixed) – population-level
coefficients of the observation formula, with the intercept
and the fixed parts of its smooths and monotonic terms.
"observation_smooth_param" (ran_pars) – the penalty of each
smooth (sds_) and the marginal deviation and length scale of
each Gaussian process.
"observation_smooth_coef" (ran_vals) – the penalised basis
coefficients of the smooths and Gaussian processes.
"random_effect_group_level" (ran_pars) – the standard
deviations and correlations of the observation formula's
group-level terms.
"random_effect_beta" (ran_vals) – the group-level
coefficients themselves, one per level and term.
"trend_model_param" (ran_pars) – parameters of the trend
dynamics (ar1_trend, theta1_trend, Sigma_trend,
k_trend, m_trend, delta_trend, etc.) and the factor
loadings.
"trend_beta", "trend_smooth_param", "trend_smooth_coef",
"trend_random_effect_group_level" and
"trend_random_effect_beta" – the same five blocks of the
trend formula.
Fixed-effect terms take the names fixef.mvgam() gives them, as
broom.mixed::tidy.brmsfit() names them: b_x is x and
b_sigma_x is sigma_x. Every other term keeps the name
variables.mvgam() lists. brms samples a centred intercept and
transforms it to the intercept on the data's scale. The table reports
the coefficient once, as Intercept.
A tibble with one row per parameter and the columns
term, type, estimate and std.error. conf.int = TRUE adds
conf.low and conf.high. rhat and ess add rhat and
ess_bulk.
Other tidiers:
augment.mvgam(),
glance.mvgam()
## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # One row per parameter, with broom's column names td <- tidy(mod) td # The `type` column separates the trend's parameters from the # observation model's td[td$type == "trend_model_param", ] # The fixed effects alone, with convergence diagnostics tidy(mod, effects = "fixed", rhat = TRUE, ess = TRUE) # Next, augment() adds fitted values and residuals to the data ## End(Not run)## Not run: set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # One row per parameter, with broom's column names td <- tidy(mod) td # The `type` column separates the trend's parameters from the # observation model's td[td$type == "trend_model_param", ] # The fixed effects alone, with convergence diagnostics tidy(mod, effects = "fixed", rhat = TRUE, ess = TRUE) # Next, augment() adds fitted values and residuals to the data ## End(Not run)
The Tweedie distribution with power mtheta between 1 and 2, the
compound Poisson-gamma. It models non-negative continuous data with
a point mass at zero, such as catch per unit effort, rainfall or
biomass. A Poisson number of events each contributes a Gamma amount.
The variance is mphi * mu^mtheta.
tweedie(M = 30L)tweedie(M = 30L)
M |
Positive integer number of series terms in the Stan log
density. Defaults to |
The family has three distributional parameters:
muThe mean, on a fixed log link. The compound
construction needs mu > 0, which an identity link driven by a
latent trend cannot guarantee.
mphiThe dispersion, on a log link.
mthetaThe power, bounded to [1.001, 1.999]. Near 1 the
Poisson rate mu^(2 - mtheta) / ((2 - mtheta) mphi) and near 2
the Gamma shape (2 - mtheta) / (mtheta - 1) leave floating-point
range.
The latent trend enters through mu. mphi and mtheta are
scalars by default. A formula such as bf(y ~ x, mphi ~ site) gives
the dispersion its own linear predictor on the log scale, whose
intercept takes a student_t(3, 0, 2.5) prior. mtheta takes no
formula.
mu, mphi and mtheta trade off along Var[Y] = mphi * mu^mtheta.
Data that weakly separate Poisson-like from Gamma-like tails leave a
ridge in their joint posterior. An informative prior such as
prior(normal(1.5, 0.3), class = mtheta) resolves it.
The Stan log density sums M terms of the compound series for each
non-zero observation (Dunn and Smyth 2005). The terms past M are
negligible when M is well above the Poisson rate lambda, which
grows as mtheta approaches 2 or mphi approaches 0. Raise M when
check_tweedie_truncation() reports a rate near it. log_lik() and
posterior_predict() use mgcv::ldTweedie() and mgcv::rTweedie().
The Stan code adapts the custom_family of the Australian Institute
of Marine Science (2023), which uses the decomposition of Spinkney
(2020).
A brms::customfamily object for mvgam(family = ).
Australian Institute of Marine Science (2023). open-AIMS/tweedie: a
brms custom_family implementation of the Tweedie compound
Poisson-gamma distribution. GitHub,
https://github.com/open-AIMS/tweedie. MIT licence.
Spinkney (2020). Tweedie likelihood (compound Poisson-gamma) in Stan. Stan Discourse, https://discourse.mc-stan.org/t/tweedie-likelihood-compound-poisson-gamma-in-stan/14636
Dunn, P. K., & Smyth, G. K. (2005). Series evaluation of Tweedie exponential dispersion model densities. Statistics and Computing, 15(4), 267-280. doi:10.1007/s11222-005-4070-y
Jorgensen, B. (1987). Exponential dispersion models. Journal of the Royal Statistical Society: Series B, 49(2), 127-162. doi:10.1111/j.2517-6161.1987.tb01685.x
Other observation families:
beta_nb(),
categ(),
com_binomial(),
diri(),
multi(),
mvgam_families,
mvn(),
mvt(),
nmix(),
occ()
## Not run: set.seed(3) simdat <- sim_mvgam(family = tweedie(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam( y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = tweedie(), chains = 2, silent = 2 ) # The dispersion and power mcmc_plot(mod, variable = c("mphi", "mtheta"), type = "areas") # The share of zeros the model predicts against the share observed prop_zero <- function(y) mean(y == 0) pp_check(mod, type = "stat", stat = "prop_zero", binwidth = 0.02) # Next: check_tweedie_truncation(mod) checks the series length M ## End(Not run)## Not run: set.seed(3) simdat <- sim_mvgam(family = tweedie(), n_series = 1L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam( y ~ s(x, k = 5), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = tweedie(), chains = 2, silent = 2 ) # The dispersion and power mcmc_plot(mod, variable = c("mphi", "mtheta"), type = "areas") # The share of zeros the model predicts against the share observed prop_zero <- function(y) mean(y == 0) pp_check(mod, type = "stat", stat = "prop_zero", binwidth = 0.02) # Next: check_tweedie_truncation(mod) checks the series length M ## End(Not run)
Refit a fitted mvgam object with new data, an updated formula, new
priors, different sampler settings or any other argument mvgam()
accepts. The signature follows brms::update.brmsfit().
## S3 method for class 'mvgam' update(object, formula. = NULL, newdata = NULL, recompile = NULL, ...)## S3 method for class 'mvgam' update(object, formula. = NULL, newdata = NULL, recompile = NULL, ...)
object |
A fitted |
formula. |
A new observation formula, or an update to the
fitted one such as |
newdata |
An optional new training data frame. |
recompile |
Optional logical. |
... |
Any other argument |
Every mvgam() argument comes from object unless ... overrides
it. update(fit, iter = 4000) keeps the original formula, data,
family, trend, prior and backend. Only the iteration count changes.
Sampler settings follow brms::update.brmsfit(). chains, iter,
warmup, thin and control carry over when the refit keeps the
original algorithm. control also needs the original backend. A
new iter without a warmup takes the default warmup of
iter / 2. control merges entry by entry:
update(fit, adapt_delta = 0.99) keeps the original max_treedepth.
New training data passed as newdata keeps the fit's held-out data
when that lies after the new training times. Held-out data
overlapping them is dropped with a message.
A refit reuses the fitted prior table. The adaptive priors of brms,
such as the Intercept prior centred on the response, keep the
constants of the original fit. Because the constants stay fixed, a
refit on a different newdata window has the same Stan code and
reuses the compiled model. lfo_cv() and other workflows that refit
many times then repeat only the sampling. An inherited row for a
parameter the refit lacks, such as the smooth of a dropped term, is
left out of the refit. A prior passed to
update() joins the priors the user set on the original fit, as in
brms::update.brmsfit(). A new row replaces an old one for the same
parameter:
new_priors <- c( prior(std_normal(), class = "b"), prior(exponential(1), class = "sigma") ) refit <- update(mod, prior = new_priors)
A prior change that alters the Stan code recompiles the model. With
recompile = FALSE it is an error. stancode(refit) shows the
model the refit compiled.
Multivariate fits take a complete new formula as formula.. A
formula update written with . is refused, as brms refuses it.
A jsdgam() fit refits through jsdgam() with the arguments the
original call evaluated, including factor_formula, n_lv,
traits, trait_slopes and phylo. ... overrides any of them.
update() refuses multiple-imputation fits from
mvgam_multiple(combine = TRUE). Refit each imputation with
mvgam() and pool them again.
A refit mvgam object.
Nicholas J Clark
loo.mvgam() and loo_compare.mvgam() compare a refit with the
original. stancode.mvgam() shows the compiled model. The
forecast evaluation article
compares competing models by their forecasts.
Other model fitting:
check_newdata(),
jsdgam(),
mvgam(),
mvgam_data(),
mvgam_multiple(),
pivot_detection_array(),
pivot_species_matrix(),
print.mvgam_formula(),
series_to_mvgam(),
stancode.mvgam_formula()
## Not run: # A Poisson GAM without a latent trend. PSIS approximates each # held-out count of such a model well (see Details of ?loo.mvgam) set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = "None") mod <- mvgam(y ~ s(x), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) ## End(Not run) ## Not run: # Swap the family for a negative binomial. The formula, priors, data # and sampler settings carry over upd <- update(mod, family = negbinomial()) # Compare the two fits by approximate leave-one-out cross-validation. # The better model comes first, with elpd_diff = 0. An elpd_diff # smaller than 4 in size means the two predict about equally well. # p_worse is the probability that a model predicts worse than the best loo_compare(mod, upd) # A change of sampler settings alone reuses the compiled model longer <- update(mod, iter = 3000, recompile = FALSE) ## End(Not run)## Not run: # A Poisson GAM without a latent trend. PSIS approximates each # held-out count of such a model well (see Details of ?loo.mvgam) set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = "None") mod <- mvgam(y ~ s(x), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) ## End(Not run) ## Not run: # Swap the family for a negative binomial. The formula, priors, data # and sampler settings carry over upd <- update(mod, family = negbinomial()) # Compare the two fits by approximate leave-one-out cross-validation. # The better model comes first, with elpd_diff = 0. An elpd_diff # smaller than 4 in size means the two predict about equally well. # p_worse is the probability that a model predicts worse than the best loo_compare(mod, upd) # A change of sampler settings alone reuses the compiled model longer <- update(mod, iter = 3000, recompile = FALSE) ## End(Not run)
Posterior draws of the standard deviation of each group-level term of the observation formula, with the correlations and covariances of terms that share a grouping factor.
## S3 method for class 'mvgam' VarCorr( x, sigma = 1, summary = TRUE, robust = FALSE, probs = c(0.025, 0.975), ... )## S3 method for class 'mvgam' VarCorr( x, sigma = 1, summary = TRUE, robust = FALSE, probs = c(0.025, 0.975), ... )
x |
A fitted |
sigma |
A single non-negative number. It has no effect.
|
summary |
Logical. |
robust |
Logical. |
probs |
Numeric vector of the two quantiles to report. |
... |
Unused. Anything passed here is refused. |
A trend-side component is named with the _trend suffix, as
sd_g__Intercept_trend. as_draws.mvgam() returns its draws.
A named list with one entry per grouping factor. Each entry is a list of these components:
sd: the standard deviation of each coefficient, a matrix of
coefficients by statistics, or of draws by coefficients under
summary = FALSE.
cor: correlation matrices, present when the factor carries two
or more correlated coefficients. The array runs over
coefficients, statistics and coefficients, or over draws and two
coefficient axes under summary = FALSE.
cov: covariance matrices, shaped as cor.
Nicholas J Clark
ranef.mvgam() gives each level's deviation.
fixef.mvgam() summarises the population-level effects.
Other posterior summaries:
bibtex(),
how_to_cite.mvgam(),
hypothesis.mvgam(),
index-mvgam,
mcmc_plot.mvgam(),
methods_md(),
mvgam_draws,
pairs.mvgam(),
posterior_interval.mvgam(),
ranef.mvgam(),
smooths.mvgam(),
summary.mvgam()
## Not run: set.seed(14) simdat <- sim_mvgam(family = poisson(), n_series = 4L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5) + (1 | series), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # The standard deviation of the series intercepts VarCorr(mod)$series$sd # Next: ranef() gives each series' own deviation ## End(Not run)## Not run: set.seed(14) simdat <- sim_mvgam(family = poisson(), n_series = 4L, n_timepoints = 120L, trend_model = AR()) mod <- mvgam(y ~ s(x, k = 5) + (1 | series), trend_formula = ~ AR(p = 1), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) # The standard deviation of the series intercepts VarCorr(mod)$series$sd # Next: ranef() gives each series' own deviation ## End(Not run)
Shows what moves each series: its covariates, the latent factors it shares with other series, its own trend, its season and, in a detection model, its detection process. Each source's share of the variance is computed draw by draw, which gives every share a posterior distribution.
variance_partition(object, ...) ## S3 method for class 'mvgam' variance_partition( object, ..., ndraws = NULL, draw_ids = NULL, scale = c("link", "expected"), resp = NULL ) ## S3 method for class 'mvgam_variance_partition' summary(object, probs = c(0.025, 0.975), ...) ## S3 method for class 'mvgam_variance_partition' print(x, digits = 2L, ...) ## S3 method for class 'mvgam_variance_partition' plot(x, ...)variance_partition(object, ...) ## S3 method for class 'mvgam' variance_partition( object, ..., ndraws = NULL, draw_ids = NULL, scale = c("link", "expected"), resp = NULL ) ## S3 method for class 'mvgam_variance_partition' summary(object, probs = c(0.025, 0.975), ...) ## S3 method for class 'mvgam_variance_partition' print(x, digits = 2L, ...) ## S3 method for class 'mvgam_variance_partition' plot(x, ...)
object |
A fitted |
... |
Unused. Anything passed here is refused. |
ndraws, draw_ids
|
The posterior draws to use, as
|
scale |
|
resp |
The response to report, needed on a model with several. |
probs |
Interval probabilities of the table. Defaults to
|
x |
An |
digits |
Number of decimal places to print. Defaults to |
Sources. Each source is a sum of parts of the fitted predictor:
environmentevery term of the observation and trend formulas, group-level terms included
associationsthe latent factors, shared across series
trenda latent state belonging to its series alone
seasonthe season of an LLT() trend
detectionthe terms of an occ() or nmix() detection
formula, p ~ ..., on that formula's own link scale. It joins
scale = "link" alone.
A source a model lacks or that never varies is left out.
A diri(), multi() or categ() fit gives each species' share
through a softmax, which ignores a shift every species at a site
shares. Each source is centred across the species at each site, the
centred log-ratio scale. A covariate with one slope for every species
then moves no share and is left out.
Under a non-linear link, scale = "expected" holds the other sources
at their fitted values. Its sources then interact, as a covariate's
effect on a count grows with the level.
Shares. A source's share is the variance of its values over the fitted rows of a series, divided by the sum of those variances across sources. Covariances between sources are left out. They would give a negative share to a source that offsets another. Observation noise is left out too: the shares describe the predictor, on a scale every family has. A series whose predictor never moves has no share.
A series row reports what moves that series over its own rows. An effect that differs only between series, such as a covariate measured once per site, has no variance there. The community row pools every row and counts those effects.
An object of class mvgam_variance_partition. print() gives
the mean share of each source by series. summary() returns a
tibble of each share's median and interval. plot() draws one
stacked bar per series and one for the community.
Nicholas J Clark
residual_cor() for the associations between series,
seasonality() for the season, bayes_R2() for the share of the
response's variance the predictor explains,
forecast_uncertainty() for the variance of a forecast
## Not run: set.seed(4) simdat <- sim_mvgam(family = poisson(), n_series = 4L, n_timepoints = 80L, trend_model = AR()) mod <- mvgam( y ~ s(x, k = 5), trend_formula = ~ AR(p = 1, n_lv = 2), data = simdat$data_train, family = poisson(), chains = 2, silent = 2 ) # The covariate's share against the shared factors', by series vp <- variance_partition(mod) vp plot(vp) # Each share with its posterior interval summary(vp) ## End(Not run)## Not run: set.seed(4) simdat <- sim_mvgam(family = poisson(), n_series = 4L, n_timepoints = 80L, trend_model = AR()) mod <- mvgam( y ~ s(x, k = 5), trend_formula = ~ AR(p = 1, n_lv = 2), data = simdat$data_train, family = poisson(), chains = 2, silent = 2 ) # The covariate's share against the shared factors', by series vp <- variance_partition(mod) vp plot(vp) # Each share with its posterior interval summary(vp) ## End(Not run)
Passes the pointwise log likelihood of log_lik.mvgam() to
loo::waic(). loo.mvgam() estimates the same ELPD by PSIS and
reports Pareto k diagnostics that say when to distrust it. Vehtari
et al. (2017) recommend it over WAIC.
## S3 method for class 'mvgam' waic( x, ..., compare = TRUE, resp = NULL, pointwise = FALSE, model_names = NULL, incl_autocor = TRUE, incl_dynamics = NULL, by_series = FALSE )## S3 method for class 'mvgam' waic( x, ..., compare = TRUE, resp = NULL, pointwise = FALSE, model_names = NULL, incl_autocor = TRUE, incl_dynamics = NULL, by_series = FALSE )
x |
A fitted |
... |
Further arguments to |
compare, resp, pointwise, model_names
|
The arguments of
brms::waic.brmsfit. |
incl_autocor |
Logical, default |
incl_dynamics |
Deprecated alias for |
by_series |
Logical, default |
A waic object (see loo::waic()), or with
by_series = TRUE a data frame of per-series estimates.
Vehtari, A., Gelman, A. and Gabry, J. (2017). Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC. Statistics and Computing, 27:1413-1432. doi:10.1007/s11222-016-9696-4
loo.mvgam() estimates the same ELPD by PSIS.
lfo_cv.mvgam() scores forecasts from rolling origins. The
forecast evaluation article
compares models by approximate and exact cross-validation.
Other model comparison:
bridge_sampler.mvgam(),
compare_elpds(),
kfold.mvgam(),
lfo_cv.mvgam(),
log_lik.mvgam(),
loo.mvgam(),
loo_compare.mvgam_lfo(),
mvgam_loo_extras,
posterior_average.mvgam()
## Not run: # A Poisson GAM without a latent trend. PSIS approximates each # held-out count of such a model well (see Details of ?loo.mvgam) set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = "None") mod <- mvgam(y ~ s(x), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) ## End(Not run) ## Not run: # The WAIC estimate of the ELPD, with its effective number of # parameters p_waic. A p_waic above 0.4 for any observation raises # a warning that recommends loo() waic(mod) # The PSIS estimate of the same ELPD. Its Pareto k diagnostics mark # the observations it estimates poorly loo(mod) # Next, loo_compare() ranks several models by either estimate ## End(Not run)## Not run: # A Poisson GAM without a latent trend. PSIS approximates each # held-out count of such a model well (see Details of ?loo.mvgam) set.seed(13) simdat <- sim_mvgam(family = poisson(), n_series = 1L, n_timepoints = 120L, trend_model = "None") mod <- mvgam(y ~ s(x), data = simdat$data_train, family = poisson(), chains = 2, silent = 2) ## End(Not run) ## Not run: # The WAIC estimate of the ELPD, with its effective number of # parameters p_waic. A p_waic above 0.4 for any observation raises # a warning that recommends loo() waic(mod) # The PSIS estimate of the same ELPD. Its Pareto k diagnostics mark # the observations it estimates poorly loo(mod) # Next, loo_compare() ranks several models by either estimate ## End(Not run)
A latent effect for each unit, such as a site, plot or time point, drawn from a multivariate normal that correlates the series. Unlike the other trends, the effect at one unit does not depend on the previous one. The constructor records its arguments. The model evaluates them against the data.
ZMVN( time = NA, series = NA, gr = NA, subgr = NA, n_lv = NULL, cor = TRUE, trend_map = NULL, df = Inf, centred = FALSE )ZMVN( time = NA, series = NA, gr = NA, subgr = NA, n_lv = NULL, cor = TRUE, trend_map = NULL, df = Inf, centred = FALSE )
time |
The unquoted name of the The values may have any spacing. Each unit's effects follow
|
series |
The unquoted name of the |
gr |
An optional grouping |
subgr |
A subgrouping |
n_lv |
The number of latent factors to estimate for dynamic
factor models. When |
cor |
In a factor model with every loading sampled, the factors take
independent shocks. The loadings carry the correlation among
series, which |
trend_map |
Optional map of the series onto the latent processes, which fixes some or all loadings of a dynamic factor model. One of three forms:
Its columns set the number of factors, which an |
df |
Degrees of freedom for the latent process innovations.
Defaults to Finite degrees of freedom let the latent process absorb an
occasional large shock while When Three caveats apply:
|
centred |
Logical. Sample the latent states directly rather
than their innovations? Default |
An object of class mvgam_trend.
A factor model with sampled loadings fits equally well under any reordering or sign change of its factors. Some models also fit equally well under any rotation. mvgam reports one version, chosen by the dynamics of the factors:
AR() factors take their own coefficients, as do
RW() and AR() factors with ma = TRUE. A
rotation would mix those coefficients. After sampling, the
factors of every draw are reordered and signed to agree with one
reference. The loadings Z, the factor paths lv_trend and the
coefficients ar1_trend or theta1_trend move together.
Factors are numbered by the variance they explain, largest
first.
RW(), VAR() and ZMVN() factors
without a moving-average term are unchanged by rotation. So are
AR() factors with coef_sharing = "shared" and no
moving-average term.
Following Heaps & Jermyn (2024), generated quantities rotate each
draw to lower-triangular loadings Z_tilde with a non-negative
diagonal. The factor paths rotate to lv_trend_tilde. A VAR
factor model rotates its coefficients to Phi_trend_tilde.
Post-fit methods use the identified loadings and factor paths.
shared_variation() and residual_cor() are the same under every
version.
A trend_map keeps its fixed entries on Z exactly. A
by = lv_axis() smooth ties each factor to its own covariate
effect. Neither takes a rotation. For a model with every loading
sampled, the loadings_prior
argument of mvgam() replaces the default iid Student-t prior
on Z with a structured matrix-normal prior. That prior is built
from per-series features, pairwise distance matrices or both. See
mvgam for its arguments.
Setting loadings_prior = "mgp" (or
loadings_prior = list(column_shrinkage = "mgp")) switches
the column scaling to the multiplicative gamma process prior of
Bhattacharya & Dunson (2011), which shrinks later columns of Z
toward zero with increasing strength. n_lv is then a truncation
ceiling on the factor count. active_factors reports
the posterior distribution of the number of active factors.
Heaps, S. E. and Jermyn, I. H. (2024). Structured prior distributions for the covariance matrix in latent factor models. Statistics and Computing, 34:143. doi:10.1007/s11222-024-10454-0
jsdgam() fits ZMVN() factors across species.
residual_cor() and ordinate() interpret the fitted
correlations. The
dynamic factor vignette builds factor
models with a partial trend_map. The
integrated distribution model article
shares one latent process across several observation families.
Other trend models:
LLT(),
PW(),
list_trend_types(),
lv_axis(),
print.mvgam_trend()
## Not run: # Simulate counts of four series whose latent effects are correlated # at each time point but independent over time. set.seed(2) simdat <- sim_mvgam( family = poisson(), n_series = 4L, n_timepoints = 120L, trend_model = ZMVN(), prop_trend = 0.9 ) mod <- mvgam( y ~ 1, trend_formula = ~ ZMVN(), data = simdat$data_train, family = poisson(), chains = 2, silent = 2 ) summary(mod) # The correlations among the series that ZMVN() estimates rc <- residual_cor(mod) rc plot(rc) # Next: jsdgam() fits ZMVN() factors across many species ## End(Not run)## Not run: # Simulate counts of four series whose latent effects are correlated # at each time point but independent over time. set.seed(2) simdat <- sim_mvgam( family = poisson(), n_series = 4L, n_timepoints = 120L, trend_model = ZMVN(), prop_trend = 0.9 ) mod <- mvgam( y ~ 1, trend_formula = ~ ZMVN(), data = simdat$data_train, family = poisson(), chains = 2, silent = 2 ) summary(mod) # The correlations among the series that ZMVN() estimates rc <- residual_cor(mod) rc plot(rc) # Next: jsdgam() fits ZMVN() factors across many species ## End(Not run)