# Example 1: Presonalized conv checker --------------------------------------
# Dummy rule, if acceptance rate is near between .2 and .3.
convergence_example <- function(x) {
arate <- 1 - coda::rejectionRate(x)
all(
abs(arate - .25) < .05
)
}
# Tell fmcmc::MCMC what is the frequency
attr(convergence_example, "freq") <- 2e3
set.seed(223)
x <- rnorm(1000)
y <- x * 2 + rnorm(1000)
logpost <- function(p) {
sum(dnorm(y, mean = x * p, log = TRUE))
}
ans <- MCMC(
initial = 0, fun = logpost, nsteps = 5e4,
kernel= kernel_ram(),
conv_checker = convergence_example
)
# Example 2: Adding information ---------------------------------------------
# Here we do two things: Save a value and set a message for the user
convergence_example_with_info <- structure(function(x) {
arate <- 1 - coda::rejectionRate(x)
# Saving a value
if (!exists("arates", envir = LAST_CONV_CHECK, inherits = FALSE)) {
convergence_data_set(list(arates = arate))
} else {
convergence_data_set(list(
arates = rbind(convergence_data_get("arates"), arate)
))
}
# Setting up the message
convergence_msg_set(
sprintf("Current Avg. Accept. Rate: %.2f", mean(arate))
)
all(
abs(arate - .25) < .05
)
}, freq = 2000)
ans <- MCMC(
initial = 0, fun = logpost, nsteps = 5e4,
kernel= kernel_ram(),
conv_checker = convergence_example_with_info,
seed = 112,
progress = FALSE
)
Run the code above in your browser using DataLab