Working with InferenceData#

Here we present a collection of common manipulations you can use while working with InferenceData.

import arviz as az
import numpy as np
import xarray as xr
xr.set_options(display_expand_data=False, display_expand_attrs=False);

display_expand_data=False makes the default view for xarray.DataArray fold the data values to a single line. To explore the values, click on the icon on the left of the view, right under the xarray.DataArray text. It has no effect on Dataset objects that already default to folded views.

display_expand_attrs=False folds the attributes in both DataArray and Dataset objects to keep the views shorter. In this page we print DataArrays and Datasets several times and they always have the same attributes.

idata = az.load_arviz_data("centered_eight")
idata
arviz.InferenceData
    • <xarray.Dataset>
      Dimensions:  (chain: 4, draw: 500, school: 8)
      Coordinates:
        * chain    (chain) int64 0 1 2 3
        * draw     (draw) int64 0 1 2 3 4 5 6 7 8 ... 492 493 494 495 496 497 498 499
        * school   (school) object 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
      Data variables:
          mu       (chain, draw) float64 -3.477 -2.456 -2.826 ... 4.597 5.899 0.1614
          theta    (chain, draw, school) float64 1.669 -8.537 -2.623 ... 10.59 4.523
          tau      (chain, draw) float64 3.73 2.075 3.703 4.146 ... 8.346 7.711 5.407
      Attributes: (3)

    • <xarray.Dataset>
      Dimensions:  (chain: 4, draw: 500, school: 8)
      Coordinates:
        * chain    (chain) int64 0 1 2 3
        * draw     (draw) int64 0 1 2 3 4 5 6 7 8 ... 492 493 494 495 496 497 498 499
        * school   (school) object 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
      Data variables:
          obs      (chain, draw, school) float64 7.85 -19.03 -22.5 ... 4.698 -15.07
      Attributes: (3)

    • <xarray.Dataset>
      Dimensions:           (chain: 4, draw: 500, school: 8)
      Coordinates:
        * chain             (chain) int64 0 1 2 3
        * draw              (draw) int64 0 1 2 3 4 5 6 ... 493 494 495 496 497 498 499
        * school            (school) object 'Choate' 'Deerfield' ... 'Mt. Hermon'
      Data variables:
          tune              (chain, draw) bool True False False ... False False False
          depth             (chain, draw) int64 5 3 3 4 5 5 4 4 5 ... 4 4 4 5 5 5 5 5
          tree_size         (chain, draw) float64 31.0 7.0 7.0 15.0 ... 31.0 31.0 31.0
          lp                (chain, draw) float64 -59.05 -56.19 ... -63.62 -58.35
          energy_error      (chain, draw) float64 0.07387 -0.1841 ... -0.087 -0.003652
          step_size_bar     (chain, draw) float64 0.2417 0.2417 ... 0.1502 0.1502
          max_energy_error  (chain, draw) float64 0.131 -0.2067 ... -0.101 -0.1757
          energy            (chain, draw) float64 60.76 62.76 64.4 ... 67.77 67.21
          mean_tree_accept  (chain, draw) float64 0.9506 0.9906 ... 0.9875 0.9967
          step_size         (chain, draw) float64 0.1275 0.1275 ... 0.1064 0.1064
          diverging         (chain, draw) bool False False False ... False False False
          log_likelihood    (chain, draw, school) float64 -5.168 -4.589 ... -3.896
      Attributes: (3)

    • <xarray.Dataset>
      Dimensions:    (chain: 1, draw: 500, school: 8)
      Coordinates:
        * chain      (chain) int64 0
        * draw       (draw) int64 0 1 2 3 4 5 6 7 ... 492 493 494 495 496 497 498 499
        * school     (school) object 'Choate' 'Deerfield' ... 'Mt. Hermon'
      Data variables:
          tau        (chain, draw) float64 6.561 1.016 68.91 ... 1.56 5.949 0.7631
          tau_log__  (chain, draw) float64 1.881 0.01593 4.233 ... 1.783 -0.2704
          mu         (chain, draw) float64 5.293 0.8137 0.7122 ... -1.658 -3.273
          theta      (chain, draw, school) float64 2.357 7.371 7.251 ... -3.775 -3.555
          obs        (chain, draw, school) float64 -3.54 6.769 19.68 ... -21.16 -6.071
      Attributes: (3)

    • <xarray.Dataset>
      Dimensions:  (school: 8)
      Coordinates:
        * school   (school) object 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
      Data variables:
          obs      (school) float64 28.0 8.0 -3.0 7.0 -1.0 1.0 18.0 12.0
      Attributes: (3)

Get the dataset corresponding to a single group#

post = idata.posterior
post
<xarray.Dataset>
Dimensions:  (chain: 4, draw: 500, school: 8)
Coordinates:
  * chain    (chain) int64 0 1 2 3
  * draw     (draw) int64 0 1 2 3 4 5 6 7 8 ... 492 493 494 495 496 497 498 499
  * school   (school) object 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
Data variables:
    mu       (chain, draw) float64 -3.477 -2.456 -2.826 ... 4.597 5.899 0.1614
    theta    (chain, draw, school) float64 1.669 -8.537 -2.623 ... 10.59 4.523
    tau      (chain, draw) float64 3.73 2.075 3.703 4.146 ... 8.346 7.711 5.407
Attributes: (3)

Tip

You’ll have noticed we stored the posterior group in a new variable: post. As .copy() was not called, now using idata.posterior or post is equivalent.

Use this to keep your code short yet easy to read. Store the groups you’ll need very often as separate variables to use explicitly, but don’t delete the InferenceData parent. You’ll need it for many ArviZ functions to work properly. For example: plot_pair() needs data from sample_stats group to show divergences, compare() needs data from both log_likelihood and posterior groups, plot_loo_pit() needs not 2 but 3 groups: log_likelihood, posterior_predictive and posterior.

Add a new variable#

post["log_tau"] = np.log(post["tau"])
idata.posterior
<xarray.Dataset>
Dimensions:  (chain: 4, draw: 500, school: 8)
Coordinates:
  * chain    (chain) int64 0 1 2 3
  * draw     (draw) int64 0 1 2 3 4 5 6 7 8 ... 492 493 494 495 496 497 498 499
  * school   (school) object 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
Data variables:
    mu       (chain, draw) float64 -3.477 -2.456 -2.826 ... 4.597 5.899 0.1614
    theta    (chain, draw, school) float64 1.669 -8.537 -2.623 ... 10.59 4.523
    tau      (chain, draw) float64 3.73 2.075 3.703 4.146 ... 8.346 7.711 5.407
    log_tau  (chain, draw) float64 1.316 0.7301 1.309 ... 2.122 2.043 1.688
Attributes: (3)

Combine chains and draws#

stacked = az.extract_dataset(idata)
stacked
<xarray.Dataset>
Dimensions:  (school: 8, sample: 2000)
Coordinates:
  * school   (school) object 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
  * sample   (sample) MultiIndex
  - chain    (sample) int64 0 0 0 0 0 0 0 0 0 0 0 0 0 3 3 3 3 3 3 3 3 3 3 3 3 3
  - draw     (sample) int64 0 1 2 3 4 5 6 7 ... 492 493 494 495 496 497 498 499
Data variables:
    mu       (sample) float64 -3.477 -2.456 -2.826 -1.996 ... 4.597 5.899 0.1614
    theta    (school, sample) float64 1.669 -6.239 2.195 ... -1.095 4.013 4.523
    tau      (sample) float64 3.73 2.075 3.703 4.146 ... 8.589 8.346 7.711 5.407
    log_tau  (sample) float64 1.316 0.7301 1.309 1.422 ... 2.122 2.043 1.688
Attributes: (3)

You can also use xarray.Dataset.stack() if you only want to combine the chain and draw dimensions. arviz.extract_dataset() is a convenience function aimed at taking care of the most common subsetting operations with MCMC samples. It can:

  • Combine chains and draws

  • Return a subset of variables (with optional filtering with regular expressions or string matching)

  • Return a subset of samples. Moreover by default it returns a random subset to prevent getting non-representative samples due to bad mixing.

  • Acess any group

Get a random subset of the samples#

az.extract_dataset(idata, num_samples=100)
<xarray.Dataset>
Dimensions:  (school: 8, sample: 100)
Coordinates:
  * school   (school) object 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
  * sample   (sample) MultiIndex
  - chain    (sample) int64 0 0 0 3 1 2 2 2 3 2 1 0 ... 3 3 3 1 1 0 1 1 1 1 2 3
  - draw     (sample) int64 419 274 161 193 178 203 ... 238 49 212 448 95 412
Data variables:
    mu       (sample) float64 6.95 7.4 4.131 1.644 ... 5.142 1.917 8.56 3.486
    theta    (school, sample) float64 8.734 3.829 19.1 ... 3.086 11.3 3.606
    tau      (sample) float64 1.867 1.603 8.83 1.929 ... 1.636 5.707 5.941 1.582
    log_tau  (sample) float64 0.6243 0.4717 2.178 0.6572 ... 1.742 1.782 0.4588
Attributes: (3)

Tip

Use a random seed to get the same subset from multiple groups: az.extract_dataset(idata, num_samples=100, rng=3) and az.extract_dataset(idata, group="log_likelihood", num_samples=100, rng=3) will continue to have matching samples

Obtain a NumPy array for a given parameter#

Let’s say we want to get the values for mu as a NumPy array.

stacked.mu.values
array([-3.47698606, -2.45587061, -2.82625433, ...,  4.59705819,
        5.89850592,  0.16138927])

Get the dimension lengths#

Let’s check how many groups are in our hierarchical model.

len(idata.observed_data.school)
8

Get coordinate values#

What are the names of the groups in our hierarchical model? You can access them from the coordinate name school in this case

idata.observed_data.school
<xarray.DataArray 'school' (school: 8)>
'Choate' 'Deerfield' 'Phillips Andover' ... "St. Paul's" 'Mt. Hermon'
Coordinates:
  * school   (school) object 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'

Get a subset of chains#

Let’s keep only chain 0 and 2 here. For the subset to take effect on all relevant InferenceData groups: posterior, sample_stats, log_likelihood, posterior_predictive we will use the arviz.InferenceData.sel(), the method of InferenceData instead of xarray.Dataset.sel().

idata.sel(chain=[0, 2])
arviz.InferenceData
    • <xarray.Dataset>
      Dimensions:  (chain: 2, draw: 500, school: 8)
      Coordinates:
        * chain    (chain) int64 0 2
        * draw     (draw) int64 0 1 2 3 4 5 6 7 8 ... 492 493 494 495 496 497 498 499
        * school   (school) object 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
      Data variables:
          mu       (chain, draw) float64 -3.477 -2.456 -2.826 ... -1.571 -4.435 9.763
          theta    (chain, draw, school) float64 1.669 -8.537 -2.623 ... 12.01 16.67
          tau      (chain, draw) float64 3.73 2.075 3.703 4.146 ... 2.812 12.18 4.453
          log_tau  (chain, draw) float64 1.316 0.7301 1.309 1.422 ... 1.034 2.5 1.494
      Attributes: (3)

    • <xarray.Dataset>
      Dimensions:  (chain: 2, draw: 500, school: 8)
      Coordinates:
        * chain    (chain) int64 0 2
        * draw     (draw) int64 0 1 2 3 4 5 6 7 8 ... 492 493 494 495 496 497 498 499
        * school   (school) object 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
      Data variables:
          obs      (chain, draw, school) float64 7.85 -19.03 -22.5 ... 9.892 17.29
      Attributes: (3)

    • <xarray.Dataset>
      Dimensions:           (chain: 2, draw: 500, school: 8)
      Coordinates:
        * chain             (chain) int64 0 2
        * draw              (draw) int64 0 1 2 3 4 5 6 ... 493 494 495 496 497 498 499
        * school            (school) object 'Choate' 'Deerfield' ... 'Mt. Hermon'
      Data variables:
          tune              (chain, draw) bool True False False ... False False False
          depth             (chain, draw) int64 5 3 3 4 5 5 4 4 5 ... 4 4 4 5 4 4 4 5
          tree_size         (chain, draw) float64 31.0 7.0 7.0 15.0 ... 15.0 15.0 31.0
          lp                (chain, draw) float64 -59.05 -56.19 ... -63.1 -61.91
          energy_error      (chain, draw) float64 0.07387 -0.1841 ... 1.118 -0.5052
          step_size_bar     (chain, draw) float64 0.2417 0.2417 ... 0.2501 0.2501
          max_energy_error  (chain, draw) float64 0.131 -0.2067 ... 4.38 -0.5052
          energy            (chain, draw) float64 60.76 62.76 64.4 ... 68.89 67.32
          mean_tree_accept  (chain, draw) float64 0.9506 0.9906 ... 0.1054 0.9791
          step_size         (chain, draw) float64 0.1275 0.1275 ... 0.2075 0.2075
          diverging         (chain, draw) bool False False False ... False False False
          log_likelihood    (chain, draw, school) float64 -5.168 -4.589 ... -3.843
      Attributes: (3)

    • <xarray.Dataset>
      Dimensions:    (chain: 1, draw: 500, school: 8)
      Coordinates:
        * chain      (chain) int64 0
        * draw       (draw) int64 0 1 2 3 4 5 6 7 ... 492 493 494 495 496 497 498 499
        * school     (school) object 'Choate' 'Deerfield' ... 'Mt. Hermon'
      Data variables:
          tau        (chain, draw) float64 6.561 1.016 68.91 ... 1.56 5.949 0.7631
          tau_log__  (chain, draw) float64 1.881 0.01593 4.233 ... 1.783 -0.2704
          mu         (chain, draw) float64 5.293 0.8137 0.7122 ... -1.658 -3.273
          theta      (chain, draw, school) float64 2.357 7.371 7.251 ... -3.775 -3.555
          obs        (chain, draw, school) float64 -3.54 6.769 19.68 ... -21.16 -6.071
      Attributes: (3)

    • <xarray.Dataset>
      Dimensions:  (school: 8)
      Coordinates:
        * school   (school) object 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
      Data variables:
          obs      (school) float64 28.0 8.0 -3.0 7.0 -1.0 1.0 18.0 12.0
      Attributes: (3)

Remove the first n draws (burn-in)#

Let’s say we want to remove the first 100 samples, from all the chains and all InferenceData groups with draws.

idata.sel(draw=slice(100, None))
arviz.InferenceData
    • <xarray.Dataset>
      Dimensions:  (chain: 4, draw: 400, school: 8)
      Coordinates:
        * chain    (chain) int64 0 1 2 3
        * draw     (draw) int64 100 101 102 103 104 105 ... 494 495 496 497 498 499
        * school   (school) object 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
      Data variables:
          mu       (chain, draw) float64 4.271 4.517 0.3265 ... 4.597 5.899 0.1614
          theta    (chain, draw, school) float64 32.74 1.796 2.199 ... 10.59 4.523
          tau      (chain, draw) float64 11.98 9.164 11.72 6.183 ... 8.346 7.711 5.407
          log_tau  (chain, draw) float64 2.483 2.215 2.462 1.822 ... 2.122 2.043 1.688
      Attributes: (3)

    • <xarray.Dataset>
      Dimensions:  (chain: 4, draw: 400, school: 8)
      Coordinates:
        * chain    (chain) int64 0 1 2 3
        * draw     (draw) int64 100 101 102 103 104 105 ... 494 495 496 497 498 499
        * school   (school) object 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
      Data variables:
          obs      (chain, draw, school) float64 24.5 11.84 28.08 ... 4.698 -15.07
      Attributes: (3)

    • <xarray.Dataset>
      Dimensions:           (chain: 4, draw: 400, school: 8)
      Coordinates:
        * chain             (chain) int64 0 1 2 3
        * draw              (draw) int64 100 101 102 103 104 ... 495 496 497 498 499
        * school            (school) object 'Choate' 'Deerfield' ... 'Mt. Hermon'
      Data variables:
          tune              (chain, draw) bool False False False ... False False False
          depth             (chain, draw) int64 5 5 5 5 5 5 4 4 4 ... 4 4 4 5 5 5 5 5
          tree_size         (chain, draw) float64 31.0 31.0 31.0 ... 31.0 31.0 31.0
          lp                (chain, draw) float64 -67.62 -66.08 ... -63.62 -58.35
          energy_error      (chain, draw) float64 0.003801 -0.0119 ... -0.003652
          step_size_bar     (chain, draw) float64 0.2417 0.2417 ... 0.1502 0.1502
          max_energy_error  (chain, draw) float64 -0.03831 -0.02486 ... -0.101 -0.1757
          energy            (chain, draw) float64 72.68 74.16 73.41 ... 67.77 67.21
          mean_tree_accept  (chain, draw) float64 0.9998 1.0 0.8716 ... 0.9875 0.9967
          step_size         (chain, draw) float64 0.1275 0.1275 ... 0.1064 0.1064
          diverging         (chain, draw) bool False False False ... False False False
          log_likelihood    (chain, draw, school) float64 -3.677 -3.414 ... -3.896
      Attributes: (3)

    • <xarray.Dataset>
      Dimensions:    (chain: 1, draw: 400, school: 8)
      Coordinates:
        * chain      (chain) int64 0
        * draw       (draw) int64 100 101 102 103 104 105 ... 494 495 496 497 498 499
        * school     (school) object 'Choate' 'Deerfield' ... 'Mt. Hermon'
      Data variables:
          tau        (chain, draw) float64 1.588 0.4472 1.197 ... 1.56 5.949 0.7631
          tau_log__  (chain, draw) float64 0.4625 -0.8048 0.1801 ... 1.783 -0.2704
          mu         (chain, draw) float64 -1.087 -8.631 -0.7139 ... -1.658 -3.273
          theta      (chain, draw, school) float64 1.556 1.323 2.802 ... -3.775 -3.555
          obs        (chain, draw, school) float64 18.6 12.49 7.67 ... -21.16 -6.071
      Attributes: (3)

    • <xarray.Dataset>
      Dimensions:  (school: 8)
      Coordinates:
        * school   (school) object 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
      Data variables:
          obs      (school) float64 28.0 8.0 -3.0 7.0 -1.0 1.0 18.0 12.0
      Attributes: (3)

If you check the burnin object you will see that the groups posterior, posterior_predictive, prior and sample_stats have 400 draws compared to idata that has 500. The group observed_data has not been affected because it does not have the draw dimension. Alternatively, you can specify which group or groups you want to change.

idata.sel(draw=slice(100, None), groups="posterior")
arviz.InferenceData
    • <xarray.Dataset>
      Dimensions:  (chain: 4, draw: 400, school: 8)
      Coordinates:
        * chain    (chain) int64 0 1 2 3
        * draw     (draw) int64 100 101 102 103 104 105 ... 494 495 496 497 498 499
        * school   (school) object 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
      Data variables:
          mu       (chain, draw) float64 4.271 4.517 0.3265 ... 4.597 5.899 0.1614
          theta    (chain, draw, school) float64 32.74 1.796 2.199 ... 10.59 4.523
          tau      (chain, draw) float64 11.98 9.164 11.72 6.183 ... 8.346 7.711 5.407
          log_tau  (chain, draw) float64 2.483 2.215 2.462 1.822 ... 2.122 2.043 1.688
      Attributes: (3)

    • <xarray.Dataset>
      Dimensions:  (chain: 4, draw: 500, school: 8)
      Coordinates:
        * chain    (chain) int64 0 1 2 3
        * draw     (draw) int64 0 1 2 3 4 5 6 7 8 ... 492 493 494 495 496 497 498 499
        * school   (school) object 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
      Data variables:
          obs      (chain, draw, school) float64 7.85 -19.03 -22.5 ... 4.698 -15.07
      Attributes: (3)

    • <xarray.Dataset>
      Dimensions:           (chain: 4, draw: 500, school: 8)
      Coordinates:
        * chain             (chain) int64 0 1 2 3
        * draw              (draw) int64 0 1 2 3 4 5 6 ... 493 494 495 496 497 498 499
        * school            (school) object 'Choate' 'Deerfield' ... 'Mt. Hermon'
      Data variables:
          tune              (chain, draw) bool True False False ... False False False
          depth             (chain, draw) int64 5 3 3 4 5 5 4 4 5 ... 4 4 4 5 5 5 5 5
          tree_size         (chain, draw) float64 31.0 7.0 7.0 15.0 ... 31.0 31.0 31.0
          lp                (chain, draw) float64 -59.05 -56.19 ... -63.62 -58.35
          energy_error      (chain, draw) float64 0.07387 -0.1841 ... -0.087 -0.003652
          step_size_bar     (chain, draw) float64 0.2417 0.2417 ... 0.1502 0.1502
          max_energy_error  (chain, draw) float64 0.131 -0.2067 ... -0.101 -0.1757
          energy            (chain, draw) float64 60.76 62.76 64.4 ... 67.77 67.21
          mean_tree_accept  (chain, draw) float64 0.9506 0.9906 ... 0.9875 0.9967
          step_size         (chain, draw) float64 0.1275 0.1275 ... 0.1064 0.1064
          diverging         (chain, draw) bool False False False ... False False False
          log_likelihood    (chain, draw, school) float64 -5.168 -4.589 ... -3.896
      Attributes: (3)

    • <xarray.Dataset>
      Dimensions:    (chain: 1, draw: 500, school: 8)
      Coordinates:
        * chain      (chain) int64 0
        * draw       (draw) int64 0 1 2 3 4 5 6 7 ... 492 493 494 495 496 497 498 499
        * school     (school) object 'Choate' 'Deerfield' ... 'Mt. Hermon'
      Data variables:
          tau        (chain, draw) float64 6.561 1.016 68.91 ... 1.56 5.949 0.7631
          tau_log__  (chain, draw) float64 1.881 0.01593 4.233 ... 1.783 -0.2704
          mu         (chain, draw) float64 5.293 0.8137 0.7122 ... -1.658 -3.273
          theta      (chain, draw, school) float64 2.357 7.371 7.251 ... -3.775 -3.555
          obs        (chain, draw, school) float64 -3.54 6.769 19.68 ... -21.16 -6.071
      Attributes: (3)

    • <xarray.Dataset>
      Dimensions:  (school: 8)
      Coordinates:
        * school   (school) object 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
      Data variables:
          obs      (school) float64 28.0 8.0 -3.0 7.0 -1.0 1.0 18.0 12.0
      Attributes: (3)

Compute posterior mean values along draw and chain dimensions#

To compute the mean value of the posterior samples, do the following:

post.mean()
<xarray.Dataset>
Dimensions:  ()
Data variables:
    mu       float64 4.093
    theta    float64 4.56
    tau      float64 4.089
    log_tau  float64 1.15

This computes the mean along all dimensions. This is probably what you want for mu and tau, which have two dimensions (chain and draw), but maybe not what you expected for theta, which has one more dimension school.

You can specify along which dimension you want to compute the mean (or other functions).

post.mean(dim=['chain', 'draw'])
<xarray.Dataset>
Dimensions:  (school: 8)
Coordinates:
  * school   (school) object 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
Data variables:
    mu       float64 4.093
    theta    (school) float64 6.026 4.724 3.576 4.478 3.064 3.821 6.25 4.544
    tau      float64 4.089
    log_tau  float64 1.15

Compute and store posterior pushforward quantities#

We use “posterior pushfoward quantities” to refer to quantities that are not variables in the posterior but deterministic computations using posterior variables.

You can use xarray for these pushforward operations and store them as a new variable in the posterior group. You’ll then be able to plot them with ArviZ functions, calculate stats and diagnostics on them (like the mcse()) or save and share the inferencedata object with the pushforward quantities included.

Compute the rolling mean of \(\log(\tau)\) with xarray.DataArray.rolling(), storing the result in the posterior

post["mlogtau"] = post["log_tau"].rolling({'draw': 50}).mean()

Using xarray for pusforward calculations has all the advantages of working with xarray. It also inherits the disadvantages of working with xarray, but we believe those to be outweighed by the advantages, and we have already shown how to extract the data as NumPy arrays. Working with InferenceData is working mainly with xarray objects and this is what is shown in this guide.

Some examples of these advantages are specifying operations with named dimensions instead of positional ones (as seen in some previous sections), automatic alignment and broadcasting of arrays (as we’ll see now), or integration with Dask (as shown in the Dask for ArviZ guide).

In this cell you will compute pairwise differences between schools on their mean effects (variable theta). To do so, substract the variable theta after renaming the school dimension to the original variable. Xarray then aligns and broadcasts the two variables because they have different dimensions, and the result is a 4d variable with all the pointwise differences.

Eventually, store the result in the theta_school_diff variable:

post['theta_school_diff'] = post.theta - post.theta.rename(school="school_bis")

The theta_shool_diff variable in the posterior has kept the named dimensions and coordinates:

post
<xarray.Dataset>
Dimensions:            (chain: 4, draw: 500, school: 8, school_bis: 8)
Coordinates:
  * chain              (chain) int64 0 1 2 3
  * draw               (draw) int64 0 1 2 3 4 5 6 ... 494 495 496 497 498 499
  * school             (school) object 'Choate' 'Deerfield' ... 'Mt. Hermon'
  * school_bis         (school_bis) object 'Choate' 'Deerfield' ... 'Mt. Hermon'
Data variables:
    mu                 (chain, draw) float64 -3.477 -2.456 ... 5.899 0.1614
    theta              (chain, draw, school) float64 1.669 -8.537 ... 4.523
    tau                (chain, draw) float64 3.73 2.075 3.703 ... 7.711 5.407
    log_tau            (chain, draw) float64 1.316 0.7301 1.309 ... 2.043 1.688
    mlogtau            (chain, draw) float64 nan nan nan ... 0.9753 1.004 1.034
    theta_school_diff  (chain, draw, school, school_bis) float64 0.0 ... 0.0
Attributes: (3)

Advanced subsetting#

To select the value corresponding to the difference between the Choate and Deerfield schools do:

post['theta_school_diff'].sel(school="Choate", school_bis="Deerfield")
<xarray.DataArray 'theta_school_diff' (chain: 4, draw: 500)>
10.21 -7.311 5.116 2.606 -1.116 24.96 ... 3.128 -4.62 4.288 2.424 2.613 -0.1137
Coordinates:
  * chain       (chain) int64 0 1 2 3
  * draw        (draw) int64 0 1 2 3 4 5 6 7 ... 492 493 494 495 496 497 498 499
    school      <U6 'Choate'
    school_bis  <U9 'Deerfield'

For more advanced subsetting (the equivalent to what is sometimes called “fancy indexing” in NumPy) you need to provide the indices as DataArray objects:

school_idx = xr.DataArray(["Choate", "Hotchkiss", "Mt. Hermon"], dims=["pairwise_school_diff"])
school_bis_idx = xr.DataArray(["Deerfield", "Choate", "Lawrenceville"], dims=["pairwise_school_diff"])
post['theta_school_diff'].sel(school=school_idx, school_bis=school_bis_idx)
<xarray.DataArray 'theta_school_diff' (chain: 4, draw: 500,
                                       pairwise_school_diff: 3)>
10.21 -5.673 2.356 -7.311 2.817 -1.51 ... 2.613 8.154 8.915 -0.1137 2.805 5.63
Coordinates:
  * chain       (chain) int64 0 1 2 3
  * draw        (draw) int64 0 1 2 3 4 5 6 7 ... 492 493 494 495 496 497 498 499
    school      (pairwise_school_diff) object 'Choate' 'Hotchkiss' 'Mt. Hermon'
    school_bis  (pairwise_school_diff) object 'Deerfield' ... 'Lawrenceville'
Dimensions without coordinates: pairwise_school_diff

Using lists or NumPy arrays instead of DataArrays does colum/row based indexing. As you can see, the result has 9 values of theta_shool_diff instead of the 3 pairs of difference we selected in the previous cell:

post['theta_school_diff'].sel(
    school=["Choate", "Hotchkiss", "Mt. Hermon"], 
    school_bis=["Deerfield", "Choate", "Lawrenceville"]
)
<xarray.DataArray 'theta_school_diff' (chain: 4, draw: 500, school: 3,
                                       school_bis: 3)>
10.21 0.0 10.84 4.533 -5.673 5.169 1.719 ... 2.691 2.805 3.861 4.46 4.574 5.63
Coordinates:
  * chain       (chain) int64 0 1 2 3
  * draw        (draw) int64 0 1 2 3 4 5 6 7 ... 492 493 494 495 496 497 498 499
  * school      (school) object 'Choate' 'Hotchkiss' 'Mt. Hermon'
  * school_bis  (school_bis) object 'Deerfield' 'Choate' 'Lawrenceville'

Add new chains using concat#

After checking the mcse() and realizing you need more samples, you rerun the model with two chains and obtain an idata_rerun object.

idata_rerun = idata.sel(chain=[0, 1]).copy().assign_coords(coords={"chain":[4,5]},groups="posterior_groups")

You can combine the two into a single InferenceData object using arviz.concat():

idata_complete = az.concat(idata, idata_rerun, dim="chain")
idata_complete.posterior.dims["chain"]
6

Add groups to InferenceData objects#

You can also add new groups to InferenceData objects with the extend() (if the new groups are already in an InferenceData object) or with add_groups() (if the new groups are dictionaries or xarray.Dataset objects).

rng = np.random.default_rng(3)
idata.add_groups(
    {"predictions": {"obs": rng.normal(size=(4, 500, 2))}}, 
    dims={"obs": ["new_school"]}, 
    coords={"new_school": ["Essex College", "Moordale"]}
)
idata
arviz.InferenceData
    • <xarray.Dataset>
      Dimensions:            (chain: 4, draw: 500, school: 8, school_bis: 8)
      Coordinates:
        * chain              (chain) int64 0 1 2 3
        * draw               (draw) int64 0 1 2 3 4 5 6 ... 494 495 496 497 498 499
        * school             (school) object 'Choate' 'Deerfield' ... 'Mt. Hermon'
        * school_bis         (school_bis) object 'Choate' 'Deerfield' ... 'Mt. Hermon'
      Data variables:
          mu                 (chain, draw) float64 -3.477 -2.456 ... 5.899 0.1614
          theta              (chain, draw, school) float64 1.669 -8.537 ... 4.523
          tau                (chain, draw) float64 3.73 2.075 3.703 ... 7.711 5.407
          log_tau            (chain, draw) float64 1.316 0.7301 1.309 ... 2.043 1.688
          mlogtau            (chain, draw) float64 nan nan nan ... 0.9753 1.004 1.034
          theta_school_diff  (chain, draw, school, school_bis) float64 0.0 ... 0.0
      Attributes: (3)

    • <xarray.Dataset>
      Dimensions:  (chain: 4, draw: 500, school: 8)
      Coordinates:
        * chain    (chain) int64 0 1 2 3
        * draw     (draw) int64 0 1 2 3 4 5 6 7 8 ... 492 493 494 495 496 497 498 499
        * school   (school) object 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
      Data variables:
          obs      (chain, draw, school) float64 7.85 -19.03 -22.5 ... 4.698 -15.07
      Attributes: (3)

    • <xarray.Dataset>
      Dimensions:     (chain: 4, draw: 500, new_school: 2)
      Coordinates:
        * chain       (chain) int64 0 1 2 3
        * draw        (draw) int64 0 1 2 3 4 5 6 7 ... 492 493 494 495 496 497 498 499
        * new_school  (new_school) <U13 'Essex College' 'Moordale'
      Data variables:
          obs         (chain, draw, new_school) float64 2.041 -2.556 ... -0.2822
      Attributes: (2)

    • <xarray.Dataset>
      Dimensions:           (chain: 4, draw: 500, school: 8)
      Coordinates:
        * chain             (chain) int64 0 1 2 3
        * draw              (draw) int64 0 1 2 3 4 5 6 ... 493 494 495 496 497 498 499
        * school            (school) object 'Choate' 'Deerfield' ... 'Mt. Hermon'
      Data variables:
          tune              (chain, draw) bool True False False ... False False False
          depth             (chain, draw) int64 5 3 3 4 5 5 4 4 5 ... 4 4 4 5 5 5 5 5
          tree_size         (chain, draw) float64 31.0 7.0 7.0 15.0 ... 31.0 31.0 31.0
          lp                (chain, draw) float64 -59.05 -56.19 ... -63.62 -58.35
          energy_error      (chain, draw) float64 0.07387 -0.1841 ... -0.087 -0.003652
          step_size_bar     (chain, draw) float64 0.2417 0.2417 ... 0.1502 0.1502
          max_energy_error  (chain, draw) float64 0.131 -0.2067 ... -0.101 -0.1757
          energy            (chain, draw) float64 60.76 62.76 64.4 ... 67.77 67.21
          mean_tree_accept  (chain, draw) float64 0.9506 0.9906 ... 0.9875 0.9967
          step_size         (chain, draw) float64 0.1275 0.1275 ... 0.1064 0.1064
          diverging         (chain, draw) bool False False False ... False False False
          log_likelihood    (chain, draw, school) float64 -5.168 -4.589 ... -3.896
      Attributes: (3)

    • <xarray.Dataset>
      Dimensions:    (chain: 1, draw: 500, school: 8)
      Coordinates:
        * chain      (chain) int64 0
        * draw       (draw) int64 0 1 2 3 4 5 6 7 ... 492 493 494 495 496 497 498 499
        * school     (school) object 'Choate' 'Deerfield' ... 'Mt. Hermon'
      Data variables:
          tau        (chain, draw) float64 6.561 1.016 68.91 ... 1.56 5.949 0.7631
          tau_log__  (chain, draw) float64 1.881 0.01593 4.233 ... 1.783 -0.2704
          mu         (chain, draw) float64 5.293 0.8137 0.7122 ... -1.658 -3.273
          theta      (chain, draw, school) float64 2.357 7.371 7.251 ... -3.775 -3.555
          obs        (chain, draw, school) float64 -3.54 6.769 19.68 ... -21.16 -6.071
      Attributes: (3)

    • <xarray.Dataset>
      Dimensions:  (school: 8)
      Coordinates:
        * school   (school) object 'Choate' 'Deerfield' ... "St. Paul's" 'Mt. Hermon'
      Data variables:
          obs      (school) float64 28.0 8.0 -3.0 7.0 -1.0 1.0 18.0 12.0
      Attributes: (3)