I am taking my first steps in Turing (and Julia) trying to solve a model inversion problem in a Hidden Markov Model. The model I have so far works fine with SMC()
, IS()
and PG()
. For HMC()
and NUTS()
I still have an issue I wasn’t able to further debug.
I created a (admittedly quite contrived) minimal working example that results in a TypeError
:
TypeError: in typeassert, expected Float64, got ForwardDiff.Dual{Nothing,Float64,10}
This is the minimal working example:
using Distributions
using LinearAlgebra
using Turing
# Linear Model
Δt = 0.1
τ = 1.0
A = [1.0 Δt-(Δt^2/(2τ)); 0.0 1.0-(Δt/τ)]
Q = [0.25 * Δt^4 0.5 * Δt^3; 0.5 * Δt^3 Δt^2] + 1e-6 * I
B = [0.0 Δt^2/(2τ); 0.0 Δt/τ]
u = [0.0; 0.5]
H = [1.0 0.0; 0.0 1.0;]
σₓ, σᵥ = 0.1, 0.1
R = [σₓ 0.0; 0.0 σᵥ]
@model function hmm(states, ::Type{T} = Array{Float64}) where {T}
# Initialize arrays for the time-series
if states === missing
states = T(undef, 2, 100)
end
observations = T(undef, 2, 100)
# Prior for first step
states[:,1] ~ MvNormal([0.0, 0.5], 0.001 * I)
# THIS IS WHERE I GET THE ERROR
observations[:,1] ~ MvNormal(states[:,1], R/Δt)
for t in 2:size(states, 2)
states[:,t] ~ MvNormal(A * states[:,t-1] + B * u, Δt*Q)
observations[:,t] ~ MvNormal(states[:,t], R/Δt)
end
return states
end
# Sample a trial from the prior to be used as the ground truth
hmm_prior = hmm(missing)
states = hmm_prior()
# Condition on the sampled trial
hmm_conditioned = hmm(states)
# Perform inference
chain = sample(hmm_conditioned, HMC(0.1, 5), 1000)
Can somebody tell, what I am missing here?
Thanks!
Simon