(empirical-approx-overview)=
For most models we use sampling MCMC algorithms like Metropolis or NUTS. In PyMC we got used to store traces of MCMC samples and then do analysis using them. There is a similar concept for the variational inference submodule in PyMC: Empirical. This type of approximation stores particles for the SVGD sampler. There is no difference between independent SVGD particles and MCMC samples. Empirical acts as a bridge between MCMC sampling output and full-fledged VI utils like apply_replacements or sample_node. For the interface description, see variational_api_quickstart [blocked]. Here we will just focus on Emprical and give an overview of specific things for the Empirical approximation.
:::{post} Jan 13, 2023 :tags: variational inference, approximation :category: advanced, how-to :author: Maxim Kochurov, Raul Maldonado, Chris Fonnesbeck :::
Let's recall the problem from variational_api_quickstart [blocked] where we first got a NUTS trace
Great. First having a trace we can create Empirical approx
This type of approximation has it's own underlying storage for samples that is pytensor.shared itself
It has exactly the same number of samples that you had in trace before. In our particular case it is 50k. Another thing to notice is that if you have multitrace with more than one chain you'll get much more samples stored at once. We flatten all the trace for creating Empirical.
This histogram is about how we store samples. The structure is pretty simple: (n_samples, n_dim) The order of these variables is stored internally in the class and in most cases will not be needed for end user
Sampling from posterior is done uniformly with replacements. Call approx.sample(1000) and you'll get again the trace but the order is not determined. There is no way now to reconstruct the underlying trace again with approx.sample.
After sampling function is compiled sampling bacomes really fast
You see there is no order any more but reconstructed density is the same.
Previously we had a trace_cov function
Now we can estimate the same covariance using Empirical
That's a tensor object, which we need to evaluate.
Estimations are very close and differ due to precision error. We can get the mean in the same way
:::{include} ../page_footer.md :::