Using DynamicHMC

Turing supports the use of DynamicHMC as a sampler through the DynamicNUTS function.

To use the DynamicNUTS function, you must import the DynamicHMC package as well as Turing. Turing does not formally require DynamicHMC but will include additional functionality if both packages are present.

Here is a brief example:

How to apply DynamicNUTS:

# Import Turing and DynamicHMC.
using DynamicHMC, Turing

# Model definition.
@model function gdemo(x, y)
~ InverseGamma(2, 3)
    m ~ Normal(0, sqrt(s²))
    x ~ Normal(m, sqrt(s²))
    return y ~ Normal(m, sqrt(s²))
end

# Pull 2,000 samples using DynamicNUTS.
dynamic_nuts = externalsampler(DynamicHMC.NUTS())
chn = sample(gdemo(1.5, 2.0), dynamic_nuts, 2000, progress=false)
Chains MCMC chain (2000×3×1 Array{Float64, 3}):

Iterations        = 1:1:2000
Number of chains  = 1
Samples per chain = 2000
Wall duration     = 7.4 seconds
Compute duration  = 7.4 seconds
parameters        = s², m
internals         = lp

Summary Statistics
  parameters      mean       std      mcse   ess_bulk   ess_tail      rhat   e ⋯
      Symbol   Float64   Float64   Float64    Float64    Float64   Float64     ⋯

          s²    1.9775    1.8487    0.0752   716.7028   928.7484    1.0006     ⋯
           m    1.1604    0.8163    0.0271   978.9692   971.4091    1.0009     ⋯
                                                                1 column omitted

Quantiles
  parameters      2.5%     25.0%     50.0%     75.0%     97.5%
      Symbol   Float64   Float64   Float64   Float64   Float64

          s²    0.5711    1.0423    1.4893    2.2648    6.4790
           m   -0.4639    0.6859    1.1469    1.6570    2.7352
Back to top