How to solve the error while loading saved chain as JLD2 file or JLS file?

JLD doesn’t appear to work out of the box, but I’m not sure why. Try using chain serialization (fixed below) instead, though we should probably get JLD working at some point because it’s a much more stable storage format that serialization.

You need to specify the type you want to receive in read. Currently you are calling read with a Chains object you already have. You need to do this instead:

chn2 = read("chain_i.jls", Chains)

Here’s a full copy-pasteable working example:

using Random
using Turing

# 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))
# g_data = CuArray(data)

# 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
iterations = 1000
# Start sampling.
chain = sample(coinflip(data), HMC(ϵ, τ), iterations);

write("chain.jls", chain)

chn2 = read("chain.jls", Chains)
1 Like