Getting generated_quantities from optimization result in Turing.jl

Suppose I optimize my Turing model to get some kind of reasonable parameter values… Is there a way to get the generated_quantities?

mapest = optimize(mymodel,MAP())
gen_quant = ???

I tried generated_quantities(model, opt_parms), but it did not work. I don’t know if it is possible, but I will leave a MWE for others to use. Computing the generated quantity outside of the model is one workaround: z = 1 - opt_parms.values[:p]

MWE

using Turing, Random, Optim

# Set the true probability of heads in a coin.
p_true = 0.5

# Iterate from having seen 0 observations to 100 observations.
Ns = 0:100

# Draw data from a Bernoulli distribution, i.e. draw heads or tails.
Random.seed!(12)
data = rand(Bernoulli(p_true), last(Ns))

# Declare our Turing model.
@model function coinflip(y)
    # Our prior belief about the probability of heads in a coin.
    p ~ Beta(1, 1)
    z =  1 - p

    # The number of observations.
    N = length(y)
    for n in 1:N
        # Heads or tails of a coin are drawn from a Bernoulli distribution.
        y[n] ~ Bernoulli(p)
    end
    return (;z)
end


model = coinflip(data)
opt_parms = optimize(model, MAP())
generated_quantities(model, opt_parms)

This is no good for general models as now the code can diverge in the two places leading to bugs. Thanks for the MWE!

No problem.

It might be worth making a feature request on GitHub.