Extract posterior draws — fit-method-draws • cmdstanr
Description: Extract posterior draws after MCMC or approximate posterior draws after variational approximation using formats provided by the posterior package. The variables include the parameters, transformed parameters, and generated quantities from the Stan program as well as lp__, the total log probability (target) accumulated in the model block.

# Extract posterior draws

Source: `R/fit.R`
`fit-method-draws.Rd`

Extract posterior draws after MCMC or approximate posterior draws after variational approximation using formats provided by the posterior package.

The variables include the parameters, transformed parameters, and generated quantities from the Stan program as well as `lp__`, the total log probability (`target`) accumulated in the model block.

    draws(
      variables = NULL,
      inc_warmup = FALSE,
      format = getOption("cmdstanr_draws_format")
    )

## Arguments

variables

  (character vector) Optionally, the names of the variables (parameters, transformed parameters, and generated quantities) to read in.

  - If `NULL` (the default) then all variables are included.

  - If an empty string (`variables=""`) then none are included.

  - For non-scalar variables all elements or specific elements can be selected:

    - `variables = "theta"` selects all elements of `theta`;

    - `variables = c("theta[1]", "theta[3]")` selects only the 1st and 3rd elements.

inc_warmup

  (logical) Should warmup draws be included? Defaults to `FALSE`. Ignored except when used with CmdStanMCMC objects.

format

  (string) The format of the returned draws or point estimates. Must be a valid format from the posterior package. The defaults are the following.

  - For sampling and generated quantities the default is `"draws_array"`. This format keeps the chains separate. To combine the chains use any of the other formats (e.g. `"draws_matrix"`).

  - For point estimates from optimization and approximate draws from variational inference the default is `"draws_matrix"`.

  To use a different format it can be specified as the full name of the format from the posterior package (e.g. `format = "draws_df"`) or omitting the `"draws_"` prefix (e.g. `format = "df"`).

  Changing the default format: To change the default format for an entire R session use `options(cmdstanr_draws_format = format)`, where `format` is the name (in quotes) of a valid format from the posterior package. For example `options(cmdstanr_draws_format = "draws_df")` will change the default to a data frame.

  Note about efficiency: For models with a large number of parameters (20k+) we recommend using the `"draws_list"` format, which is the most efficient and RAM friendly when combining draws from multiple chains. If speed or memory is not a constraint we recommend selecting the format that most suits the coding style of the post processing phase.

## Value

Depends on the value of `format`. The defaults are:

- For MCMC, a 3-D `draws_array` object (iteration x chain x variable).

- For standalone generated quantities, a 3-D `draws_array` object (iteration x chain x variable).

- For variational inference, a 2-D `draws_matrix` object (draw x variable) because there are no chains. An additional variable `lp_approx__` is also included, which is the log density of the variational approximation to the posterior evaluated at each of the draws.

- For optimization, a 1-row `draws_matrix` with one column per variable. These are not actually draws, just point estimates stored in the `draws_matrix` format. See `$mle()` to extract them as a numeric vector.

## See also

`CmdStanMCMC`, `CmdStanMLE`, `CmdStanVB`, `CmdStanGQ`

## Examples

    # \dontrun{
    # logistic regression with intercept alpha and coefficients beta
    fit <- cmdstanr_example("logistic", method = "sample")

    # returned as 3-D array (see ?posterior::draws_array)
    draws <- fit$draws()
    dim(draws)
    #> [1] 1000    4  105
    str(draws)
    #>  'draws_array' num [1:1000, 1:4, 1:105] -66.2 -64.2 -65.5 -66.1 -64.4 ...
    #>  - attr(*, "dimnames")=List of 3
    #>   ..$ iteration: chr [1:1000] "1" "2" "3" "4" ...
    #>   ..$ chain    : chr [1:4] "1" "2" "3" "4"
    #>   ..$ variable : chr [1:105] "lp__" "alpha" "beta[1]" "beta[2]" ...

    # can easily convert to other formats (data frame, matrix, list)
    # using the posterior package
    head(posterior::as_draws_matrix(draws))
    #> # A draws_matrix: 6 iterations, 1 chains, and 105 variables
    #>     variable
    #> draw lp__ alpha beta[1] beta[2] beta[3] log_lik[1] log_lik[2] log_lik[3]
    #>    1  -66 0.098   -0.85   -0.59    0.74      -0.65      -0.30      -0.84
    #>    2  -64 0.291   -0.57   -0.31    0.52      -0.55      -0.45      -0.58
    #>    3  -65 0.185   -0.32   -0.28    0.82      -0.65      -0.32      -0.62
    #>    4  -66 0.223   -0.38   -0.14    0.97      -0.62      -0.25      -0.44
    #>    5  -64 0.313   -0.65   -0.14    0.83      -0.53      -0.28      -0.37
    #>    6  -64 0.338   -0.74   -0.20    0.80      -0.52      -0.30      -0.39
    #> # ... with 97 more variables

    # or can specify 'format' argument to avoid manual conversion
    # matrix format combines all chains
    draws <- fit$draws(format = "matrix")
    head(draws)
    #> # A draws_matrix: 6 iterations, 1 chains, and 105 variables
    #>     variable
    #> draw lp__ alpha beta[1] beta[2] beta[3] log_lik[1] log_lik[2] log_lik[3]
    #>    1  -66 0.098   -0.85   -0.59    0.74      -0.65      -0.30      -0.84
    #>    2  -64 0.291   -0.57   -0.31    0.52      -0.55      -0.45      -0.58
    #>    3  -65 0.185   -0.32   -0.28    0.82      -0.65      -0.32      -0.62
    #>    4  -66 0.223   -0.38   -0.14    0.97      -0.62      -0.25      -0.44
    #>    5  -64 0.313   -0.65   -0.14    0.83      -0.53      -0.28      -0.37
    #>    6  -64 0.338   -0.74   -0.20    0.80      -0.52      -0.30      -0.39
    #> # ... with 97 more variables

    # can select specific parameters
    fit$draws("alpha")
    #> # A draws_array: 1000 iterations, 4 chains, and 1 variables
    #> , , variable = alpha
    #>
    #>          chain
    #> iteration     1     2    3     4
    #>         1 0.098 0.043 0.30 0.119
    #>         2 0.291 0.133 0.26 0.609
    #>         3 0.185 0.612 0.11 0.483
    #>         4 0.223 0.561 0.43 0.842
    #>         5 0.313 0.463 0.21 0.044
    #>
    #> # ... with 995 more iterations
    fit$draws("beta")  # selects entire vector beta
    #> # A draws_array: 1000 iterations, 4 chains, and 3 variables
    #> , , variable = beta[1]
    #>
    #>          chain
    #> iteration     1     2     3     4
    #>         1 -0.85 -1.03 -1.02 -0.77
    #>         2 -0.57 -0.76 -0.92 -0.44
    #>         3 -0.32 -0.65 -0.94 -0.31
    #>         4 -0.38 -0.95 -0.54 -0.49
    #>         5 -0.65 -0.91 -0.28 -0.75
    #>
    #> , , variable = beta[2]
    #>
    #>          chain
    #> iteration     1      2      3      4
    #>         1 -0.59 -0.120 -0.206  0.053
    #>         2 -0.31 -0.066 -0.353 -0.424
    #>         3 -0.28 -0.552  0.039 -0.239
    #>         4 -0.14 -0.550 -0.715 -0.513
    #>         5 -0.14 -0.153  0.147 -0.444
    #>
    #> , , variable = beta[3]
    #>
    #>          chain
    #> iteration    1    2    3    4
    #>         1 0.74 0.61 0.61 0.58
    #>         2 0.52 0.57 0.52 0.83
    #>         3 0.82 0.72 0.68 1.21
    #>         4 0.97 0.59 0.74 1.03
    #>         5 0.83 0.57 0.46 0.52
    #>
    #> # ... with 995 more iterations
    fit$draws(c("alpha", "beta[2]"))
    #> # A draws_array: 1000 iterations, 4 chains, and 2 variables
    #> , , variable = alpha
    #>
    #>          chain
    #> iteration     1     2    3     4
    #>         1 0.098 0.043 0.30 0.119
    #>         2 0.291 0.133 0.26 0.609
    #>         3 0.185 0.612 0.11 0.483
    #>         4 0.223 0.561 0.43 0.842
    #>         5 0.313 0.463 0.21 0.044
    #>
    #> , , variable = beta[2]
    #>
    #>          chain
    #> iteration     1      2      3      4
    #>         1 -0.59 -0.120 -0.206  0.053
    #>         2 -0.31 -0.066 -0.353 -0.424
    #>         3 -0.28 -0.552  0.039 -0.239
    #>         4 -0.14 -0.550 -0.715 -0.513
    #>         5 -0.14 -0.153  0.147 -0.444
    #>
    #> # ... with 995 more iterations

    # can be passed directly to bayesplot plotting functions
    bayesplot::color_scheme_set("brightblue")
    bayesplot::mcmc_dens(fit$draws(c("alpha", "beta")))

    bayesplot::mcmc_scatter(fit$draws(c("beta[1]", "beta[2]")), alpha = 0.3)

    # example using variational inference
    fit <- cmdstanr_example("logistic", method = "variational")
    head(fit$draws("beta")) # a matrix by default
    #> # A draws_matrix: 6 iterations, 1 chains, and 3 variables
    #>     variable
    #> draw beta[1] beta[2] beta[3]
    #>    1   -0.66  0.3552    1.03
    #>    2   -0.39 -0.0109    0.32
    #>    3   -0.65 -0.8123    0.59
    #>    4   -0.48  0.0005    0.86
    #>    5   -0.60 -0.4373    0.48
    #>    6   -1.04 -0.0197    1.13
    head(fit$draws("beta", format = "df"))
    #> # A draws_df: 6 iterations, 1 chains, and 3 variables
    #>   beta[1] beta[2] beta[3]
    #> 1   -0.66  0.3552    1.03
    #> 2   -0.39 -0.0109    0.32
    #> 3   -0.65 -0.8123    0.59
    #> 4   -0.48  0.0005    0.86
    #> 5   -0.60 -0.4373    0.48
    #> 6   -1.04 -0.0197    1.13
    #> # ... hidden reserved variables {'.chain', '.iteration', '.draw'}
    # }