How can I solve "no method matching Chains" in Turing - Julia

Hi,

I am trying to learn as a beginner of Julia and Turing and run the following program given in Turing tutorial.

# Import libraries.
using Turing, StatsPlots, Random

# 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 coinflip(y) = begin
    # Our prior belief about the probability of heads in a coin.
    p ~ Beta(1, 1)

    # 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
end;

# Settings of the Hamiltonian Monte Carlo (HMC) sampler.
iterations = 1000
ϵ = 0.05
τ = 10

# Start sampling.
chain = sample(coinflip(data), HMC(iterations, ϵ, τ));

# Construct summary of the sampling process for the parameter p, i.e. the probability of heads in a coin.
psummary = Chains(chain[:p])
histogram(psummary)

https://turing.ml/docs/using-turing/quick-start

While running, I am getting the following error as follows:

MethodError: no method matching Chains(::Chains{Union{Missing, Float64},Float64,NamedTuple{(:parameters,),Tuple{Array{String,1}}},NamedTuple{(:samples, :hashedsummary),Tuple{Array{Turing.Utilities.Sample,1},Base.RefValue{Tuple{UInt64,Array{ChainDataFrame,1}}}}}})
Closest candidates are:
  Chains(::Chains{A,T,K,L}, !Matched::Any; sorted) where {A, T, K, L} at C:\Users\z5168736\.julia\packages\MCMCChains\x3N5v\src\chains.jl:144
  Chains(!Matched::AxisArrays.AxisArray{A,3,D,Ax} where Ax where D, !Matched::T, !Matched::K<:NamedTuple, !Matched::L<:NamedTuple) where {A, T, K<:NamedTuple, L<:NamedTuple} at C:\Users\z5168736\.julia\packages\MCMCChains\x3N5v\src\MCMCChains.jl:50
  Chains(!Matched::Array{Array{A<:Union{Missing, Real},1},1}) where A<:Union{Missing, Real} at C:\Users\z5168736\.julia\packages\MCMCChains\x3N5v\src\chains.jl:27
  ...
top-level scope at none:0

How can I solve this error?

Thanks in Advance !
Manu

The sample function already returns a Chains object. Meaning, you do not have to construct one explicitly.

Removing this line:

psummary = Chains(chain[:p])

Should solve the issue. The description in the tutorial has not been updated, we are a bit behind with updating the docs at the moment. But I will open a PR that fixes the explanation.

1 Like

You can do histogram(chain) or histogram(chain[:p]). chain[:p] is also an instance of Chains.

1 Like

@mohamed82008: Thanks a lot for your reply !!

@trappmartin: Thank you !!