ArviZ.jl Quickstart

Note

This tutorial is adapted from ArviZ's quickstart.

Setup

Here we add the necessary packages for this notebook and load a few we will use throughout.

begin
    using ArviZ, CmdStan, Distributions, LinearAlgebra, PyPlot, Random, Soss, Turing
    using Soss.MeasureTheory: HalfCauchy
    using SampleChainsDynamicHMC: getchains, dynamichmc
end
# ArviZ ships with style sheets!
ArviZ.use_style("arviz-darkgrid")

Get started with plotting

ArviZ.jl is designed to be used with libraries like CmdStan, Turing.jl, and Soss.jl but works fine with raw arrays.

rng1 = Random.MersenneTwister(37772);
begin
    plot_posterior(randn(rng1, 100_000))
    gcf()
end

Plotting a dictionary of arrays, ArviZ.jl will interpret each key as the name of a different random variable. Each row of an array is treated as an independent series of draws from the variable, called a chain. Below, we have 10 chains of 50 draws each for four different distributions.

let
    s = (10, 50)
    plot_forest(
        Dict(
            "normal" => randn(rng1, s),
            "gumbel" => rand(rng1, Gumbel(), s),
            "student t" => rand(rng1, TDist(6), s),
            "exponential" => rand(rng1, Exponential(), s),
        ),
    )
    gcf()
end

Plotting with MCMCChains.jl's Chains objects produced by Turing.jl

ArviZ is designed to work well with high dimensional, labelled data. Consider the eight schools model, which roughly tries to measure the effectiveness of SAT classes at eight different schools. To show off ArviZ's labelling, I give the schools the names of a different eight schools.

This model is small enough to write down, is hierarchical, and uses labelling. Additionally, a centered parameterization causes divergences (which are interesting for illustration).

First we create our data and set some sampling parameters.

begin
    J = 8
    y = [28.0, 8.0, -3.0, 7.0, -1.0, 1.0, 18.0, 12.0]
    σ = [15.0, 10.0, 16.0, 11.0, 9.0, 11.0, 10.0, 18.0]
    schools = [
        "Choate",
        "Deerfield",
        "Phillips Andover",
        "Phillips Exeter",
        "Hotchkiss",
        "Lawrenceville",
        "St. Paul's",
        "Mt. Hermon",
    ]
    ndraws = 1_000
    ndraws_warmup = 1_000
    nchains = 4
end;

Now we write and run the model using Turing:

Turing.@model function model_turing(y, σ, J=length(y))
    μ ~ Normal(0, 5)
    τ ~ truncated(Cauchy(0, 5), 0, Inf)
    θ ~ filldist(Normal(μ, τ), J)
    for i in 1:J
        y[i] ~ Normal(θ[i], σ[i])
    end
end
model_turing (generic function with 3 methods)
rng2 = Random.MersenneTwister(16653);
begin
    param_mod_turing = model_turing(y, σ)
    sampler = NUTS(ndraws_warmup, 0.8)

    turing_chns = Turing.sample(
        rng2, model_turing(y, σ), sampler, MCMCThreads(), ndraws, nchains
    )
end;

Most ArviZ functions work fine with Chains objects from Turing:

begin
    plot_autocorr(turing_chns; var_names=["μ", "τ"])
    gcf()
end

Convert to InferenceData

For much more powerful querying, analysis and plotting, we can use built-in ArviZ utilities to convert Chains objects to xarray datasets. Note we are also giving some information about labelling.

ArviZ is built to work with InferenceData (a netcdf datastore that loads data into xarray datasets), and the more groups it has access to, the more powerful analyses it can perform.

idata_turing_post = from_mcmcchains(
    turing_chns;
    coords=Dict("school" => schools),
    dims=Dict("y" => ["school"], "σ" => ["school"], "θ" => ["school"]),
    library="Turing",
)
InferenceData
    • Dataset (xarray.Dataset)
      Dimensions:  (chain: 4, draw: 1000, school: 8)
      Coordinates:
        * chain    (chain) int64 1 2 3 4
        * draw     (draw) int64 1 2 3 4 5 6 7 8 9 ... 993 994 995 996 997 998 999 1000
        * school   (school) <U16 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
      Data variables:
          μ        (chain, draw) float64 2.165 -0.3012 -0.138 ... -1.124 -1.01 3.933
          τ        (chain, draw) float64 3.889 6.079 15.28 7.384 ... 6.474 5.583 4.12
          θ        (chain, draw, school) float64 3.638 3.869 2.71 ... 1.051 -0.513
      Attributes:
          created_at:         2022-05-11T19:17:54.113781
          arviz_version:      0.12.0
          start_time:         [1.65229664e+09 1.65229666e+09 1.65229664e+09 1.65229...
          stop_time:          [1.65229665e+09 1.65229666e+09 1.65229665e+09 1.65229...
          inference_library:  Turing

    • Dataset (xarray.Dataset)
      Dimensions:           (chain: 4, draw: 1000)
      Coordinates:
        * chain             (chain) int64 1 2 3 4
        * draw              (draw) int64 1 2 3 4 5 6 7 ... 995 996 997 998 999 1000
      Data variables:
          energy            (chain, draw) float64 61.6 62.57 69.19 ... 62.56 62.92
          energy_error      (chain, draw) float64 -0.0432 0.09601 ... 0.002727
          tree_depth        (chain, draw) int64 3 4 4 5 5 5 5 5 5 ... 4 4 4 5 5 5 5 5
          diverging         (chain, draw) bool False False False ... False False False
          step_size_nom     (chain, draw) float64 0.102 0.1489 ... 0.09994 0.09994
          acceptance_rate   (chain, draw) float64 0.9881 0.9158 ... 0.9961 0.9942
          log_density       (chain, draw) float64 -54.26 -58.95 ... -58.35 -56.61
          max_energy_error  (chain, draw) float64 0.1225 0.4607 ... -0.07489 -0.01799
          is_accept         (chain, draw) bool True True True True ... True True True
          lp                (chain, draw) float64 -54.26 -58.95 ... -58.35 -56.61
          step_size         (chain, draw) float64 0.102 0.1489 ... 0.09994 0.09994
          n_steps           (chain, draw) int64 15 15 31 31 31 31 ... 31 31 63 31 31
      Attributes:
          created_at:         2022-05-11T19:17:54.147292
          arviz_version:      0.12.0
          start_time:         [1.65229664e+09 1.65229666e+09 1.65229664e+09 1.65229...
          stop_time:          [1.65229665e+09 1.65229666e+09 1.65229665e+09 1.65229...
          inference_library:  Turing

Each group is an ArviZ.Dataset (a thinly wrapped xarray.Dataset). We can view a summary of the dataset.

idata_turing_post.posterior
Dataset (xarray.Dataset)
Dimensions:  (chain: 4, draw: 1000, school: 8)
Coordinates:
  * chain    (chain) int64 1 2 3 4
  * draw     (draw) int64 1 2 3 4 5 6 7 8 9 ... 993 994 995 996 997 998 999 1000
  * school   (school) <U16 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
Data variables:
    μ        (chain, draw) float64 2.165 -0.3012 -0.138 ... -1.124 -1.01 3.933
    τ        (chain, draw) float64 3.889 6.079 15.28 7.384 ... 6.474 5.583 4.12
    θ        (chain, draw, school) float64 3.638 3.869 2.71 ... 1.051 -0.513
Attributes:
    created_at:         2022-05-11T19:17:54.113781
    arviz_version:      0.12.0
    start_time:         [1.65229664e+09 1.65229666e+09 1.65229664e+09 1.65229...
    stop_time:          [1.65229665e+09 1.65229666e+09 1.65229665e+09 1.65229...
    inference_library:  Turing

Here is a plot of the trace. Note the intelligent labels.

begin
    plot_trace(idata_turing_post)
    gcf()
end

We can also generate summary stats...

summarystats(idata_turing_post)
variable mean sd hdi_3% hdi_97% mcse_mean mcse_sd ess_bulk ess_tail r_hat
"μ" 3.109 3.825 -2.144 9.651 1.06 0.767 13.0 6.0 1.22
"τ" 3.149 3.111 0.333 8.678 0.571 0.408 12.0 5.0 1.27
"θ[Choate]" 4.702 6.13 -4.11 15.717 1.401 1.006 14.0 7.0 1.19
"θ[Deerfield]" 3.456 5.119 -2.971 13.629 1.237 0.89 15.0 6.0 1.18
"θ[Phillips Andover]" 2.626 5.325 -5.428 13.259 0.923 0.658 29.0 1126.0 1.09
"θ[Phillips Exeter]" 3.459 5.045 -4.414 12.767 1.053 0.754 21.0 1488.0 1.12
"θ[Hotchkiss]" 2.41 4.653 -5.05 11.469 0.848 0.605 30.0 1264.0 1.09
"θ[Lawrenceville]" 2.794 4.972 -4.936 12.383 0.928 0.663 24.0 1228.0 1.11
"θ[St. Paul's]" 4.77 5.752 -2.478 15.962 1.474 1.063 12.0 6.0 1.23
"θ[Mt. Hermon]" 3.679 5.686 -4.95 15.484 1.118 0.799 21.0 1213.0 1.12

...and examine the energy distribution of the Hamiltonian sampler.

begin
    plot_energy(idata_turing_post)
    gcf()
end

Additional information in Turing.jl

With a few more steps, we can use Turing to compute additional useful groups to add to the InferenceData.

To sample from the prior, one simply calls sample but with the Prior sampler:

prior = Turing.sample(rng2, param_mod_turing, Prior(), ndraws);

To draw from the prior and posterior predictive distributions we can instantiate a "predictive model", i.e. a Turing model but with the observations set to missing, and then calling predict on the predictive model and the previously drawn samples:

begin
    # Instantiate the predictive model
    param_mod_predict = model_turing(similar(y, Missing), σ)
    # and then sample!
    prior_predictive = Turing.predict(rng2, param_mod_predict, prior)
    posterior_predictive = Turing.predict(rng2, param_mod_predict, turing_chns)
end;

And to extract the pointwise log-likelihoods, which is useful if you want to compute metrics such as loo,

log_likelihood = let
    log_likelihood = Turing.pointwise_loglikelihoods(
        param_mod_turing, MCMCChains.get_sections(turing_chns, :parameters)
    )
    # Ensure the ordering of the loglikelihoods matches the ordering of `posterior_predictive`
    ynames = string.(keys(posterior_predictive))
    log_likelihood_y = getindex.(Ref(log_likelihood), ynames)
    # Reshape into `(nchains, ndraws, size(y)...)`
    Dict("y" => permutedims(cat(log_likelihood_y...; dims=3), (2, 1, 3)))
end;

This can then be included in the from_mcmcchains call from above:

idata_turing = from_mcmcchains(
    turing_chns;
    posterior_predictive,
    log_likelihood,
    prior,
    prior_predictive,
    observed_data=Dict("y" => y),
    coords=Dict("school" => schools),
    dims=Dict("y" => ["school"], "σ" => ["school"], "θ" => ["school"]),
    library="Turing",
)
InferenceData
    • Dataset (xarray.Dataset)
      Dimensions:  (chain: 4, draw: 1000, school: 8)
      Coordinates:
        * chain    (chain) int64 1 2 3 4
        * draw     (draw) int64 1 2 3 4 5 6 7 8 9 ... 993 994 995 996 997 998 999 1000
        * school   (school) <U16 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
      Data variables:
          μ        (chain, draw) float64 2.165 -0.3012 -0.138 ... -1.124 -1.01 3.933
          τ        (chain, draw) float64 3.889 6.079 15.28 7.384 ... 6.474 5.583 4.12
          θ        (chain, draw, school) float64 3.638 3.869 2.71 ... 1.051 -0.513
      Attributes:
          created_at:         2022-05-11T19:18:23.053023
          arviz_version:      0.12.0
          start_time:         [1.65229664e+09 1.65229666e+09 1.65229664e+09 1.65229...
          stop_time:          [1.65229665e+09 1.65229666e+09 1.65229665e+09 1.65229...
          inference_library:  Turing

    • Dataset (xarray.Dataset)
      Dimensions:  (chain: 4, draw: 1000, school: 8)
      Coordinates:
        * chain    (chain) int64 1 2 3 4
        * draw     (draw) int64 1 2 3 4 5 6 7 8 9 ... 993 994 995 996 997 998 999 1000
        * school   (school) <U16 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
      Data variables:
          y        (chain, draw, school) float64 22.59 0.6308 20.01 ... -2.753 -21.02
      Attributes:
          start_time:         [None, None, None, None]
          created_at:         2022-05-11T19:18:22.563642
          stop_time:          [None, None, None, None]
          arviz_version:      0.12.0
          inference_library:  Turing

    • Dataset (xarray.Dataset)
      Dimensions:  (chain: 4, draw: 1000, school: 8)
      Coordinates:
        * chain    (chain) int64 1 2 3 4
        * draw     (draw) int64 1 2 3 4 5 6 7 8 9 ... 993 994 995 996 997 998 999 1000
        * school   (school) <U16 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
      Data variables:
          y        (chain, draw, school) float64 -4.946 -3.307 ... -4.658 -4.051
      Attributes:
          created_at:         2022-05-11T19:18:22.985100
          arviz_version:      0.12.0
          inference_library:  Turing

    • Dataset (xarray.Dataset)
      Dimensions:           (chain: 4, draw: 1000)
      Coordinates:
        * chain             (chain) int64 1 2 3 4
        * draw              (draw) int64 1 2 3 4 5 6 7 ... 995 996 997 998 999 1000
      Data variables:
          energy            (chain, draw) float64 61.6 62.57 69.19 ... 62.56 62.92
          energy_error      (chain, draw) float64 -0.0432 0.09601 ... 0.002727
          tree_depth        (chain, draw) int64 3 4 4 5 5 5 5 5 5 ... 4 4 4 5 5 5 5 5
          diverging         (chain, draw) bool False False False ... False False False
          step_size_nom     (chain, draw) float64 0.102 0.1489 ... 0.09994 0.09994
          acceptance_rate   (chain, draw) float64 0.9881 0.9158 ... 0.9961 0.9942
          log_density       (chain, draw) float64 -54.26 -58.95 ... -58.35 -56.61
          max_energy_error  (chain, draw) float64 0.1225 0.4607 ... -0.07489 -0.01799
          is_accept         (chain, draw) bool True True True True ... True True True
          lp                (chain, draw) float64 -54.26 -58.95 ... -58.35 -56.61
          step_size         (chain, draw) float64 0.102 0.1489 ... 0.09994 0.09994
          n_steps           (chain, draw) int64 15 15 31 31 31 31 ... 31 31 63 31 31
      Attributes:
          created_at:         2022-05-11T19:18:23.057295
          arviz_version:      0.12.0
          start_time:         [1.65229664e+09 1.65229666e+09 1.65229664e+09 1.65229...
          stop_time:          [1.65229665e+09 1.65229666e+09 1.65229665e+09 1.65229...
          inference_library:  Turing

    • Dataset (xarray.Dataset)
      Dimensions:  (chain: 1, draw: 1000, school: 8)
      Coordinates:
        * chain    (chain) int64 1
        * draw     (draw) int64 1 2 3 4 5 6 7 8 9 ... 993 994 995 996 997 998 999 1000
        * school   (school) <U16 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
      Data variables:
          μ        (chain, draw) float64 8.628 -1.015 -3.058 ... 0.9541 6.471 8.363
          τ        (chain, draw) float64 4.816 1.663 1.182 19.69 ... 11.82 1.349 10.5
          θ        (chain, draw, school) float64 4.891 5.633 11.72 ... 11.28 11.92
      Attributes:
          created_at:         2022-05-11T19:18:24.464042
          arviz_version:      0.12.0
          start_time:         1652296681.68964
          stop_time:          1652296689.568721
          inference_library:  Turing

    • Dataset (xarray.Dataset)
      Dimensions:  (chain: 1, draw: 1000, school: 8)
      Coordinates:
        * chain    (chain) int64 1
        * draw     (draw) int64 1 2 3 4 5 6 7 8 9 ... 993 994 995 996 997 998 999 1000
        * school   (school) <U16 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
      Data variables:
          y        (chain, draw, school) float64 -1.721 12.34 29.75 ... -10.13 18.5
      Attributes:
          created_at:         2022-05-11T19:18:24.348059
          arviz_version:      0.12.0
          inference_library:  Turing

    • Dataset (xarray.Dataset)
      Dimensions:  (chain: 1, draw: 1000)
      Coordinates:
        * chain    (chain) int64 1
        * draw     (draw) int64 1 2 3 4 5 6 7 8 9 ... 993 994 995 996 997 998 999 1000
      Data variables:
          lp       (chain, draw) float64 -61.87 -57.45 -48.72 ... -78.14 -50.08 -63.96
      Attributes:
          created_at:         2022-05-11T19:18:24.493568
          arviz_version:      0.12.0
          start_time:         1652296681.68964
          stop_time:          1652296689.568721
          inference_library:  Turing

    • Dataset (xarray.Dataset)
      Dimensions:  (school: 8)
      Coordinates:
        * school   (school) <U16 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
      Data variables:
          y        (school) float64 28.0 8.0 -3.0 7.0 -1.0 1.0 18.0 12.0
      Attributes:
          created_at:         2022-05-11T19:18:25.775228
          arviz_version:      0.12.0
          inference_library:  Turing

Then we can for example compute the expected leave-one-out (LOO) predictive density, which is an estimate of the out-of-distribution predictive fit of the model:

loo(idata_turing; pointwise=false) # higher is better
loo loo_se p_loo n_samples n_data_points warning loo_scale
-31.2054 1.59303 1.04645 4000 8 true "log"

If the model is well-calibrated, i.e. it replicates the true generative process well, the CDF of the pointwise LOO values should be similarly distributed to a uniform distribution. This can be inspected visually:

begin
    plot_loo_pit(idata_turing; y="y", ecdf=true)
    gcf()
end

Plotting with CmdStan.jl outputs

CmdStan.jl and StanSample.jl also default to producing Chains outputs, and we can easily plot these chains.

Here is the same centered eight schools model:

begin
    schools_code = """
    data {
      int<lower=0> J;
      real y[J];
      real<lower=0> sigma[J];
    }

    parameters {
      real mu;
      real<lower=0> tau;
      real theta[J];
    }

    model {
      mu ~ normal(0, 5);
      tau ~ cauchy(0, 5);
      theta ~ normal(mu, tau);
      y ~ normal(theta, sigma);
    }

    generated quantities {
        vector[J] log_lik;
        vector[J] y_hat;
        for (j in 1:J) {
            log_lik[j] = normal_lpdf(y[j] | theta[j], sigma[j]);
            y_hat[j] = normal_rng(theta[j], sigma[j]);
        }
    }
    """

    schools_data = Dict("J" => J, "y" => y, "sigma" => σ)
    stan_chns = mktempdir() do path
        stan_model = Stanmodel(;
            model=schools_code,
            name="schools",
            nchains,
            num_warmup=ndraws_warmup,
            num_samples=ndraws,
            output_format=:mcmcchains,
            random=CmdStan.Random(28983),
            tmpdir=path,
        )
        _, chns, _ = stan(stan_model, schools_data; summary=false)
        return chns
    end
end;
begin
    plot_density(stan_chns; var_names=["mu", "tau"])
    gcf()
end

Again, converting to InferenceData, we can get much richer labelling and mixing of data. Note that we're using the same from_cmdstan function used by ArviZ to process cmdstan output files, but through the power of dispatch in Julia, if we pass a Chains object, it instead uses ArviZ.jl's overloads, which forward to from_mcmcchains.

idata_stan = from_cmdstan(
    stan_chns;
    posterior_predictive="y_hat",
    observed_data=Dict("y" => schools_data["y"]),
    log_likelihood="log_lik",
    coords=Dict("school" => schools),
    dims=Dict(
        "y" => ["school"],
        "sigma" => ["school"],
        "theta" => ["school"],
        "log_lik" => ["school"],
        "y_hat" => ["school"],
    ),
)
InferenceData
    • Dataset (xarray.Dataset)
      Dimensions:  (chain: 4, draw: 1000, school: 8)
      Coordinates:
        * chain    (chain) int64 1 2 3 4
        * draw     (draw) int64 1 2 3 4 5 6 7 8 9 ... 993 994 995 996 997 998 999 1000
        * school   (school) <U16 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
      Data variables:
          theta    (chain, draw, school) float64 6.541 4.165 1.673 ... 7.588 7.146
          tau      (chain, draw) float64 2.026 3.44 2.047 ... 0.5002 0.5771 0.5771
          mu       (chain, draw) float64 5.864 4.849 3.906 5.24 ... 7.369 7.617 7.617
      Attributes:
          created_at:         2022-05-11T19:19:00.204108
          arviz_version:      0.12.0
          inference_library:  CmdStan

    • Dataset (xarray.Dataset)
      Dimensions:  (chain: 4, draw: 1000, school: 8)
      Coordinates:
        * chain    (chain) int64 1 2 3 4
        * draw     (draw) int64 1 2 3 4 5 6 7 8 9 ... 993 994 995 996 997 998 999 1000
        * school   (school) <U16 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
      Data variables:
          y_hat    (chain, draw, school) float64 -10.71 23.66 -9.425 ... 9.078 20.88
      Attributes:
          created_at:         2022-05-11T19:19:00.200374
          arviz_version:      0.12.0
          inference_library:  CmdStan

    • Dataset (xarray.Dataset)
      Dimensions:  (chain: 4, draw: 1000, school: 8)
      Coordinates:
        * chain    (chain) int64 1 2 3 4
        * draw     (draw) int64 1 2 3 4 5 6 7 8 9 ... 993 994 995 996 997 998 999 1000
        * school   (school) <U16 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
      Data variables:
          log_lik  (chain, draw, school) float64 -4.65 -3.295 -3.734 ... -3.764 -3.846
      Attributes:
          created_at:         2022-05-11T19:19:00.202167
          arviz_version:      0.12.0
          inference_library:  CmdStan

    • Dataset (xarray.Dataset)
      Dimensions:          (chain: 4, draw: 1000)
      Coordinates:
        * chain            (chain) int64 1 2 3 4
        * draw             (draw) int64 1 2 3 4 5 6 7 ... 994 995 996 997 998 999 1000
      Data variables:
          tree_depth       (chain, draw) int64 4 2 4 3 3 3 4 4 4 ... 1 1 2 1 2 1 5 3 2
          diverging        (chain, draw) bool False False False ... False True False
          energy           (chain, draw) float64 21.85 17.36 18.12 ... 11.01 16.54
          lp               (chain, draw) float64 -11.6 -14.53 -12.58 ... -6.09 -6.09
          step_size        (chain, draw) float64 0.2012 0.2012 ... 0.1493 0.1493
          acceptance_rate  (chain, draw) float64 0.9582 0.8976 ... 0.04874 1.587e-05
          n_steps          (chain, draw) int64 15 7 15 15 7 15 15 ... 5 1 5 3 31 9 3
      Attributes:
          created_at:         2022-05-11T19:19:00.206799
          arviz_version:      0.12.0
          inference_library:  CmdStan

    • Dataset (xarray.Dataset)
      Dimensions:  (school: 8)
      Coordinates:
        * school   (school) <U16 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
      Data variables:
          y        (school) float64 28.0 8.0 -3.0 7.0 -1.0 1.0 18.0 12.0
      Attributes:
          created_at:         2022-05-11T19:19:00.209578
          arviz_version:      0.12.0
          inference_library:  CmdStan

Here is a plot showing where the Hamiltonian sampler had divergences:

begin
    plot_pair(
        idata_stan;
        coords=Dict("school" => ["Choate", "Deerfield", "Phillips Andover"]),
        divergences=true,
    )
    gcf()
end