Optimize in cmdstanr

Hi–I have a cmdstanr issue. I don’t see a separate category for cmdstanr questions so I’m putting this in the general Interfaces category.

I have two issues.

  1. Is there a way to suppress the output? I’m running stan-optimize within a loop and it’s annoying and slows down my R to have to print 7 lines into the console for each run.

  2. Specifiying initial values is awkward. For example, I have a model with just a single parameter called “a”, and the call looks something like this:

model$optimize(data, init=function() list(a=5))

I just want to initialize a to the value 5, but I have to embed it in a function and a list!

I get that I can’t just do init=list(a=5) because then it will draw a from uniform(-5, 5). And I get that the function() list() thing is the right level of generality for many purposes. Still, it seems kinda ugly and it’s awkward to teach, so I’m wondering whether there could be a better option.

For example, what if we did init=list(a=5) if we wanted to just specify a fixed value, and we did init=list(a=uniform(-5,5)) if we wanted to do the uniform thing? That would be more logical, no?

To suppress all output in optimizing, add show_messages = FALSE:

opt <- mod$optimize(data = stan_data, show_messages = FALSE)
2 Likes

Thanks!

With the latest cmdstanr you can init with draws objects, e.g.

model$optimize(data, init=draws_df(a=0.5))

or

model$optimize(data, init=draws_df(a=runif(n=1)))

and if you want to init 4 chains with 4 random values

model$sample(data, init=draws_df(a=runif(n=4)))

and if you have mix of fixed and random values it works, too

model$sample(data, init=draws_df(a=runif(n=4), b=0.5)

Instead of draws_df() you can also use draws_list(), draws_matrix(), or draws_rvars().

For non-scalar parameters ,you need to use rvars, e.g. if
b is an array with length 2

draws_rvars(theta=0.5, b=rvar(array(runif(n=4*2),dim=c(4,2))))
4 Likes