I am trying to extract the Standard Deviation out of Turing for the parameter p but it kept giving me an error. I was tired and frustrated and I could not think straight. I guess I need to take a break.
The guide here is of no help https://turing.ml/dev/tutorials/
I get the error
ERROR: LoadError: MethodError: no method matching iterate(::Chains{Union{Missing, Real},Missing,NamedTuple{(:parameters,),Tuple{Array{String,1}}},NamedTuple{(:hashedsummary,),Tuple{Base.RefValue{Tuple{UInt64,Array{ChainDataFrame,1}}}}}})
Closest candidates are:
iterate(::Core.SimpleVector) at essentials.jl:600
iterate(::Core.SimpleVector, ::Any) at essentials.jl:600
iterate(::ExponentialBackOff) at error.jl:218
for
# personally extracting the statistics for the parameter p
p_mean = mean(chain[:p])[:mean][1] # Extracting the mean for parameter p
p_std = std(chain[:p])[:std][1] # Extracting the std for parameter p
println("Parameter p has a mean of $(p_mean) and a standard deviation of $(p_std)")
Here is the entire source code to reproduce the error.
# Import libraries.
using Turing
using Distributions, Random, Plots
# Set the true probability of heads in a coin.
p_true = 0.5
# We has 7 coin toss observations.
NumOfCoinToss = 7
# Draw data from a Bernoulli distribution, i.e. draw heads or tails.
Random.seed!(12345)
data = rand(Bernoulli(p_true), NumOfCoinToss)
@show data
println("The result of ",NumOfCoinToss," coin tosses are:")
commaflag=false
for coinresult in data
global commaflag
print(commaflag ? ", " : "")
print(coinresult == 1 ? "head" : "tail")
commaflag=true
end
println()
# Now we use Turing to find the unknown probability p
# Declare our Turing model.
@model coinflip(data) = begin
# Our prior belief about the unknown parameter p which is
# the probability of heads in a coin.
p ~ Beta(1, 1)
# The number of observations.
N = length(data)
for n in 1:N
# Heads or tails of a coin are drawn using
# a process which have a Bernoulli distribution
data[n] ~ Bernoulli(p)
end
end;
# Settings of the Hamiltonian Monte Carlo (HMC) sampler.
# If you never used HMC before then do not change the value
# of ϵ and τ from 0.05 and 10
samples = 1_000
ϵ = 0.05 # leapfrog step size
τ = 10 # leapfrog step numbers
# Start sampling.
chain = sample(coinflip(data), HMC(ϵ, τ), samples);
# Summarise results
describe(chain)
# Plot a summary of the sampling process for the parameter p, i.e. the probability of heads in a coin.
histogram(chain[:p])
# personally extracting the statistics for the parameter p
p_mean = mean(chain[:p])[:mean][1] # Extracting the mean for parameter p
p_std = std(chain[:p])[:std][1] # Extracting the std for parameter p
println("Parameter p has a mean of $(p_mean) and a standard deviation of $(p_std)")