Using SVI with arviz

Does anyone have a working code snipit for getting an SVI based model working with arviz? The current from_pryo function is mcmc specific and assumes a kernel.model attribute exists. Rather than wrapping in a mock object to make it work I was wondering if someone else had a working example through one of the dict methods.

Solved it:

posterior_samples = Predictive(
    sidewalk_model,
    num_samples=5000,
    return_sites=(
        "week", 
        "slippery", 
        "wet", 
        "sprinkler", 
        "sprinkler_probs", 
        "prcp_probs", 
        "prcp", 
        "wet_probs", 
        "tavg"
    )
).get_samples(*sprinker_model_params)

az_data = az.convert_to_inference_data(
    {k: np.expand_dims(v.detach().numpy(), 0) for k, v in posterior_samples.items()},
)

Another option is to use az.from_dict.

az_data = az.from_dict(
    {k: np.expand_dims(v.detach().numpy(), 0) for k, v in posterior_samples.items()},
)

will return the same output, and in addition, if you also had observed data and posterior predictive samples, you would be able to include them too in the same inference data which would allow you to use plot_ppc.

1 Like