Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Drawing from posterior with generated_quantities: MethodError in dot_assume #2136

Closed
simonsteiger opened this issue Nov 26, 2023 · 2 comments

Comments

@simonsteiger
Copy link

simonsteiger commented Nov 26, 2023

Hi,

I have been using the generated_quantities function to draw samples from the posterior distribution (as described in this youtube video at around 1h into the video).

This has been working until I recently updated the packages, but now there's an error for models using broadcasting.

using Turing

@model function binoflip(n, k)
    p ~ Beta(1, 1)
    k ~ Binomial(n, p)
    return (; p, k)
end

n = 100
k = sum(rand(Bernoulli(0.3), n) .== 1)

model_binoflip = binoflip(n, k)
chain_binoflip = sample(model_binoflip, NUTS(), 1000)

quantities_binoflip = let 
    model_missing_binoflip = binoflip(n, missing)
    generated_quantities(model_missing_binoflip, chain_binoflip)
end
# Looks good!

@model function bernflip(y)
    p ~ Beta(1, 1)
    y .~ Bernoulli.(p)
    return (; p, y)
end

y = rand(Bernoulli(0.3), n)

model_bernflip = bernflip(y)
chain_bernflip = sample(model_bernflip, NUTS(), 1000)

quantities_bernflip = let 
    model_missing_bernflip = bernflip(missing)
    generated_quantities(model_missing_bernflip, chain_bernflip)
end
# MethodError: no method matching dot_assume(...)
@torfjelde
Copy link
Member

.~ has, in almost all cases, the same semantics as .=.

This means that when you write

y .~ dist

internally this is, effectively, converted into

# some other stuff
# ...
# and then
y .= rand(...)

Now, if you define y to be missing, this will not work (it doesn't make sense to do missing .= ...).

Are you sure this used to work before you updated?

Nonetheless, you can fix this by replacing

y .~ Bernoulli.(p)

with

y ~ arraydist(Bernoulli.(p))

@simonsteiger
Copy link
Author

simonsteiger commented Dec 13, 2023

Thank you for the explanation!

I went back to the commit where I thought the code was working. If I read the Manifest correctly, Turing was on v0.24.4 before the update that I blamed. And indeed, only the model with ~, not the one with .~, worked with the above generated_quantities code. I must have recalled incorrectly, thinking that both were working. Sorry!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants