The “vb” Function in R

  • Package: rstan

  • Purpose: Performs variational Bayesian inference on a Stan model

  • General class: Bayesian inference

  • Required argument(s):

    • object: A stan model compiled with a function like “stan_model”.

    • data: List or environment containing data for the Stan model.

  • Notable optional arguments:

    • pars: Names of parameters to monitor and return estimates for.

    • algorithm: The algorithm to use for variational inference, such as “meanfield” or “fullrank”.

    • iter: Number of iterations for the variational algorithm.

    • tol_rel_obj: Relative tolerance for the convergence criterion.

    • seed: Random seed for reproducibility.

  • Example:

  • # Load the rstan library
    library(rstan)

    # Define the Stan model code
    model_code <- '
    data {
    int<lower=0> N;
    real y[N];
    }
    parameters {
    real mu;
    real<lower=0> sigma;
    }
    model {
    y ~ normal(mu, sigma);
    }
    '

    # Compile the Stan model
    model <- stan_model(model_code = model_code)

    # Perform variational Bayesian inference
    N = 1000
    fit <- vb(model, data = list(N = N, y = rnorm(N)))

    # View summary of variational estimates
    summary(fit)

  • This example demonstrates how to use the “vb” function from the rstan package to perform variational Bayesian inference on a compiled Stan model. The function requires the result of fitting a Stan model (stanfit object) as input and allows specifying various optional arguments like parameters to monitor, the variational algorithm, convergence criteria, and random seed.

Previous
Previous

The “optimizing” Function in R

Next
Next

The “sampling” Function in R