| Title: | Bayesian Analysis of Graphical Models |
|---|---|
| Description: | Bayesian estimation and edge selection for graphical models of mixed binary, ordinal, and continuous variables. The variable types determine the model: an ordinal Markov random field for discrete data, a Gaussian graphical model for continuous data, or a mixed Markov random field combining both. Edge inclusion is determined through spike-and-slab priors, yielding posterior inclusion probabilities for each edge. Supports multi-group comparison via 'bgmCompare()', simulation, prediction, and missing data imputation. |
| Authors: | Maarten Marsman [aut, cre] (ORCID: <https://orcid.org/0000-0001-5309-7502>), Don van den Bergh [aut] (ORCID: <https://orcid.org/0000-0002-9838-7308>), Nikola Sekulovski [ctb] (ORCID: <https://orcid.org/0000-0001-7032-1684>), Giuseppe Arena [ctb] (ORCID: <https://orcid.org/0000-0001-5204-3326>), Laura Groot [ctb], Gali Geller [ctb] |
| Maintainer: | Maarten Marsman <[email protected]> |
| License: | GPL (>= 2) |
| Version: | 0.2.0.0 |
| Built: | 2026-06-08 10:35:16 UTC |
| Source: | https://github.com/bayesian-graphical-modelling-lab/bgms |
This dataset includes ADHD symptom ratings for 355 children aged 6 to 8 years from the Children's Attention Project (CAP) cohort (Silk et al. 2019). The sample consists of 146 children diagnosed with ADHD and 209 without a diagnosis. Symptoms were assessed through structured interviews with parents using the NIMH Diagnostic Interview Schedule for Children IV (DISC-IV) (Shaffer et al. 2000). The checklist includes 18 items: 9 Inattentive (I) and 9 Hyperactive/Impulsive (HI). Each item is binary (1 = present, 0 = absent).
data("ADHD")data("ADHD")
A data frame with 355 rows and 19 columns.
ADHD diagnosis: 1 = diagnosed, 0 = not diagnosed
Often avoids, dislikes, or is reluctant to engage in tasks that require sustained mental effort (I)
Often fails to give close attention to details or makes careless mistakes in schoolwork, work, or other activities (I)
Is often easily distracted by extraneous stimuli (I)
Is often forgetful in daily activities (I)
Often does not follow through on instructions and fails to finish schoolwork, chores, or duties in the workplace (I)
Often does not seem to listen when spoken to directly (I)
Often loses things necessary for tasks or activities (I)
Often has difficulty organizing tasks and activities (I)
Often has difficulty sustaining attention in tasks or play activities (I)
Often blurts out answers before questions have been completed (HI)
Often fidgets with hands or feet or squirms in seat (HI)
Often interrupts or intrudes on others (HI)
Is often "on the go" or often acts as if "driven by a motor" (HI)
Often has difficulty playing or engaging in leisure activities quietly (HI)
Often runs about or climbs excessively in situations in which it is inappropriate (HI)
Often leaves seat in classroom or in other situations in which remaining seated is expected (HI)
Often talks excessively (HI)
Often has difficulty awaiting turn (HI)
Silk et al. (2019). Data retrieved from doi:10.1371/journal.pone.0211053.s004. Licensed under the CC-BY 4.0: https://creativecommons.org/licenses/by/4.0/
Shaffer D, Fisher P, Lucas CP, Dulcan MK, Schwab-Stone ME (2000).
“NIMH Diagnostic Interview Schedule for Children Version IV (NIMH DISC-IV): description, differences from previous versions, and reliability of some common diagnoses.”
Journal of the American Academy of Child & Adolescent Psychiatry, 39, 28–38.
doi:10.1097/00004583-200001000-00014.
PMID: 10638065.
Silk TJ, Malpas CB, Beare R, Efron D, Anderson V, Hazell P, Jongeling B, Nicholson JM, Sciberras E (2019).
“A network analysis approach to ADHD symptoms: More than the sum of its parts.”
PLOS ONE, 14(1), e0211053.
doi:10.1371/journal.pone.0211053.
Specifies a Bernoulli prior for inclusion indicators with a fixed
inclusion probability. Used for edge selection in bgm and
difference selection in bgmCompare.
bernoulli_prior(inclusion_probability = 0.5)bernoulli_prior(inclusion_probability = 0.5)
inclusion_probability |
Numeric scalar or symmetric matrix. Prior
probability of each edge being included. A scalar applies to all edges;
a matrix allows edge-specific probabilities. Must be in (0, 1).
Default: |
An object of class "bgms_indicator_prior" with
family = "Bernoulli".
beta_bernoulli_prior, sbm_prior,
bgm
Other prior-constructors:
beta_bernoulli_prior(),
beta_prime_prior(),
cauchy_prior(),
exponential_prior(),
gamma_prior(),
normal_prior(),
sbm_prior()
bernoulli_prior() bernoulli_prior(inclusion_probability = 0.25)bernoulli_prior() bernoulli_prior(inclusion_probability = 0.25)
Specifies a Beta-Bernoulli prior for inclusion indicators. The inclusion
probability is drawn from a
distribution and shared across all edges.
beta_bernoulli_prior(alpha = 1, beta = 1)beta_bernoulli_prior(alpha = 1, beta = 1)
alpha |
Positive numeric. First shape parameter of the Beta
distribution. Default: |
beta |
Positive numeric. Second shape parameter of the Beta
distribution. Default: |
An object of class "bgms_indicator_prior" with
family = "Beta-Bernoulli".
bernoulli_prior, sbm_prior,
bgm
Other prior-constructors:
bernoulli_prior(),
beta_prime_prior(),
cauchy_prior(),
exponential_prior(),
gamma_prior(),
normal_prior(),
sbm_prior()
beta_bernoulli_prior() beta_bernoulli_prior(alpha = 2, beta = 5)beta_bernoulli_prior() beta_bernoulli_prior(alpha = 2, beta = 5)
Specifies a beta-prime prior on model parameters.
The parameterization follows the logistic transformation:
,
so where
.
beta_prime_prior(alpha = 0.5, beta = 0.5)beta_prime_prior(alpha = 0.5, beta = 0.5)
alpha |
Positive numeric. First shape parameter. Default: |
beta |
Positive numeric. Second shape parameter. Default: |
An object of class "bgms_parameter_prior" with
family = "beta-prime".
cauchy_prior, normal_prior,
bgm
Other prior-constructors:
bernoulli_prior(),
beta_bernoulli_prior(),
cauchy_prior(),
exponential_prior(),
gamma_prior(),
normal_prior(),
sbm_prior()
beta_prime_prior() beta_prime_prior(alpha = 1, beta = 1)beta_prime_prior() beta_prime_prior(alpha = 1, beta = 1)
The bgm function estimates the pseudoposterior distribution of the
parameters of a Markov Random Field (MRF) for binary, ordinal, continuous,
or mixed (discrete and continuous) variables. Optionally, it performs
Bayesian edge selection using discrete spike-and-slab priors to infer the
network structure.
bgm( x, variable_type = "ordinal", baseline_category, iter = 2000, warmup = 2000, interaction_prior = cauchy_prior(scale = 1), threshold_prior = beta_prime_prior(alpha = 0.5, beta = 0.5), means_prior = normal_prior(scale = 1), precision_scale_prior = gamma_prior(shape = 1, rate = 1), delta = NULL, edge_selection = TRUE, edge_prior = bernoulli_prior(0.5), na_action = c("listwise", "impute"), update_method = c("nuts", "adaptive-metropolis"), target_accept, nuts_max_depth = 10, learn_mass_matrix = TRUE, chains = 4, cores = parallel::detectCores(), display_progress = c("per-chain", "total", "none"), seed = NULL, standardize = FALSE, verbose = getOption("bgms.verbose", TRUE), progress_callback = NULL, pairwise_scale, main_alpha, main_beta, inclusion_probability, beta_bernoulli_alpha, beta_bernoulli_beta, beta_bernoulli_alpha_between, beta_bernoulli_beta_between, dirichlet_alpha, lambda, interaction_scale, burnin, save, threshold_alpha, threshold_beta )bgm( x, variable_type = "ordinal", baseline_category, iter = 2000, warmup = 2000, interaction_prior = cauchy_prior(scale = 1), threshold_prior = beta_prime_prior(alpha = 0.5, beta = 0.5), means_prior = normal_prior(scale = 1), precision_scale_prior = gamma_prior(shape = 1, rate = 1), delta = NULL, edge_selection = TRUE, edge_prior = bernoulli_prior(0.5), na_action = c("listwise", "impute"), update_method = c("nuts", "adaptive-metropolis"), target_accept, nuts_max_depth = 10, learn_mass_matrix = TRUE, chains = 4, cores = parallel::detectCores(), display_progress = c("per-chain", "total", "none"), seed = NULL, standardize = FALSE, verbose = getOption("bgms.verbose", TRUE), progress_callback = NULL, pairwise_scale, main_alpha, main_beta, inclusion_probability, beta_bernoulli_alpha, beta_bernoulli_beta, beta_bernoulli_alpha_between, beta_bernoulli_beta_between, dirichlet_alpha, lambda, interaction_scale, burnin, save, threshold_alpha, threshold_beta )
x |
A data frame or matrix with |
variable_type |
Character or character vector. Specifies the type of
each variable in |
baseline_category |
Integer or vector. Baseline category used in
Blume–Capel variables. Can be a single integer (applied to all) or a
vector of length |
iter |
Integer. Number of post–burn-in iterations (per chain).
Default: |
warmup |
Integer. Number of warmup iterations before collecting
samples. Short warmups trigger progressive warnings (NUTS only); see
|
interaction_prior |
A prior specification object for pairwise interaction parameters, created by one of the prior constructor functions:
Default: |
threshold_prior |
A prior specification object for threshold (main effect) parameters, created by one of the prior constructor functions:
Default: |
means_prior |
A prior specification object for continuous variable means (mixed MRF models only), created by one of the prior constructor functions:
Only used when the model includes continuous variables. Ignored for
pure ordinal or pure continuous (GGM) models.
Default: |
precision_scale_prior |
A prior specification object for the diagonal elements of the precision matrix, created by one of:
Only used for models with continuous variables (GGM and mixed MRF).
Ignored for pure ordinal models.
Default: |
delta |
Non-negative numeric, or |
edge_selection |
Logical. Whether to perform Bayesian edge selection.
If |
edge_prior |
An edge prior specification object, or a character string (deprecated). Specifies the prior for edge inclusion. Preferred: pass an object from one of:
Legacy character strings |
na_action |
Character. Specifies missing data handling. Either
|
update_method |
Character. Specifies how the MCMC sampler updates the model parameters:
Default: |
target_accept |
Numeric between 0 and 1. Target acceptance rate for
the sampler. Defaults are set automatically if not supplied:
|
nuts_max_depth |
Integer. Maximum tree depth in NUTS. Must be positive.
Default: |
learn_mass_matrix |
Logical. If |
chains |
Integer. Number of parallel chains to run. Default: |
cores |
Integer. Number of CPU cores for parallel execution.
Default: |
display_progress |
Character. Controls progress reporting during
sampling. Options: |
seed |
Optional integer. Random seed for reproducibility. Must be a single non-negative integer. |
standardize |
Logical. If |
verbose |
Logical. If |
progress_callback |
An optional R function with signature
|
pairwise_scale |
|
main_alpha, main_beta
|
|
inclusion_probability |
|
beta_bernoulli_alpha, beta_bernoulli_beta
|
|
beta_bernoulli_alpha_between, beta_bernoulli_beta_between
|
|
dirichlet_alpha |
|
lambda |
|
interaction_scale, burnin, save, threshold_alpha, threshold_beta
|
|
Depending on the variable types, the model is an ordinal MRF, a Gaussian graphical model (GGM), or a mixed MRF. Both regular ordinal variables and Blume–Capel ordinal variables (with a baseline category) are supported.
Edge selection uses spike-and-slab priors with Bernoulli, Beta-Bernoulli, or Stochastic-Block priors on the edge inclusion indicators. Parameters are sampled with NUTS (default) or adaptive Metropolis–Hastings, with a multi-stage warmup schedule. Missing data can be handled via listwise deletion or Gibbs imputation.
For full details on model specification, prior choices, warmup, and output interpretation, see the package website at https://bayesian-graphical-modelling-lab.github.io/bgms-docs/.
An S7 object of class bgms with posterior summaries, posterior mean
matrices, and access to raw MCMC draws. Its fields are accessible with
$ and [[ for backward compatibility, and it can be passed to
print(), summary(), and coef().
Main components include:
posterior_summary_main: Data frame with posterior summaries
(mean, sd, MCSE, ESS, Rhat) for main-effect parameters.
For OMRF models these are category thresholds;
for mixed MRF models these are discrete thresholds and
continuous means. NULL for GGM models (no main effects).
posterior_summary_quadratic: Data frame with posterior
summaries for the residual variance parameters (GGM and mixed MRF).
NULL for OMRF models.
posterior_summary_pairwise: Data frame with posterior
summaries for partial association parameters.
posterior_summary_indicator: Data frame with posterior
summaries for edge inclusion indicators (if edge_selection = TRUE).
posterior_mean_main: Posterior mean of main-effect
parameters. NULL for GGM models. For OMRF: a matrix
(p x max_categories) of category thresholds. For mixed MRF: a list
with $discrete (threshold matrix) and $continuous
(q x 1 matrix of means).
posterior_mean_pairwise: Symmetric matrix of posterior
mean partial associations (zero diagonal). For continuous variables
these are unstandardized partial correlations; for discrete variables
these are half the log adjacent-category odds ratio. Use
extract_precision(), extract_partial_correlations(), or
extract_log_odds() to convert to interpretable scales.
posterior_mean_residual_variance: Named numeric vector of
posterior mean residual variances .
Present for GGM and mixed MRF models; NULL for OMRF.
posterior_mean_indicator: Symmetric matrix of posterior mean
inclusion probabilities (if edge selection was enabled).
Additional summaries returned when
edge_prior = "Stochastic-Block". For more details about this prior
see Sekulovski et al. (2025).
posterior_summary_pairwise_allocations: Data frame with
posterior summaries (mean, sd, MCSE, ESS, Rhat) for the pairwise
cluster co-occurrence of the nodes. This serves to indicate
whether the estimated posterior allocations,co-clustering matrix
and posterior cluster probabilities (see blow) have converged.
posterior_mean_coclustering_matrix: a symmetric matrix of
pairwise proportions of occurrence of every variable. This matrix
can be plotted to visually inspect the estimated number of clusters
and visually inspect nodes that tend to switch clusters.
posterior_mean_allocations: A vector with the posterior mean
of the cluster allocations of the nodes. This is calculated using the method
proposed in Dahl (2009).
posterior_mode_allocations: A vector with the posterior
mode of the cluster allocations of the nodes.
posterior_num_blocks: A data frame with the estimated
posterior inclusion probabilities for all the possible number of clusters.
raw_samples: A list of raw MCMC draws per chain:
mainList of main effect samples.
pairwiseList of pairwise effect samples.
indicatorList of indicator samples (if edge selection enabled).
allocationsList of cluster allocations (if SBM prior used).
nchainsNumber of chains.
niterNumber of post–warmup iterations per chain.
parameter_namesNamed lists of parameter labels.
arguments: A list of function call arguments and metadata
(e.g., number of variables, warmup, sampler settings, package version).
The summary() method prints formatted posterior summaries, and
coef() extracts posterior mean matrices.
NUTS diagnostics (tree depth, divergences, energy, E-BFMI) are included
in fit$nuts_diag if update_method = "nuts".
Dahl DB (2009).
“Modal clustering in a class of product partition models.”
Bayesian Analysis, 4(2), 243–264.
doi:10.1214/09-BA409.
Sekulovski N, Arena G, Haslbeck JMB, Huth KBS, Friel N, Marsman M (2025).
“A Stochastic Block Prior for Clustering in Graphical Models.”
Retrieved from https://osf.io/preprints/psyarxiv/29p3m_v1.
OSF preprint.
vignette("intro", package = "bgms") for a worked example.
Other model-fitting:
bgmCompare()
# Run bgm on subset of the Wenchuan dataset fit = bgm(x = Wenchuan[, 1:5], chains = 2) # Posterior inclusion probabilities summary(fit)$indicator # Posterior pairwise effects summary(fit)$pairwise# Run bgm on subset of the Wenchuan dataset fit = bgm(x = Wenchuan[, 1:5], chains = 2) # Posterior inclusion probabilities summary(fit)$indicator # Posterior pairwise effects summary(fit)$pairwise
The bgmCompare function estimates group differences in category
threshold parameters (main effects) and pairwise interactions (pairwise
effects) of a Markov Random Field (MRF) for binary and ordinal variables.
Groups can be defined either by supplying two separate datasets (x and
y) or by a group membership vector. Optionally, Bayesian variable
selection can be applied to identify differences across groups.
bgmCompare( x, y, group_indicator, difference_selection = TRUE, main_difference_selection = FALSE, variable_type = "ordinal", baseline_category, difference_scale = 1, difference_prior = bernoulli_prior(0.5), difference_probability, interaction_prior = cauchy_prior(scale = 1), threshold_prior = beta_prime_prior(alpha = 0.5, beta = 0.5), iter = 2000, warmup = 2000, na_action = c("listwise", "impute"), update_method = c("nuts", "adaptive-metropolis"), target_accept, nuts_max_depth = 10, learn_mass_matrix = TRUE, chains = 4, cores = parallel::detectCores(), display_progress = c("per-chain", "total", "none"), seed = NULL, standardize = FALSE, verbose = getOption("bgms.verbose", TRUE), progress_callback = NULL, pairwise_scale, main_alpha, main_beta, beta_bernoulli_alpha, beta_bernoulli_beta, main_difference_model, reference_category, main_difference_scale, pairwise_difference_scale, pairwise_difference_prior, main_difference_prior, pairwise_difference_probability, main_difference_probability, pairwise_beta_bernoulli_alpha, pairwise_beta_bernoulli_beta, main_beta_bernoulli_alpha, main_beta_bernoulli_beta, interaction_scale, threshold_alpha, threshold_beta, burnin, save )bgmCompare( x, y, group_indicator, difference_selection = TRUE, main_difference_selection = FALSE, variable_type = "ordinal", baseline_category, difference_scale = 1, difference_prior = bernoulli_prior(0.5), difference_probability, interaction_prior = cauchy_prior(scale = 1), threshold_prior = beta_prime_prior(alpha = 0.5, beta = 0.5), iter = 2000, warmup = 2000, na_action = c("listwise", "impute"), update_method = c("nuts", "adaptive-metropolis"), target_accept, nuts_max_depth = 10, learn_mass_matrix = TRUE, chains = 4, cores = parallel::detectCores(), display_progress = c("per-chain", "total", "none"), seed = NULL, standardize = FALSE, verbose = getOption("bgms.verbose", TRUE), progress_callback = NULL, pairwise_scale, main_alpha, main_beta, beta_bernoulli_alpha, beta_bernoulli_beta, main_difference_model, reference_category, main_difference_scale, pairwise_difference_scale, pairwise_difference_prior, main_difference_prior, pairwise_difference_probability, main_difference_probability, pairwise_beta_bernoulli_alpha, pairwise_beta_bernoulli_beta, main_beta_bernoulli_alpha, main_beta_bernoulli_beta, interaction_scale, threshold_alpha, threshold_beta, burnin, save )
x |
A data frame or matrix of binary and ordinal responses for Group 1. Variables should be coded as nonnegative integers starting at 0. For ordinal variables, unused categories are collapsed; for Blume–Capel variables, all categories are retained. |
y |
Optional data frame or matrix for Group 2 (two-group designs).
Must have the same variables (columns) as |
group_indicator |
Optional integer vector of group memberships for
rows of |
difference_selection |
Logical. If |
main_difference_selection |
Logical. If |
variable_type |
Character vector specifying type of each variable:
|
baseline_category |
Integer or vector giving the baseline category for Blume–Capel variables. |
difference_scale |
Double. Scale of the Cauchy prior for difference
parameters. Default: |
difference_prior |
An indicator prior specification object for difference selection, created by one of:
Legacy character strings |
difference_probability |
|
interaction_prior |
A prior specification object for baseline pairwise interaction parameters, created by one of the prior constructor functions:
When supplied, overrides |
threshold_prior |
A prior specification object for threshold (main effect) parameters, created by one of the prior constructor functions:
When supplied, overrides |
iter |
Integer. Number of post–warmup iterations per chain.
Default: |
warmup |
Integer. Number of warmup iterations before sampling.
Default: |
na_action |
Character. How to handle missing data:
|
update_method |
Character. Sampling algorithm:
|
target_accept |
Numeric between 0 and 1. Target acceptance rate. Defaults: 0.44 (Metropolis), 0.80 (NUTS). |
nuts_max_depth |
Integer. Maximum tree depth for NUTS. Default: |
learn_mass_matrix |
Logical. If |
chains |
Integer. Number of parallel chains. Default: |
cores |
Integer. Number of CPU cores. Default:
|
display_progress |
Character. Controls progress reporting:
|
seed |
Optional integer. Random seed for reproducibility. |
standardize |
Logical. If |
verbose |
Logical. If |
progress_callback |
An optional R function with signature
|
pairwise_scale |
|
main_alpha, main_beta
|
|
beta_bernoulli_alpha, beta_bernoulli_beta
|
Doubles. Shape parameters
of the Beta prior for inclusion probabilities in the Beta–Bernoulli
model. Defaults: |
main_difference_model, reference_category, pairwise_difference_scale, main_difference_scale, pairwise_difference_prior, main_difference_prior, pairwise_difference_probability, main_difference_probability, pairwise_beta_bernoulli_alpha, pairwise_beta_bernoulli_beta, main_beta_bernoulli_alpha, main_beta_bernoulli_beta, interaction_scale, threshold_alpha, threshold_beta, burnin, save
|
|
Group-specific parameters are decomposed into a shared baseline plus
group differences that sum to zero. Difference selection uses
spike-and-slab priors (Bernoulli or Beta-Bernoulli). Parameters are
sampled with NUTS (default) or adaptive Metropolis–Hastings, using the
same multi-stage warmup schedule as bgm.
For full details on model specification, prior choices, and output interpretation, see the package website at https://bayesian-graphical-modelling-lab.github.io/bgms-docs/.
An S7 object of class bgmCompare supporting list-style $ /
[[ access for backward compatibility, containing posterior summaries,
posterior mean matrices, and raw MCMC samples. Some
posterior_summary_* fields are computed lazily on first access:
posterior_summary_main_baseline,
posterior_summary_pairwise_baseline: summaries of baseline
thresholds and pairwise interactions.
posterior_summary_main_differences,
posterior_summary_pairwise_differences: summaries of group
differences in thresholds and pairwise interactions.
posterior_summary_indicator: summaries of inclusion
indicators (if difference_selection = TRUE).
posterior_mean_main_baseline,
posterior_mean_pairwise_baseline: posterior mean matrices
(legacy style).
raw_samples: list of raw draws per chain for main,
pairwise, and indicator parameters.
arguments: list of function call arguments and metadata.
The summary() method prints formatted summaries, and
coef() extracts posterior means.
NUTS diagnostics (tree depth, divergences, energy, E-BFMI) are included
in fit$nuts_diag if update_method = "nuts".
There are no references for Rd macro \insertAllCites on this help page.
vignette("comparison", package = "bgms") for a worked example.
Other model-fitting:
bgm()
## Not run: # Run bgmCompare on subset of the Boredom dataset x = Boredom[Boredom$language == "fr", 2:6] y = Boredom[Boredom$language != "fr", 2:6] fit = bgmCompare(x, y, chains = 2) # Posterior inclusion probabilities summary(fit)$indicator # Bayesian model averaged main effects for the groups coef(fit)$main_effects_groups # Bayesian model averaged pairwise effects for the groups coef(fit)$pairwise_effects_groups ## End(Not run)## Not run: # Run bgmCompare on subset of the Boredom dataset x = Boredom[Boredom$language == "fr", 2:6] y = Boredom[Boredom$language != "fr", 2:6] fit = bgmCompare(x, y, chains = 2) # Posterior inclusion probabilities summary(fit)$indicator # Bayesian model averaged main effects for the groups coef(fit)$main_effects_groups # Bayesian model averaged pairwise effects for the groups coef(fit)$pairwise_effects_groups ## End(Not run)
This dataset includes responses to the 8-item Short Boredom Proneness Scale (SBPS), a self-report measure of an individual's susceptibility to boredom (Martarelli et al. 2023). Items were rated on a 7-point Likert scale ranging from 1 ("strongly disagree") to 7 ("strongly agree"). The scale was administered in either English (Struk et al. 2015) or French (translated by (Martarelli et al. 2023)).
data("Boredom")data("Boredom")
A data frame with 986 rows and 9 columns. Each row corresponds to a respondent.
Language in which the SBPS was administered: "en" = English, "fr" = French
I often find myself at "loose ends," not knowing what to do.
I find it hard to entertain myself.
Many things I have to do are repetitive and monotonous.
It takes more stimulation to get me going than most people.
I don't feel motivated by most things that I do.
In most situations, it is hard for me to find something to do or see to keep me interested.
Much of the time, I just sit around doing nothing.
Unless I am doing something exciting, even dangerous, I feel half-dead and dull.
Martarelli et al. (2023). Data retrieved from https://osf.io/qhux8. Licensed under the CC-BY 4.0: https://creativecommons.org/licenses/by/4.0/
Martarelli CS, Baillifard A, Audrin C (2023).
“A Trait-Based Network Perspective on the Validation of the French Short Boredom Proneness Scale.”
European Journal of Psychological Assessment, 39(6), 390–399.
doi:10.1027/1015-5759/a000718.
Struk AA, Carriere JSA, Cheyne JA, Danckert J (2015).
“A Short Boredom Proneness Scale: Development and Psychometric Properties.”
Assessment, 24(3), 346–359.
doi:10.1177/1073191115609996.
Specifies a Cauchy(0, scale) prior on model parameters.
This is the default prior for pairwise interactions in bgm
and produces heavy-tailed shrinkage toward zero.
cauchy_prior(scale = 1)cauchy_prior(scale = 1)
scale |
Positive numeric. Scale (half-width at half-maximum) of the
Cauchy distribution. Default: |
An object of class "bgms_parameter_prior" with
family = "cauchy".
normal_prior, beta_prime_prior,
bgm
Other prior-constructors:
bernoulli_prior(),
beta_bernoulli_prior(),
beta_prime_prior(),
exponential_prior(),
gamma_prior(),
normal_prior(),
sbm_prior()
cauchy_prior() cauchy_prior(scale = 2.5)cauchy_prior() cauchy_prior(scale = 2.5)
Returns posterior means for raw parameters (baseline + differences)
and group-specific effects from a bgmCompare fit, as well as inclusion indicators.
## S3 method for class 'bgmCompare' coef(object, ...)## S3 method for class 'bgmCompare' coef(object, ...)
object |
An object of class |
... |
Ignored. |
A list with components:
Posterior means of the raw main-effect parameters (variables x (baseline + differences)).
Posterior means of the raw pairwise-effect parameters (pairs x (baseline + differences)).
Posterior means of group-specific main effects (variables x groups), computed as baseline plus projected differences.
Posterior means of group-specific pairwise effects (pairs x groups), computed as baseline plus projected differences.
Posterior mean inclusion probabilities as a symmetric matrix, with diagonals corresponding to main effects and off-diagonals to pairwise effects.
bgmCompare(), print.bgmCompare(), summary.bgmCompare()
Other posterior-methods:
coef.bgms(),
print.bgmCompare(),
print.bgms(),
summary.bgmCompare(),
summary.bgms()
# See ?bgmCompare for a full example# See ?bgmCompare for a full example
Returns the posterior mean main effects, pairwise effects, and edge inclusion indicators from a bgms model fit.
## S3 method for class 'bgms' coef(object, ...)## S3 method for class 'bgms' coef(object, ...)
object |
An object of class |
... |
Ignored. |
A list with the following components:
Posterior mean of the main-effect parameters. NULL for
GGM models (no main effects). For OMRF models this is a numeric matrix
(p x max_categories) of category thresholds. For mixed MRF models this
is a list with $discrete (p x max_categories matrix) and
$continuous (q x 1 matrix of means).
Posterior mean of the partial association matrix (zero
diagonal). Use extract_precision() for the full precision matrix.
Posterior mean of the edge inclusion indicators (if available).
Posterior mean block allocations. Present only for Stochastic-Block edge-prior fits.
Posterior mode block allocations. Present only for Stochastic-Block edge-prior fits.
Data frame of the posterior distribution over the number of blocks. Present only for Stochastic-Block edge-prior fits.
bgm(), print.bgms(), summary.bgms()
Other posterior-methods:
coef.bgmCompare(),
print.bgmCompare(),
print.bgms(),
summary.bgmCompare(),
summary.bgms()
fit = bgm(x = Wenchuan[, 1:3]) coef(fit)fit = bgm(x = Wenchuan[, 1:3]) coef(fit)
Specifies an Exponential(rate) prior for positive scale parameters.
This is a convenience function equivalent to
gamma_prior(shape = 1, rate = rate).
exponential_prior(rate = 1)exponential_prior(rate = 1)
rate |
Positive numeric. Rate parameter of the Exponential
distribution. Default: |
An object of class "bgms_scale_prior" with
family = "exponential".
Other prior-constructors:
bernoulli_prior(),
beta_bernoulli_prior(),
beta_prime_prior(),
cauchy_prior(),
gamma_prior(),
normal_prior(),
sbm_prior()
exponential_prior() exponential_prior(rate = 2)exponential_prior() exponential_prior(rate = 2)
Retrieves the arguments used when fitting a model with bgm() or
bgmCompare().
extract_arguments(bgms_object)extract_arguments(bgms_object)
bgms_object |
A fitted model object of class |
A named list containing all arguments passed to the fitting function, including data dimensions, prior settings, and MCMC configuration.
bgm(), bgmCompare(), summary.bgms(), summary.bgmCompare()
Other extractors:
extract_category_thresholds(),
extract_ess(),
extract_group_params(),
extract_indicator_priors(),
extract_indicators(),
extract_log_odds(),
extract_main_effects(),
extract_pairwise_interactions(),
extract_partial_correlations(),
extract_posterior_inclusion_probabilities(),
extract_precision(),
extract_rhat(),
extract_sbm()
extract_category_thresholds() was renamed to extract_main_effects() to
reflect that main effects include continuous means and precision diagonal
(mixed MRF), not only category thresholds.
extract_category_thresholds(bgms_object)extract_category_thresholds(bgms_object)
bgms_object |
A fitted model object of class |
See extract_main_effects() for details.
Other extractors:
extract_arguments(),
extract_ess(),
extract_group_params(),
extract_indicator_priors(),
extract_indicators(),
extract_log_odds(),
extract_main_effects(),
extract_pairwise_interactions(),
extract_partial_correlations(),
extract_posterior_inclusion_probabilities(),
extract_precision(),
extract_rhat(),
extract_sbm()
Retrieves effective sample size estimates for all parameters from a
model fitted with bgm() or bgmCompare().
extract_ess(bgms_object)extract_ess(bgms_object)
bgms_object |
A fitted model object of class |
A named list with ESS values for each parameter type present in
the model (e.g., main, pairwise, indicator).
bgm(), bgmCompare(), extract_rhat()
Other extractors:
extract_arguments(),
extract_category_thresholds(),
extract_group_params(),
extract_indicator_priors(),
extract_indicators(),
extract_log_odds(),
extract_main_effects(),
extract_pairwise_interactions(),
extract_partial_correlations(),
extract_posterior_inclusion_probabilities(),
extract_precision(),
extract_rhat(),
extract_sbm()
Computes group-specific parameter estimates by combining baseline
parameters and group differences from a model fitted with bgmCompare().
extract_group_params(bgms_object)extract_group_params(bgms_object)
bgms_object |
A fitted model object of class |
A list with elements main_effects_groups (main effects per
group) and pairwise_effects_groups (pairwise effects per group).
bgmCompare(), extract_pairwise_interactions(),
extract_main_effects()
Other extractors:
extract_arguments(),
extract_category_thresholds(),
extract_ess(),
extract_indicator_priors(),
extract_indicators(),
extract_log_odds(),
extract_main_effects(),
extract_pairwise_interactions(),
extract_partial_correlations(),
extract_posterior_inclusion_probabilities(),
extract_precision(),
extract_rhat(),
extract_sbm()
Retrieves the prior specification used for inclusion indicators in a
model fitted with bgm() (edge indicators) or bgmCompare()
(difference indicators).
extract_indicator_priors(bgms_object)extract_indicator_priors(bgms_object)
bgms_object |
A fitted model object of class |
A named list describing the prior structure, including the prior type and any hyperparameters.
Requires edge_selection = TRUE. Returns a list with the
prior type ("Bernoulli", "Beta-Bernoulli", or
"Stochastic-Block") and associated hyperparameters.
Requires difference_selection = TRUE. Returns the
difference prior specification.
bgm(), bgmCompare(), extract_indicators()
Other extractors:
extract_arguments(),
extract_category_thresholds(),
extract_ess(),
extract_group_params(),
extract_indicators(),
extract_log_odds(),
extract_main_effects(),
extract_pairwise_interactions(),
extract_partial_correlations(),
extract_posterior_inclusion_probabilities(),
extract_precision(),
extract_rhat(),
extract_sbm()
Retrieves posterior samples of inclusion indicators from a model fitted
with bgm() (edge inclusion indicators) or bgmCompare() (difference
indicators).
extract_indicators(bgms_object)extract_indicators(bgms_object)
bgms_object |
A fitted model object of class |
A matrix with one row per post-warmup iteration and one column per indicator, containing binary (0/1) samples.
One column per edge. Requires edge_selection = TRUE.
Columns for main-effect and pairwise difference
indicators. Requires difference_selection = TRUE.
bgm(), bgmCompare(),
extract_posterior_inclusion_probabilities()
Other extractors:
extract_arguments(),
extract_category_thresholds(),
extract_ess(),
extract_group_params(),
extract_indicator_priors(),
extract_log_odds(),
extract_main_effects(),
extract_pairwise_interactions(),
extract_partial_correlations(),
extract_posterior_inclusion_probabilities(),
extract_precision(),
extract_rhat(),
extract_sbm()
Retrieves the posterior mean pairwise interaction matrix for discrete
variables from a model fitted with bgm(). These are the log-odds
parameters of the discrete (Markov random field) block. GGM models have
no discrete variables and return NULL.
extract_log_odds(bgms_object)extract_log_odds(bgms_object)
bgms_object |
A fitted model object of class |
A named numeric matrix of posterior mean log-odds interactions, or
NULL for GGM models.
A symmetric matrix with zero diagonal and one row and column per variable.
A symmetric matrix with zero diagonal and one row and column per discrete variable.
NULL (invisibly).
bgm(), extract_pairwise_interactions(), extract_precision()
Other extractors:
extract_arguments(),
extract_category_thresholds(),
extract_ess(),
extract_group_params(),
extract_indicator_priors(),
extract_indicators(),
extract_main_effects(),
extract_pairwise_interactions(),
extract_partial_correlations(),
extract_posterior_inclusion_probabilities(),
extract_precision(),
extract_rhat(),
extract_sbm()
fit = bgm(x = Wenchuan[, 1:3]) extract_log_odds(fit)fit = bgm(x = Wenchuan[, 1:3]) extract_log_odds(fit)
Retrieves main-effect parameters from a model fitted with bgm()
(posterior means) or bgmCompare() (posterior samples of baseline main
effects). For OMRF models these are category thresholds; for mixed MRF
models these include discrete thresholds and continuous means. GGM models
have no main effects and return NULL.
extract_main_effects(bgms_object)extract_main_effects(bgms_object)
bgms_object |
A fitted model object of class |
The structure depends on the model type:
NULL (invisibly). GGM models have no main effects;
use extract_precision() to obtain the precision matrix.
A numeric matrix with one row per variable and one
column per category threshold, containing posterior means. Columns
beyond the number of categories for a variable are NA.
A list with two elements:
A numeric matrix (p rows x max_categories columns) of posterior mean thresholds for discrete variables.
A numeric matrix (q rows x 1 column) of posterior mean continuous variable means.
A matrix with one row per post-warmup iteration, containing posterior samples of baseline main-effect parameters.
bgm(), bgmCompare(), extract_pairwise_interactions(),
extract_category_thresholds()
Other extractors:
extract_arguments(),
extract_category_thresholds(),
extract_ess(),
extract_group_params(),
extract_indicator_priors(),
extract_indicators(),
extract_log_odds(),
extract_pairwise_interactions(),
extract_partial_correlations(),
extract_posterior_inclusion_probabilities(),
extract_precision(),
extract_rhat(),
extract_sbm()
fit = bgm(x = Wenchuan[, 1:3]) extract_main_effects(fit)fit = bgm(x = Wenchuan[, 1:3]) extract_main_effects(fit)
Retrieves posterior samples of pairwise interaction parameters from a
model fitted with bgm() or bgmCompare().
extract_pairwise_interactions(bgms_object)extract_pairwise_interactions(bgms_object)
bgms_object |
A fitted model object of class |
A matrix with one row per post-warmup iteration and one column per edge, containing posterior samples of interaction strengths.
Columns correspond to all unique variable pairs.
Columns correspond to the baseline pairwise interaction parameters.
bgm(), bgmCompare(), extract_main_effects()
Other extractors:
extract_arguments(),
extract_category_thresholds(),
extract_ess(),
extract_group_params(),
extract_indicator_priors(),
extract_indicators(),
extract_log_odds(),
extract_main_effects(),
extract_partial_correlations(),
extract_posterior_inclusion_probabilities(),
extract_precision(),
extract_rhat(),
extract_sbm()
Computes the posterior mean partial correlation matrix from a model fitted
with bgm(). For GGM models this is the full matrix. For mixed
MRF models this is the matrix for the continuous block. OMRF models
have no partial correlations and return NULL.
Partial correlations are computed from the precision matrix as
.
extract_partial_correlations(bgms_object)extract_partial_correlations(bgms_object)
bgms_object |
A fitted model object of class |
A named numeric matrix containing posterior mean partial
correlations, or NULL for OMRF models.
A symmetric matrix with ones on the diagonal and one row and column per variable.
A symmetric matrix with ones on the diagonal and one row and column per continuous variable.
NULL (invisibly).
Other extractors:
extract_arguments(),
extract_category_thresholds(),
extract_ess(),
extract_group_params(),
extract_indicator_priors(),
extract_indicators(),
extract_log_odds(),
extract_main_effects(),
extract_pairwise_interactions(),
extract_posterior_inclusion_probabilities(),
extract_precision(),
extract_rhat(),
extract_sbm()
fit = bgm( x = Wenchuan[, 1:3], variable_type = rep("continuous", 3) ) extract_partial_correlations(fit)fit = bgm( x = Wenchuan[, 1:3], variable_type = rep("continuous", 3) ) extract_partial_correlations(fit)
Computes posterior inclusion probabilities from a model fitted with
bgm() (edge inclusion) or bgmCompare() (difference inclusion).
extract_posterior_inclusion_probabilities(bgms_object)extract_posterior_inclusion_probabilities(bgms_object)
bgms_object |
A fitted model object of class |
A symmetric p x p matrix of posterior inclusion probabilities, with variable names as row and column names.
Off-diagonal entries are edge inclusion probabilities.
Requires edge_selection = TRUE.
Diagonal entries are main-effect inclusion
probabilities; off-diagonal entries are pairwise difference
inclusion probabilities. Requires difference_selection = TRUE.
bgm(), bgmCompare(), extract_indicators()
Other extractors:
extract_arguments(),
extract_category_thresholds(),
extract_ess(),
extract_group_params(),
extract_indicator_priors(),
extract_indicators(),
extract_log_odds(),
extract_main_effects(),
extract_pairwise_interactions(),
extract_partial_correlations(),
extract_precision(),
extract_rhat(),
extract_sbm()
Retrieves the posterior mean precision matrix from a model fitted with
bgm(). For GGM models this is the full precision matrix. For
mixed MRF models this is the precision matrix of the continuous
(Gaussian) block. OMRF models have no precision matrix and return NULL.
For mixed MRF models the precision matrix is reconstructed from the internal association-scale parameterization.
extract_precision(bgms_object)extract_precision(bgms_object)
bgms_object |
A fitted model object of class |
A named numeric matrix containing the posterior mean precision
matrix, or NULL for OMRF models.
A symmetric matrix with one row and column per variable.
A symmetric matrix with one row and column per continuous variable.
NULL (invisibly).
bgm(), coef.bgms(), extract_partial_correlations()
Other extractors:
extract_arguments(),
extract_category_thresholds(),
extract_ess(),
extract_group_params(),
extract_indicator_priors(),
extract_indicators(),
extract_log_odds(),
extract_main_effects(),
extract_pairwise_interactions(),
extract_partial_correlations(),
extract_posterior_inclusion_probabilities(),
extract_rhat(),
extract_sbm()
fit = bgm( x = Wenchuan[, 1:3], variable_type = rep("continuous", 3) ) extract_precision(fit)fit = bgm( x = Wenchuan[, 1:3], variable_type = rep("continuous", 3) ) extract_precision(fit)
Retrieves R-hat convergence diagnostics for all parameters from a
model fitted with bgm() or bgmCompare().
extract_rhat(bgms_object)extract_rhat(bgms_object)
bgms_object |
A fitted model object of class |
A named list with R-hat values for each parameter type present in
the model (e.g., main, pairwise, indicator).
bgm(), bgmCompare(), extract_ess()
Other extractors:
extract_arguments(),
extract_category_thresholds(),
extract_ess(),
extract_group_params(),
extract_indicator_priors(),
extract_indicators(),
extract_log_odds(),
extract_main_effects(),
extract_pairwise_interactions(),
extract_partial_correlations(),
extract_posterior_inclusion_probabilities(),
extract_precision(),
extract_sbm()
Retrieves posterior summaries from a model fitted with the Stochastic
Block prior. Works on both bgms fits (where SBM governs edge inclusion)
and bgmCompare fits (where SBM governs the off-diagonal pairwise
difference inclusions).
extract_sbm(bgms_object)extract_sbm(bgms_object)
bgms_object |
A fitted model object of class |
A list with elements posterior_num_blocks,
posterior_mean_allocations, posterior_mode_allocations, and
posterior_mean_coclustering_matrix. For bgms, requires
edge_selection = TRUE and edge_prior = sbm_prior(...). For
bgmCompare, requires difference_selection = TRUE and
difference_prior = sbm_prior(...).
bgm(), bgmCompare(), extract_indicators(),
extract_posterior_inclusion_probabilities()
Other extractors:
extract_arguments(),
extract_category_thresholds(),
extract_ess(),
extract_group_params(),
extract_indicator_priors(),
extract_indicators(),
extract_log_odds(),
extract_main_effects(),
extract_pairwise_interactions(),
extract_partial_correlations(),
extract_posterior_inclusion_probabilities(),
extract_precision(),
extract_rhat()
Specifies a Gamma(shape, rate) prior for positive scale parameters such as
the diagonal elements of the precision matrix. The default
gamma_prior(1, 1) corresponds to an Exponential(1) distribution.
gamma_prior(shape = 1, rate = 1)gamma_prior(shape = 1, rate = 1)
shape |
Positive numeric. Shape parameter of the Gamma distribution.
Default: |
rate |
Positive numeric. Rate parameter of the Gamma distribution.
Default: |
An object of class "bgms_scale_prior" with
family = "gamma".
Other prior-constructors:
bernoulli_prior(),
beta_bernoulli_prior(),
beta_prime_prior(),
cauchy_prior(),
exponential_prior(),
normal_prior(),
sbm_prior()
gamma_prior() gamma_prior(shape = 2, rate = 0.5)gamma_prior() gamma_prior(shape = 2, rate = 0.5)
Specifies a Normal(0, scale) prior on model parameters. Produces lighter-tailed shrinkage than the Cauchy prior and is better suited for simulation-based calibration (SBC) studies. Can be used for interactions, thresholds, or continuous means.
normal_prior(scale = 1)normal_prior(scale = 1)
scale |
Positive numeric. Standard deviation of the normal
distribution. Default: |
An object of class "bgms_parameter_prior" with
family = "normal".
cauchy_prior, beta_prime_prior,
bgm
Other prior-constructors:
bernoulli_prior(),
beta_bernoulli_prior(),
beta_prime_prior(),
cauchy_prior(),
exponential_prior(),
gamma_prior(),
sbm_prior()
normal_prior() normal_prior(scale = 0.5)normal_prior() normal_prior(scale = 0.5)
Computes conditional probability distributions for one or more variables
given the observed values of other variables in the data, using
group-specific parameters from a bgmCompare model.
## S3 method for class 'bgmCompare' predict( object, newdata, group, variables = NULL, type = c("probabilities", "response"), method = c("posterior-mean"), ... )## S3 method for class 'bgmCompare' predict( object, newdata, group, variables = NULL, type = c("probabilities", "response"), method = c("posterior-mean"), ... )
object |
An object of class |
newdata |
A matrix or data frame with |
group |
Integer specifying which group's parameters to use for prediction (1 to number of groups). Required argument. |
variables |
Which variables to predict. Can be:
|
type |
Character string specifying the type of prediction:
|
method |
Character string specifying which parameter estimates to use:
|
... |
Additional arguments (currently ignored). |
Group-specific parameters are obtained by applying the projection matrix to convert baseline parameters and differences into group-level estimates. The function then computes the conditional distribution of target variables given the observed values of all other variables.
For type = "probabilities": A named list with one
element per predicted variable. Each element is a matrix with
n rows and num_categories + 1 columns containing
for each observation and category.
For type = "response": A matrix with n rows and
length(variables) columns containing predicted categories.
predict.bgms for predicting
from single-group models,
simulate.bgmCompare for simulating
from group-comparison models.
Other prediction:
predict.bgms(),
simulate.bgmCompare(),
simulate.bgms(),
simulate_mrf()
# Fit a comparison model x = Boredom[Boredom$language == "fr", 2:6] y = Boredom[Boredom$language != "fr", 2:6] fit = bgmCompare(x, y, chains = 2) # Predict conditional probabilities using group 1 parameters probs_g1 = predict(fit, newdata = x[1:10, ], group = 1) # Predict responses using group 2 parameters pred_g2 = predict(fit, newdata = y[1:10, ], group = 2, type = "response")# Fit a comparison model x = Boredom[Boredom$language == "fr", 2:6] y = Boredom[Boredom$language != "fr", 2:6] fit = bgmCompare(x, y, chains = 2) # Predict conditional probabilities using group 1 parameters probs_g1 = predict(fit, newdata = x[1:10, ], group = 1) # Predict responses using group 2 parameters pred_g2 = predict(fit, newdata = y[1:10, ], group = 2, type = "response")
Computes conditional probability distributions for one or more variables given the observed values of other variables in the data. Supports ordinal, Blume-Capel, continuous (GGM), and mixed MRF models.
## S3 method for class 'bgms' predict( object, newdata, variables = NULL, type = c("probabilities", "response"), method = c("posterior-mean", "posterior-sample"), ndraws = NULL, seed = NULL, ... )## S3 method for class 'bgms' predict( object, newdata, variables = NULL, type = c("probabilities", "response"), method = c("posterior-mean", "posterior-sample"), ndraws = NULL, seed = NULL, ... )
object |
An object of class |
newdata |
A matrix or data frame with |
variables |
Which variables to predict. Can be:
|
type |
Character string specifying the type of prediction:
|
method |
Character string specifying which parameter estimates to use:
|
ndraws |
Number of posterior draws to use when
|
seed |
Optional random seed for reproducibility when
|
... |
Additional arguments (currently ignored). |
For each observation, the function computes the conditional distribution of the target variable(s) given the observed values of all other variables. This is the same conditional distribution used internally by the Gibbs sampler.
For GGM (continuous) models, the conditional distribution of
is Gaussian with mean
and variance , where
is the precision matrix.
Ordinal models:
For type = "probabilities": A named list with one element per
predicted variable. Each element is a matrix with n rows and
num_categories + 1 columns containing
for each observation and category.
For type = "response": A matrix with n rows and
length(variables) columns containing predicted categories.
When method = "posterior-sample", probabilities are averaged over
posterior draws, and an attribute "sd" is included containing the
standard deviation across draws.
GGM (continuous) models:
For type = "probabilities": A named list with one element per
predicted variable. Each element is a matrix with n rows and
2 columns ("mean" and "sd") containing the conditional
Gaussian parameters and
.
For type = "response": A matrix with n rows and
length(variables) columns containing conditional means.
When method = "posterior-sample", conditional parameters are
averaged over posterior draws, and an attribute "sd" is included.
Mixed MRF models:
For mixed models, the return list contains elements for both discrete and continuous predicted variables. Discrete variables return probability matrices (as in ordinal models); continuous variables return conditional mean and SD matrices (as in GGM models).
simulate.bgms for generating new data from the model.
Other prediction:
predict.bgmCompare(),
simulate.bgmCompare(),
simulate.bgms(),
simulate_mrf()
# Fit a model fit = bgm(x = Wenchuan[, 1:5], chains = 2) # Compute conditional probabilities for all variables probs = predict(fit, newdata = Wenchuan[1:10, 1:5]) # Predict the first variable only probs_v1 = predict(fit, newdata = Wenchuan[1:10, 1:5], variables = 1) # Get predicted categories pred_class = predict(fit, newdata = Wenchuan[1:10, 1:5], type = "response")# Fit a model fit = bgm(x = Wenchuan[, 1:5], chains = 2) # Compute conditional probabilities for all variables probs = predict(fit, newdata = Wenchuan[1:10, 1:5]) # Predict the first variable only probs_v1 = predict(fit, newdata = Wenchuan[1:10, 1:5], variables = 1) # Get predicted categories pred_class = predict(fit, newdata = Wenchuan[1:10, 1:5], type = "response")
bgmCompare objectsMinimal console output for bgmCompare fit objects.
## S3 method for class 'bgmCompare' print(x, ...)## S3 method for class 'bgmCompare' print(x, ...)
x |
An object of class |
... |
Ignored. |
Invisibly returns x.
bgmCompare(), summary.bgmCompare(), coef.bgmCompare()
Other posterior-methods:
coef.bgmCompare(),
coef.bgms(),
print.bgms(),
summary.bgmCompare(),
summary.bgms()
# See ?bgmCompare for a full example# See ?bgmCompare for a full example
bgms objectsMinimal console output for bgms fit objects.
## S3 method for class 'bgms' print(x, ...)## S3 method for class 'bgms' print(x, ...)
x |
An object of class |
... |
Ignored. |
Invisibly returns x.
bgm(), summary.bgms(), coef.bgms()
Other posterior-methods:
coef.bgmCompare(),
coef.bgms(),
print.bgmCompare(),
summary.bgmCompare(),
summary.bgms()
fit = bgm(x = Wenchuan[, 1:3]) print(fit)fit = bgm(x = Wenchuan[, 1:3]) print(fit)
Draws from the prior of a Gaussian graphical model. The likelihood is
omitted (, ), so the chain targets the prior alone.
Two specifications are supported via the spec argument:
"conditional" (default): fix a graph and
sample via the same constrained NUTS sampler
that drives bgm for continuous data. The chain
targets .
"joint": sample jointly from the
un-normalised joint prior .
Uses the adaptive-Metropolis MH chain from bgm with
edge selection on and the likelihood off, so the marginal on
is (joint
specification, not hierarchical). Useful for simulation-based
calibration of bgm's default sampler.
sample_ggm_prior( p, n_samples, n_warmup = 2000, interaction_prior = cauchy_prior(scale = 2.5), precision_scale_prior = gamma_prior(shape = 1, rate = 1), step_size = 0.1, max_depth = 10L, seed = 1L, verbose = TRUE, edge_indicators = NULL, delta = NULL, spec = c("conditional", "joint"), edge_inclusion_prob = 0.5 )sample_ggm_prior( p, n_samples, n_warmup = 2000, interaction_prior = cauchy_prior(scale = 2.5), precision_scale_prior = gamma_prior(shape = 1, rate = 1), step_size = 0.1, max_depth = 10L, seed = 1L, verbose = TRUE, edge_indicators = NULL, delta = NULL, spec = c("conditional", "joint"), edge_inclusion_prob = 0.5 )
p |
Integer. Dimension of the precision matrix ( |
n_samples |
Integer. Number of post-warmup draws to keep. |
n_warmup |
Integer. NUTS warmup iterations. Default |
interaction_prior |
A |
precision_scale_prior |
A |
step_size |
Positive numeric. Initial NUTS step size used to seed
dual-averaging adaptation. Default |
max_depth |
Integer. Maximum NUTS tree depth. Default |
seed |
Integer. RNG seed for the chain. Default |
verbose |
Logical. If |
edge_indicators |
Optional integer |
delta |
Non-negative numeric, or |
spec |
One of |
edge_inclusion_prob |
Probability in |
The priors are specified on the partial-association scale
: interaction_prior acts on
, and precision_scale_prior acts on
. The same convention is used by
bgm and by the continuous block of the mixed-MRF model, so
a prior argument passed here means the same distribution it would mean
there. Output samples are reported as entries of ; convert with
if you want them on the partial-association scale.
When spec = "conditional" and edge_indicators is supplied,
off-diagonals at excluded positions are constrained to zero throughout
the chain. edge_indicators is ignored when spec = "joint"
(the chain samples ).
A list with components
K_offdiagNumeric matrix of size
n_samples x p * (p - 1) / 2 containing the upper-triangle
off-diagonal entries of for each draw, in row-major order
(the upper triangle traversed by row)
. Under
spec = "conditional", excluded edges are returned as
0; under spec = "joint", off-diagonals at excluded
edges are sampled at 0 per the inclusion indicator.
K_diagNumeric matrix of size
n_samples x p containing the diagonal entries
.
offdiag_namesCharacter vector of length
p * (p - 1) / 2 naming the columns of K_offdiag
(e.g. "K_1_2").
diag_namesCharacter vector of length p naming
the columns of K_diag.
edge_indicatorsUnder spec = "conditional", the
p x p integer matrix of fixed inclusion indicators used
(full graph if not supplied). Under spec = "joint", an
n_samples x p(p-1)/2 integer matrix of sampled
indicators (column order matches
K_offdiag).
cauchy_prior, normal_prior,
gamma_prior, exponential_prior,
bgm
# Default Cauchy(0, 2.5) off-diagonal, Gamma(1, 1) diagonal, p = 4. draws = sample_ggm_prior( p = 4, n_samples = 200, n_warmup = 200, verbose = FALSE ) dim(draws$K_offdiag) # 200 x 6 colnames(draws$K_offdiag) = draws$offdiag_names head(draws$K_offdiag) # Sparser graph: drop the (1, 4) edge. E = matrix(1L, 4, 4) E[1, 4] = E[4, 1] = 0L draws = sample_ggm_prior( p = 4, n_samples = 200, n_warmup = 200, edge_indicators = E, verbose = FALSE ) colnames(draws$K_offdiag) = draws$offdiag_names all(draws$K_offdiag[, "K_1_4"] == 0) # TRUE# Default Cauchy(0, 2.5) off-diagonal, Gamma(1, 1) diagonal, p = 4. draws = sample_ggm_prior( p = 4, n_samples = 200, n_warmup = 200, verbose = FALSE ) dim(draws$K_offdiag) # 200 x 6 colnames(draws$K_offdiag) = draws$offdiag_names head(draws$K_offdiag) # Sparser graph: drop the (1, 4) edge. E = matrix(1L, 4, 4) E[1, 4] = E[4, 1] = 0L draws = sample_ggm_prior( p = 4, n_samples = 200, n_warmup = 200, edge_indicators = E, verbose = FALSE ) colnames(draws$K_offdiag) = draws$offdiag_names all(draws$K_offdiag[, "K_1_4"] == 0) # TRUE
Specifies a Stochastic Block Model (SBM) prior for inclusion indicators. Variables are assigned to latent clusters, with separate Beta priors on within-cluster and between-cluster inclusion probabilities.
sbm_prior( alpha = 1, beta = 1, alpha_between = 1, beta_between = 1, dirichlet_alpha = 1, lambda = 1 )sbm_prior( alpha = 1, beta = 1, alpha_between = 1, beta_between = 1, dirichlet_alpha = 1, lambda = 1 )
alpha |
Positive numeric. First shape parameter of the Beta
distribution for within-cluster edges. Default: |
beta |
Positive numeric. Second shape parameter of the Beta
distribution for within-cluster edges. Default: |
alpha_between |
Positive numeric. First shape parameter of the Beta
distribution for between-cluster edges. Default: |
beta_between |
Positive numeric. Second shape parameter of the Beta
distribution for between-cluster edges. Default: |
dirichlet_alpha |
Positive numeric. Concentration parameter of the
Dirichlet prior on cluster assignments. Default: |
lambda |
Positive numeric. Rate parameter of the zero-truncated
Poisson prior on the number of clusters. Default: |
An object of class "bgms_indicator_prior" with
family = "Stochastic-Block".
bernoulli_prior, beta_bernoulli_prior,
bgm
Other prior-constructors:
bernoulli_prior(),
beta_bernoulli_prior(),
beta_prime_prior(),
cauchy_prior(),
exponential_prior(),
gamma_prior(),
normal_prior()
sbm_prior() sbm_prior(alpha = 2, beta = 1, alpha_between = 1, beta_between = 5)sbm_prior() sbm_prior(alpha = 2, beta = 1, alpha_between = 1, beta_between = 5)
simulate_mrf() generates observations from a Markov Random
Field using user-specified parameters. For ordinal and
Blume-Capel variables, observations are generated via Gibbs
sampling. For continuous variables (Gaussian graphical model),
observations are drawn directly from the multivariate normal
distribution implied by the precision matrix.
simulate_mrf( num_states, num_variables, num_categories, pairwise, main, variable_type = "ordinal", baseline_category, iter = 1000, seed = NULL )simulate_mrf( num_states, num_variables, num_categories, pairwise, main, variable_type = "ordinal", baseline_category, iter = 1000, seed = NULL )
num_states |
The number of observations to be generated. |
num_variables |
The number of variables in the MRF. |
num_categories |
Either a positive integer or a vector
of positive integers of length |
pairwise |
A symmetric |
main |
For ordinal and Blume-Capel variables: a
|
variable_type |
What kind of variables are simulated? Can be a single
character string specifying the variable type of all |
baseline_category |
An integer vector of length
|
iter |
The number of iterations used by the Gibbs sampler
(ordinal/Blume-Capel variables only). The function provides the last state
of the Gibbs sampler as output. Ignored for continuous variables.
By default set to |
seed |
Optional integer seed for reproducibility. If |
Ordinal / Blume-Capel variables: The Gibbs sampler is initiated with random values from the response options, after which it proceeds by simulating states for each variable from its full conditional distribution given the other variable states.
Continuous variables (GGM):
Observations are drawn from
where is the precision matrix specified via
pairwise and is the means vector specified via main.
No Gibbs sampling is needed; iter is ignored.
There are two modeling options for the category thresholds. The default option assumes that the category thresholds are free, except that the first threshold is set to zero for identification. The user then only needs to specify the thresholds for the remaining response categories. This option is useful for any type of ordinal variable and gives the user the most freedom in specifying their model.
The Blume-Capel option is specifically designed for ordinal variables that have a special type of baseline_category category, such as the neutral category in a Likert scale. The Blume-Capel model specifies the following quadratic model for the threshold parameters:
where is the threshold for category c
(which now includes zero), offers a linear trend
across categories (increasing threshold values if
and decreasing threshold values if
), if , it offers an
increasing penalty for responding in a category further away from the
baseline_category category r, while suggests a
preference for responding in the baseline_category category.
A num_states by num_variables matrix of simulated
observations. For ordinal/Blume-Capel variables, entries are non-negative
integers. For continuous variables, entries are real-valued.
simulate.bgms for simulating from a fitted model.
Other prediction:
predict.bgmCompare(),
predict.bgms(),
simulate.bgmCompare(),
simulate.bgms()
# Generate responses from a network of five binary and ordinal variables. num_variables = 5 num_categories = sample(1:5, size = num_variables, replace = TRUE) Pairwise = matrix(0, nrow = num_variables, ncol = num_variables) Pairwise[2, 1] = Pairwise[4, 1] = Pairwise[3, 2] = Pairwise[5, 2] = Pairwise[5, 4] = .25 Pairwise = Pairwise + t(Pairwise) Main = matrix(0, nrow = num_variables, ncol = max(num_categories)) x = simulate_mrf( num_states = 1e3, num_variables = num_variables, num_categories = num_categories, pairwise = Pairwise, main = Main ) # Generate responses from a network of 2 ordinal and 3 Blume-Capel variables. num_variables = 5 num_categories = 4 Pairwise = matrix(0, nrow = num_variables, ncol = num_variables) Pairwise[2, 1] = Pairwise[4, 1] = Pairwise[3, 2] = Pairwise[5, 2] = Pairwise[5, 4] = .25 Pairwise = Pairwise + t(Pairwise) Main = matrix(NA, num_variables, num_categories) Main[, 1] = -1 Main[, 2] = -1 Main[3, ] = sort(-abs(rnorm(4)), decreasing = TRUE) Main[5, ] = sort(-abs(rnorm(4)), decreasing = TRUE) x = simulate_mrf( num_states = 1e3, num_variables = num_variables, num_categories = num_categories, pairwise = Pairwise, main = Main, variable_type = c("b", "b", "o", "b", "o"), baseline_category = 2 ) # Generate responses from a Gaussian graphical model (GGM) with 4 variables. num_variables = 4 # Precision matrix (symmetric, positive definite) Omega = diag(c(1, 1.2, 0.8, 1.5)) Omega[2, 1] = Omega[1, 2] = 0.3 Omega[3, 1] = Omega[1, 3] = 0.3 Omega[4, 2] = Omega[2, 4] = -0.2 x = simulate_mrf( num_states = 500, num_variables = num_variables, pairwise = Omega, variable_type = "continuous" )# Generate responses from a network of five binary and ordinal variables. num_variables = 5 num_categories = sample(1:5, size = num_variables, replace = TRUE) Pairwise = matrix(0, nrow = num_variables, ncol = num_variables) Pairwise[2, 1] = Pairwise[4, 1] = Pairwise[3, 2] = Pairwise[5, 2] = Pairwise[5, 4] = .25 Pairwise = Pairwise + t(Pairwise) Main = matrix(0, nrow = num_variables, ncol = max(num_categories)) x = simulate_mrf( num_states = 1e3, num_variables = num_variables, num_categories = num_categories, pairwise = Pairwise, main = Main ) # Generate responses from a network of 2 ordinal and 3 Blume-Capel variables. num_variables = 5 num_categories = 4 Pairwise = matrix(0, nrow = num_variables, ncol = num_variables) Pairwise[2, 1] = Pairwise[4, 1] = Pairwise[3, 2] = Pairwise[5, 2] = Pairwise[5, 4] = .25 Pairwise = Pairwise + t(Pairwise) Main = matrix(NA, num_variables, num_categories) Main[, 1] = -1 Main[, 2] = -1 Main[3, ] = sort(-abs(rnorm(4)), decreasing = TRUE) Main[5, ] = sort(-abs(rnorm(4)), decreasing = TRUE) x = simulate_mrf( num_states = 1e3, num_variables = num_variables, num_categories = num_categories, pairwise = Pairwise, main = Main, variable_type = c("b", "b", "o", "b", "o"), baseline_category = 2 ) # Generate responses from a Gaussian graphical model (GGM) with 4 variables. num_variables = 4 # Precision matrix (symmetric, positive definite) Omega = diag(c(1, 1.2, 0.8, 1.5)) Omega[2, 1] = Omega[1, 2] = 0.3 Omega[3, 1] = Omega[1, 3] = 0.3 Omega[4, 2] = Omega[2, 4] = -0.2 x = simulate_mrf( num_states = 500, num_variables = num_variables, pairwise = Omega, variable_type = "continuous" )
Generates new observations from the Markov Random Field model for a
specified group using the estimated parameters from a fitted
bgmCompare object.
## S3 method for class 'bgmCompare' simulate( object, nsim = 500, seed = NULL, group, method = c("posterior-mean"), iter = 1000, ... )## S3 method for class 'bgmCompare' simulate( object, nsim = 500, seed = NULL, group, method = c("posterior-mean"), iter = 1000, ... )
object |
An object of class |
nsim |
Number of observations to simulate. Default: |
seed |
Optional random seed for reproducibility. |
group |
Integer specifying which group to simulate from (1 to number of groups). Required argument. |
method |
Character string specifying which parameter estimates to use:
|
iter |
Number of Gibbs iterations for equilibration before collecting
samples. Default: |
... |
Additional arguments (currently ignored). |
Group-specific parameters are obtained by applying the projection matrix
to convert baseline parameters and differences into group-level estimates:
group_param = baseline + projection[group, ] %*% differences.
The function then uses these group-specific interaction and threshold parameters to generate new data via Gibbs sampling.
A matrix with nsim rows and p columns containing
simulated observations for the specified group.
simulate.bgms for simulating from single-group models,
predict.bgmCompare for computing conditional probabilities.
Other prediction:
predict.bgmCompare(),
predict.bgms(),
simulate.bgms(),
simulate_mrf()
# Fit a comparison model x = Boredom[Boredom$language == "fr", 2:6] y = Boredom[Boredom$language != "fr", 2:6] fit = bgmCompare(x, y, chains = 2) # Simulate 100 observations from group 1 new_data_g1 = simulate(fit, nsim = 100, group = 1) # Simulate 100 observations from group 2 new_data_g2 = simulate(fit, nsim = 100, group = 2)# Fit a comparison model x = Boredom[Boredom$language == "fr", 2:6] y = Boredom[Boredom$language != "fr", 2:6] fit = bgmCompare(x, y, chains = 2) # Simulate 100 observations from group 1 new_data_g1 = simulate(fit, nsim = 100, group = 1) # Simulate 100 observations from group 2 new_data_g2 = simulate(fit, nsim = 100, group = 2)
Generates new observations from the Markov Random Field model using the
estimated parameters from a fitted bgms object. Supports ordinal,
Blume-Capel, continuous (GGM), and mixed MRF models.
## S3 method for class 'bgms' simulate( object, nsim = 500, seed = NULL, method = c("posterior-mean", "posterior-sample"), ndraws = NULL, iter = 1000, cores = parallel::detectCores(), display_progress = c("per-chain", "total", "none"), ... )## S3 method for class 'bgms' simulate( object, nsim = 500, seed = NULL, method = c("posterior-mean", "posterior-sample"), ndraws = NULL, iter = 1000, cores = parallel::detectCores(), display_progress = c("per-chain", "total", "none"), ... )
object |
An object of class |
nsim |
Number of observations to simulate. Default: |
seed |
Optional random seed for reproducibility. |
method |
Character string specifying which parameter estimates to use:
|
ndraws |
Number of posterior draws to use when
|
iter |
Number of Gibbs iterations for equilibration before collecting
samples. Default: |
cores |
Number of CPU cores for parallel execution when
|
display_progress |
Character string specifying the type of progress bar.
Options: |
... |
Additional arguments (currently ignored). |
This function uses the estimated interaction and threshold
parameters to generate new data via Gibbs sampling. When
method = "posterior-sample", parameter uncertainty is
propagated to the simulated data by using different
posterior draws. Parallel processing is available for this method via the
cores argument.
If method = "posterior-mean": A matrix with nsim rows and
p columns containing simulated observations.
If method = "posterior-sample": A list of matrices, one per posterior
draw, each with nsim rows and p columns.
For mixed MRF models, discrete columns contain non-negative integers and continuous columns contain real-valued observations, ordered as in the original data.
predict.bgms for computing conditional probabilities,
simulate_mrf for simulation with user-specified parameters.
Other prediction:
predict.bgmCompare(),
predict.bgms(),
simulate.bgmCompare(),
simulate_mrf()
# Fit a model fit = bgm(x = Wenchuan[, 1:5], chains = 2) # Simulate 100 new observations using posterior means new_data = simulate(fit, nsim = 100) # Simulate with parameter uncertainty (10 datasets) new_data_list = simulate( fit, nsim = 100, method = "posterior-sample", ndraws = 10 ) # Use parallel processing for faster simulation new_data_list = simulate(fit, nsim = 100, method = "posterior-sample", ndraws = 100, cores = 2 )# Fit a model fit = bgm(x = Wenchuan[, 1:5], chains = 2) # Simulate 100 new observations using posterior means new_data = simulate(fit, nsim = 100) # Simulate with parameter uncertainty (10 datasets) new_data_list = simulate( fit, nsim = 100, method = "posterior-sample", ndraws = 10 ) # Use parallel processing for faster simulation new_data_list = simulate(fit, nsim = 100, method = "posterior-sample", ndraws = 100, cores = 2 )
bgmCompare objectsReturns posterior summaries and diagnostics for a fitted bgmCompare model.
## S3 method for class 'bgmCompare' summary(object, ...)## S3 method for class 'bgmCompare' summary(object, ...)
object |
An object of class |
... |
Currently ignored. |
An object of class summary.bgmCompare with posterior summaries.
bgmCompare(), print.bgmCompare(), coef.bgmCompare()
Other posterior-methods:
coef.bgmCompare(),
coef.bgms(),
print.bgmCompare(),
print.bgms(),
summary.bgms()
# See ?bgmCompare for a full example# See ?bgmCompare for a full example
bgms objectsReturns posterior summaries and diagnostics for a fitted bgms model.
## S3 method for class 'bgms' summary(object, ...)## S3 method for class 'bgms' summary(object, ...)
object |
An object of class |
... |
Currently ignored. |
An object of class summary.bgms with posterior summaries.
bgm(), print.bgms(), coef.bgms()
Other posterior-methods:
coef.bgmCompare(),
coef.bgms(),
print.bgmCompare(),
print.bgms(),
summary.bgmCompare()
fit = bgm(x = Wenchuan[, 1:3]) summary(fit)fit = bgm(x = Wenchuan[, 1:3]) summary(fit)
This dataset contains responses to 17 items assessing symptoms of post-traumatic stress disorder (PTSD) in Chinese adults who survived the 2008 Wenchuan earthquake and lost at least one child in the disaster (McNally et al. 2015). Participants completed the civilian version of the Posttraumatic Checklist, with each item corresponding to a DSM-IV PTSD symptom. Items were rated on a 5-point Likert scale from "not at all" to "extremely," indicating the degree to which the symptom bothered the respondent in the past month.
data("Wenchuan")data("Wenchuan")
A matrix with 362 rows and 17 columns. Each row represents a participant.
Repeated, disturbing memories, thoughts, or images of a stressful experience from the past?
Repeated, disturbing dreams of a stressful experience from the past?
Suddenly acting or feeling as if a stressful experience were happening again (as if you were reliving it)?
Feeling very upset when something reminded you of a stressful experience from the past?
Having physical reactions (e.g., heart pounding, trouble breathing, sweating) when something reminded you of a stressful experience from the past?
Avoiding thinking about or talking about a stressful experience from the past or avoiding having feelings related to it?
Avoiding activities or situations because they reminded you of a stressful experience from the past?
Trouble remembering important parts of a stressful experience from the past?
Loss of interest in activities that you used to enjoy?
Feeling distant or cut off from other people?
Feeling emotionally numb or being unable to have loving feelings for those close to you?
Feeling as if your future will somehow be cut short?
Trouble falling or staying asleep?
Feeling irritable or having angry outbursts?
Having difficulty concentrating?
Being "super-alert" or watchful or on guard?
Feeling jumpy or easily startled?
https://psychosystems.org/wp-content/uploads/2014/10/Wenchuan.csv
McNally RJ, Robinaugh DJ, Wu GWY, Wang L, Deserno MK, Borsboom D (2015). “Mental disorders as causal systems: A network approach to posttraumatic stress disorder.” Clinical Psychological Science, 6, 836–849. doi:10.1177/2167702614553230.