File: MCMC-traces.Rd

package info (click to toggle)
r-cran-bayesplot 1.11.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 7,080 kB
  • sloc: sh: 13; makefile: 2
file content (372 lines) | stat: -rw-r--r-- 13,830 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/mcmc-traces.R
\name{MCMC-traces}
\alias{MCMC-traces}
\alias{mcmc_trace}
\alias{mcmc_trace_highlight}
\alias{trace_style_np}
\alias{mcmc_rank_overlay}
\alias{mcmc_rank_hist}
\alias{mcmc_rank_ecdf}
\alias{mcmc_trace_data}
\title{Trace and rank plots of MCMC draws}
\usage{
mcmc_trace(
  x,
  pars = character(),
  regex_pars = character(),
  transformations = list(),
  ...,
  facet_args = list(),
  n_warmup = 0,
  iter1 = 0,
  window = NULL,
  size = NULL,
  np = NULL,
  np_style = trace_style_np(),
  divergences = NULL
)

mcmc_trace_highlight(
  x,
  pars = character(),
  regex_pars = character(),
  transformations = list(),
  ...,
  facet_args = list(),
  n_warmup = 0,
  window = NULL,
  size = NULL,
  alpha = 0.2,
  highlight = 1
)

trace_style_np(div_color = "red", div_size = 0.25, div_alpha = 1)

mcmc_rank_overlay(
  x,
  pars = character(),
  regex_pars = character(),
  transformations = list(),
  facet_args = list(),
  ...,
  n_bins = 20,
  ref_line = FALSE
)

mcmc_rank_hist(
  x,
  pars = character(),
  regex_pars = character(),
  transformations = list(),
  ...,
  facet_args = list(),
  n_bins = 20,
  ref_line = FALSE
)

mcmc_rank_ecdf(
  x,
  pars = character(),
  regex_pars = character(),
  transformations = list(),
  ...,
  K = NULL,
  facet_args = list(),
  prob = 0.99,
  plot_diff = FALSE,
  interpolate_adj = NULL
)

mcmc_trace_data(
  x,
  pars = character(),
  regex_pars = character(),
  transformations = list(),
  ...,
  highlight = NULL,
  n_warmup = 0,
  iter1 = 0
)
}
\arguments{
\item{x}{An object containing MCMC draws:
\itemize{
\item A 3-D array, matrix, list of matrices, or data frame. The \link{MCMC-overview}
page provides details on how to specify each these.
\item A \code{draws} object from the \pkg{\link{posterior}} package (e.g.,
\code{draws_array}, \code{draws_rvars}, etc.).
\item An object with an \code{as.array()} method that returns the same kind of 3-D
array described on the \link{MCMC-overview} page.
}}

\item{pars}{An optional character vector of parameter names. If neither
\code{pars} nor \code{regex_pars} is specified then the default is to use \emph{all}
parameters. As of version \verb{1.7.0}, \strong{bayesplot} also supports 'tidy'
parameter selection by specifying \code{pars = vars(...)}, where \code{...} is
specified the same way as in \link[dplyr:select]{dplyr::select(...)} and
similar functions. Examples of using \code{pars} in this way can be found on the
\link[=tidy-params]{Tidy parameter selection} page.}

\item{regex_pars}{An optional \link[base:grep]{regular expression} to use for
parameter selection. Can be specified instead of \code{pars} or in addition to
\code{pars}. When using \code{pars} for tidy parameter selection, the \code{regex_pars}
argument is ignored since \link[tidyselect:language]{select helpers}
perform a similar function.}

\item{transformations}{Optionally, transformations to apply to parameters
before plotting. If \code{transformations} is a function or a single string
naming a function then that function will be used to transform all
parameters. To apply transformations to particular parameters, the
\code{transformations} argument can be a named list with length equal to
the number of parameters to be transformed. Currently only univariate
transformations of scalar parameters can be specified (multivariate
transformations will be implemented in a future release). If
\code{transformations} is a list, the name of each list element should be a
parameter name and the content of each list element should be a function
(or any item to match as a function via \code{\link[=match.fun]{match.fun()}}, e.g. a
string naming a function). If a function is specified by its name as a
string (e.g. \code{"log"}), then it can be used to construct a new
parameter label for the appropriate parameter (e.g. \code{"log(sigma)"}).
If a function itself is specified
(e.g. \code{log} or \code{function(x) log(x)})
then \code{"t"} is used in the new parameter label to indicate that the
parameter is transformed (e.g. \code{"t(sigma)"}).

Note: due to partial argument matching \code{transformations} can be
abbreviated for convenience in interactive use (e.g., \code{transform}).}

\item{...}{Currently ignored.}

\item{facet_args}{A named list of arguments (other than \code{facets}) passed
to \code{\link[ggplot2:facet_wrap]{ggplot2::facet_wrap()}} or \code{\link[ggplot2:facet_grid]{ggplot2::facet_grid()}}
to control faceting. Note: if \code{scales} is not included in \code{facet_args}
then \strong{bayesplot} may use \code{scales="free"} as the default (depending
on the plot) instead of the \strong{ggplot2} default of \code{scales="fixed"}.}

\item{n_warmup}{An integer; the number of warmup iterations included in
\code{x}. The default is \code{n_warmup = 0}, i.e. to assume no warmup
iterations are included. If \code{n_warmup > 0} then the background for
iterations \code{1:n_warmup} is shaded gray.}

\item{iter1}{An integer; the iteration number of the first included draw
(default is \code{0}). This can be used to make it more obvious that the warmup
iterations have been discarded from the traceplot. It cannot be specified
if \code{n_warmup} is also set to a positive value.}

\item{window}{An integer vector of length two specifying the limits of a
range of iterations to display.}

\item{size}{An optional value to override the default line size
for \code{mcmc_trace()} or the default point size for \code{mcmc_trace_highlight()}.}

\item{np}{For models fit using \link{NUTS} (more generally, any
\href{https://en.wikipedia.org/wiki/Symplectic_integrator}{symplectic integrator}),
an optional data frame providing NUTS diagnostic information. The data
frame should be the object returned by \code{\link[=nuts_params]{nuts_params()}} or one with the same
structure. If \code{np} is specified then tick marks are added to the bottom of
the trace plot indicating within which iterations there was a divergence
(if there were any). See the end of the \strong{Examples} section, below.}

\item{np_style}{A call to the \code{trace_style_np()} helper function to
specify arguments controlling the appearance of tick marks representing
divergences (if the \code{np} argument is specified).}

\item{divergences}{Deprecated. Use the \code{np} argument instead.}

\item{alpha}{For \code{mcmc_trace_highlight()}, passed to
\code{\link[ggplot2:geom_point]{ggplot2::geom_point()}} to control the transparency of the points
for the chains not highlighted.}

\item{highlight}{For \code{mcmc_trace_highlight()}, an integer specifying one
of the chains that will be more visible than the others in the plot.}

\item{div_color, div_size, div_alpha}{Optional arguments to the
\code{trace_style_np()} helper function that are eventually passed to
\code{\link[ggplot2:geom_rug]{ggplot2::geom_rug()}} if the \code{np} argument is also specified. They control
the color, size, and transparency specifications for showing divergences in
the plot. The default values are displayed in the \strong{Usage} section above.}

\item{n_bins}{For the rank plots, the number of bins to use for the histogram
of rank-normalized MCMC samples. Defaults to \code{20}.}

\item{ref_line}{For the rank plots, whether to draw a horizontal line at the
average number of ranks per bin. Defaults to \code{FALSE}.}

\item{K}{An optional integer defining the number of equally spaced evaluation
points for the PIT-ECDF. Reducing K when using \code{interpolate_adj = FALSE}
makes computing the confidence bands faster. For \code{ppc_pit_ecdf} and
\code{ppc_pit_ecdf_grouped}, if PIT values are supplied, defaults to
\code{length(pit)}, otherwise yrep determines the maximum accuracy of the
estimated PIT values and \code{K} is set to \code{min(nrow(yrep) + 1, 1000)}. For
\code{mcmc_rank_ecdf}, defaults to the number of iterations per chain in \code{x}.}

\item{prob}{For \code{mcmc_rank_ecdf()}, a value between 0 and 1
specifying the desired simultaneous confidence of the confidence bands to be
drawn for the rank ECDF plots.}

\item{plot_diff}{For \code{mcmc_rank_ecdf()}, a boolean specifying if the
difference between the observed rank ECDFs and the theoretical expectation
should be drawn instead of the unmodified rank ECDF plots.}

\item{interpolate_adj}{A boolean defining if the simultaneous confidence
bands should be interpolated based on precomputed values rather than
computed exactly. Computing the bands may be computationally intensive and
the approximation gives a fast method for assessing the ECDF trajectory.
The default is to use interpolation if \code{K} is greater than 200.}
}
\value{
The plotting functions return a ggplot object that can be further
customized using the \strong{ggplot2} package. The functions with suffix
\verb{_data()} return the data that would have been drawn by the plotting
function.

\code{mcmc_trace_data()} returns the data for the trace \emph{and} rank plots
in the same data frame.
}
\description{
Trace and rank plots of MCMC draws. See the \strong{Plot Descriptions}
section, below, for details.
}
\section{Plot Descriptions}{

\describe{
\item{\code{mcmc_trace()}}{
Standard trace plots of MCMC draws. For models fit using \link{NUTS},
the \code{np} argument can be used to also show divergences on the trace plot.
}
\item{\code{mcmc_trace_highlight()}}{
Traces are plotted using points rather than lines and the opacity of all
chains but one (specified by the \code{highlight} argument) is reduced.
}
\item{\code{mcmc_rank_hist()}}{
Whereas traditional trace plots visualize how the chains mix over the
course of sampling, rank histograms visualize how the values
from the chains mix together in terms of ranking. An ideal plot would
show the rankings mixing or overlapping in a uniform distribution.
See Vehtari et al. (2019) for details.
}
\item{\code{mcmc_rank_overlay()}}{
Ranks from \code{mcmc_rank_hist()} are plotted using overlaid lines in a
single panel.
}
\item{\code{mcmc_rank_ecdf()}}{
The ECDFs of the ranks from \code{mcmc_rank_hist()} are plotted with the
simultaneous confidence bands with a coverage determined by \code{prob}, that
is, bands that completely cover all of the rank ECDFs with the probability
\code{prob}. If \code{plot_diff = TRUE}, the difference between the observed rank
ECDFs and the theoretical expectation for samples originating from the
same distribution is drawn. See Säilynoja et al. (2021) for details.
}
}
}

\examples{
# some parameter draws to use for demonstration
x <- example_mcmc_draws(chains = 4, params = 6)
dim(x)
dimnames(x)

# trace plots of the betas
color_scheme_set("viridis")
mcmc_trace(x, regex_pars = "beta")
\donttest{
color_scheme_set("viridisA")
mcmc_trace(x, regex_pars = "beta")

color_scheme_set("viridisC")
mcmc_trace(x, regex_pars = "beta")
}

# mix color schemes
color_scheme_set("mix-blue-red")
mcmc_trace(x, regex_pars = "beta")

# use traditional ggplot discrete color scale
mcmc_trace(x, pars = c("alpha", "sigma")) +
 ggplot2::scale_color_discrete()

# zoom in on a window of iterations, increase line size,
# add tick marks, move legend to the top, add gray background
color_scheme_set("viridisA")
mcmc_trace(x[,, 1:4], window = c(100, 130), size = 1) +
  panel_bg(fill = "gray90", color = NA) +
  legend_move("top")

# Rank-normalized histogram plots. Instead of showing how chains mix over
# time, look at how the ranking of MCMC samples mixed between chains.
color_scheme_set("viridisE")
mcmc_rank_hist(x, "alpha")
mcmc_rank_hist(x, pars = c("alpha", "sigma"), ref_line = TRUE)
mcmc_rank_overlay(x, "alpha")

# ECDF and ECDF difference plots of the ranking of MCMC samples between chains.
# Provide 99\% simultaneous confidence intervals for the chains sampling from
# the same distribution.
mcmc_rank_ecdf(x, prob = 0.99)
mcmc_rank_ecdf(x, prob = 0.99, plot_diff = TRUE)

\dontrun{
# parse facet label text
color_scheme_set("purple")
p <- mcmc_trace(
  x,
  regex_pars = "beta\\\\[[1,3]\\\\]",
  facet_args = list(labeller = ggplot2::label_parsed)
)
p + facet_text(size = 15)

# mark first 100 draws as warmup
mcmc_trace(x, n_warmup = 100)

# plot as points, highlighting chain 2
color_scheme_set("brightblue")
mcmc_trace_highlight(x, pars = "sigma", highlight = 2, size = 2)

# for models fit using HMC/NUTS divergences can be displayed in the trace plot
library("rstanarm")
fit <- stan_glm(mpg ~ ., data = mtcars, refresh = 0,
  # next line to keep example fast and also ensure we get some divergences
                prior = hs(), iter = 400, adapt_delta = 0.8)

# extract draws using as.array (instead of as.matrix) to keep
# chains separate for trace plot
posterior <- as.array(fit)

# for stanfit and stanreg objects use nuts_params() to get the divergences
mcmc_trace(posterior, pars = "sigma", np = nuts_params(fit))

color_scheme_set("viridis")
mcmc_trace(
  posterior,
  pars = c("wt", "sigma"),
  size = 0.5,
  facet_args = list(nrow = 2),
  np = nuts_params(fit),
  np_style = trace_style_np(div_color = "black", div_size = 0.5)
)
}

}
\references{
Vehtari, A., Gelman, A., Simpson, D., Carpenter, B., Bürkner, P.
(2019). Rank-normalization, folding, and localization: An improved \emph{R}-hat
for assessing convergence of MCMC. \href{https://arxiv.org/abs/1903.08008}{arXiv preprint}.

Säilynoja, T., Bürkner, P., Vehtari, A.
(2021). Graphical Test for Discrete Uniformity and its Applications in
Goodness of Fit Evaluation and Multiple Sample Comparison \href{https://arxiv.org/abs/2103.10522}{arXiv preprint}.
}
\seealso{
Other MCMC: 
\code{\link{MCMC-combos}},
\code{\link{MCMC-diagnostics}},
\code{\link{MCMC-distributions}},
\code{\link{MCMC-intervals}},
\code{\link{MCMC-nuts}},
\code{\link{MCMC-overview}},
\code{\link{MCMC-parcoord}},
\code{\link{MCMC-recover}},
\code{\link{MCMC-scatterplots}}
}
\concept{MCMC}