# GLM: Hierarchical Linear Regression¶

- 2016 by Danne Elbers, Thomas Wiecki

This tutorial is adapted from a blog post by Danne Elbers and Thomas Wiecki called “The Best Of Both Worlds: Hierarchical Linear Regression in PyMC3”.

Today’s blog post is co-written by Danne Elbers who is doing her masters thesis with me on computational psychiatry using Bayesian modeling. This post also borrows heavily from a Notebook by Chris Fonnesbeck.

The power of Bayesian modelling really clicked for me when I was first introduced to hierarchical modelling. In this blog post we will:

- provide and intuitive explanation of hierarchical/multi-level Bayesian modeling;
- show how this type of model can easily be built and estimated in PyMC3;
- demonstrate the advantage of using hierarchical Bayesian modelling as opposed to non-hierarchical Bayesian modelling by comparing the two;
- visualize the “shrinkage effect” (explained below); and
- highlight connections to the frequentist version of this model.

Having multiple sets of related measurements comes up all the time. In mathematical psychology, for example, you test multiple subjects on the same task. We then want to estimate a computational/mathematical model that describes the behavior on the task by a set of parameters. We could thus fit a model to each subject individually, assuming they share no similarities; or, pool all the data and estimate one model assuming all subjects are identical. Hierarchical modeling allows the best of both worlds by modeling subjects’ similarities but also allowing estimiation of individual parameters. As an aside, software from our lab, HDDM, allows hierarchical Bayesian estimation of a widely used decision making model in psychology. In this blog post, however, we will use a more classical example of hierarchical linear regression to predict radon levels in houses.

This is the 3rd blog post on the topic of Bayesian modeling in PyMC3, see here for the previous two:

- The Inference Button: Bayesian GLMs made easy with PyMC3
- This world is far from Normal(ly distributed): Bayesian Robust Regression in PyMC3

## The data set¶

Gelman et al.’s (2007) radon dataset is a classic for hierarchical modeling. In this dataset the amount of the radioactive gas radon has been measured among different households in all counties of several states. Radon gas is known to be the highest cause of lung cancer in non-smokers. It is believed to be more strongly present in households containing a basement and to differ in amount present among types of soil. Here we’ll investigate this differences and try to make predictions of radonlevels in different counties based on the county itself and the presence of a basement. In this example we’ll look at Minnesota, a state that contains 85 counties in which different measurements are taken, ranging from 2 to 116 measurements per county.

First, we’ll load the data:

```
In [1]:
```

```
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pymc3 as pm
import pandas as pd
import theano
data = pd.read_csv('../data/radon.csv')
data['log_radon'] = data['log_radon'].astype(theano.config.floatX)
county_names = data.county.unique()
county_idx = data.county_code.values
n_counties = len(data.county.unique())
```

The relevant part of the data we will model looks as follows:

```
In [6]:
```

```
data[['county', 'log_radon', 'floor']].head()
```

```
Out[6]:
```

county | log_radon | floor | |
---|---|---|---|

0 | AITKIN | 0.832909 | 1.0 |

1 | AITKIN | 0.832909 | 0.0 |

2 | AITKIN | 1.098612 | 0.0 |

3 | AITKIN | 0.095310 | 0.0 |

4 | ANOKA | 1.163151 | 0.0 |

As you can see, we have multiple `radon`

measurements (log-converted
to be on the real line) – one row for each house – in a `county`

and
whether the house has a basement (`floor`

== 0) or not (`floor`

==
1). We are interested in whether having a basement increases the
`radon`

measured in the house.

## The Models¶

### Pooling of measurements¶

Now you might say: “That’s easy! I’ll just pool all my data and estimate one big regression to asses the influence of a basement across all counties”. In math-speak that model would be:

Where \(i\) represents the measurement, \(c\) the county and
floor contains a 0 or 1 if the house has a basement or not,
respectively. If you need a refresher on Linear Regressions in `PyMC`

,
check out my previous blog
post.
Critically, we are only estimating *one* intercept and *one* slope for
all measurements over all counties pooled together as illustrated in the
graphic below (\(\theta\) represents \((\alpha, \beta)\) in our
case and \(y_i\) are the measurements of the \(i\)th county).

### Unpooled measurements: separate regressions¶

But what if we are interested in whether different counties actually have different relationships (slope) and different base-rates of radon (intercept)? Then you might say “OK then, I’ll just estimate \(n\) (number of counties) different regressions – one for each county”. In math-speak that model would be:

Note that we added the subindex \(c\) so we are estimating \(n\) different \(\alpha\)s and \(\beta\)s – one for each county.

This is the extreme opposite model; where above we assumed all counties are exactly the same, here we are saying that they share no similarities whatsoever. As we show below, this type of model can be very noisy when we have little data per county, as is the case in this data set.

### Partial pooling: Hierarchical Regression aka, the best of both worlds¶

Fortunately, there is a middle ground to both of these extremes. Specifically, we may assume that while \(\alpha\)s and \(\beta\)s are different for each county as in the unpooled case, the coefficients all share similarity. We can model this by assuming that each individual coefficient comes from a common group distribution:

We thus assume the intercepts \(\alpha\) and slopes \(\beta\) to come from a normal distribution centered around their respective group mean \(\mu\) with a certain standard deviation \(\sigma^2\), the values (or rather posteriors) of which we also estimate. That’s why this is called a multilevel, hierarchical or partial-pooling modeling.

How do we estimate such a complex model you might ask? Well, that’s the beauty of Probabilistic Programming – we just formulate the model we want and press our Inference Button(TM).

(Note that the above is not a complete Bayesian model specification as we haven’t defined priors or hyperpriors (i.e. priors for the group distribution, \(\mu\) and \(\sigma\)). These will be used in the model implementation below but only distract here.)

## Probabilistic Programming¶

### Unpooled/non-hierarchical model¶

To highlight the effect of the hierarchical linear regression we’ll first estimate the non-hierarchical, unpooled Bayesian model from above (separate regressions). For each county we estimate a completely separate mean (intercept). As we have no prior information on what the intercept or regressions could be, we will be using a normal distribution centered around 0 with a wide standard-deviation to describe the intercept and regressions. We’ll assume the measurements are normally distributed with noise \(\epsilon\) on which we place a uniform distribution.

```
In [2]:
```

```
with pm.Model() as unpooled_model:
# Independent parameters for each county
a = pm.Normal('a', 0, sd=100, shape=n_counties)
b = pm.Normal('b', 0, sd=100, shape=n_counties)
# Model error
eps = pm.HalfCauchy('eps', 5)
# Model prediction of radon level
# a[county_idx] translates to a[0, 0, 0, 1, 1, ...],
# we thus link multiple household measures of a county
# to its coefficients.
radon_est = a[county_idx] + b[county_idx]*data.floor.values
# Data likelihood
y = pm.Normal('y', radon_est, sd=eps, observed=data.log_radon)
```

```
In [4]:
```

```
with unpooled_model:
unpooled_trace = pm.sample(5000)
```

```
Auto-assigning NUTS sampler...
Initializing NUTS using advi...
Average ELBO = -1,745.39: 100%|██████████| 500000/500000 [01:26<00:00, 5800.64it/s]
Finished [100%]: Average ELBO = -1,745.30
100%|██████████| 5000/5000 [00:20<00:00, 238.98it/s]
```

### Hierarchical Model¶

Instead of creating models separatley, the hierarchical model creates group parameters that consider the countys not as completely different but as having an underlying similarity. These distributions are subsequently used to influence the distribution of each county’s \(\alpha\) and \(\beta\).

```
In [2]:
```

```
with pm.Model() as hierarchical_model:
# Hyperpriors for group nodes
mu_a = pm.Normal('mu_a', mu=0., sd=100**2)
sigma_a = pm.HalfCauchy('sigma_a', 5)
mu_b = pm.Normal('mu_b', mu=0., sd=100**2)
sigma_b = pm.HalfCauchy('sigma_b', 5)
# Intercept for each county, distributed around group mean mu_a
# Above we just set mu and sd to a fixed value while here we
# plug in a common group distribution for all a and b (which are
# vectors of length n_counties).
a = pm.Normal('a', mu=mu_a, sd=sigma_a, shape=n_counties)
# Intercept for each county, distributed around group mean mu_a
b = pm.Normal('b', mu=mu_b, sd=sigma_b, shape=n_counties)
# Model error
eps = pm.HalfCauchy('eps', 5)
radon_est = a[county_idx] + b[county_idx] * data.floor.values
# Data likelihood
radon_like = pm.Normal('radon_like', mu=radon_est, sd=eps, observed=data.log_radon)
```

```
In [4]:
```

```
%pdb
```

```
Automatic pdb calling has been turned ON
```

```
In [10]:
```

```
# Inference button (TM)!
with hierarchical_model:
start, step = pm.init_nuts(n_advi=20000, n_nuts=2000)
```

```
Initializing NUTS...
0%| | 0/20000 [00:00<?, ?it/s]
3%|▎ | 543/20000 [00:00<00:03, 5421.25it/s]
5%|▌ | 1000/20000 [00:00<00:03, 5130.69it/s]
7%|▋ | 1438/20000 [00:00<00:03, 4877.42it/s]
10%|▉ | 1939/20000 [00:00<00:03, 4901.83it/s]
Average ELBO = -2,802.1: 12%|█▏ | 2415/20000 [00:00<00:03, 4857.76it/s]
Average ELBO = -2,802.1: 14%|█▍ | 2875/20000 [00:00<00:03, 4769.82it/s]
Average ELBO = -2,802.1: 17%|█▋ | 3414/20000 [00:00<00:03, 4938.47it/s]
Average ELBO = -2,802.1: 20%|█▉ | 3958/20000 [00:00<00:03, 5078.93it/s]
Average ELBO = -2,275.8: 23%|██▎ | 4520/20000 [00:00<00:02, 5228.12it/s]
Average ELBO = -2,275.8: 26%|██▌ | 5100/20000 [00:01<00:02, 5371.62it/s]
Average ELBO = -2,275.8: 28%|██▊ | 5626/20000 [00:01<00:02, 5301.94it/s]
Average ELBO = -1,921.1: 31%|███ | 6148/20000 [00:01<00:02, 4786.83it/s]
Average ELBO = -1,921.1: 33%|███▎ | 6635/20000 [00:01<00:02, 4810.05it/s]
Average ELBO = -1,921.1: 36%|███▌ | 7205/20000 [00:01<00:02, 5046.32it/s]
Average ELBO = -1,921.1: 39%|███▉ | 7779/20000 [00:01<00:02, 5219.64it/s]
Average ELBO = -1,617.3: 42%|████▏ | 8348/20000 [00:01<00:02, 5351.21it/s]
Average ELBO = -1,617.3: 45%|████▍ | 8916/20000 [00:01<00:02, 5445.16it/s]
Average ELBO = -1,617.3: 47%|████▋ | 9464/20000 [00:01<00:01, 5299.74it/s]
Average ELBO = -1,414.5: 50%|█████ | 10019/20000 [00:01<00:01, 5371.52it/s]
Average ELBO = -1,414.5: 53%|█████▎ | 10598/20000 [00:02<00:01, 5480.20it/s]
Average ELBO = -1,414.5: 56%|█████▌ | 11161/20000 [00:02<00:01, 5521.99it/s]
Average ELBO = -1,414.5: 59%|█████▊ | 11715/20000 [00:02<00:01, 5489.58it/s]
Average ELBO = -1,273.8: 61%|██████▏ | 12266/20000 [00:02<00:01, 5434.43it/s]
Average ELBO = -1,273.8: 64%|██████▍ | 12832/20000 [00:02<00:01, 5499.73it/s]
Average ELBO = -1,273.8: 67%|██████▋ | 13391/20000 [00:02<00:01, 5526.03it/s]
Average ELBO = -1,273.8: 70%|██████▉ | 13945/20000 [00:02<00:01, 5376.40it/s]
Average ELBO = -1,193.3: 72%|███████▏ | 14484/20000 [00:02<00:01, 4900.92it/s]
Average ELBO = -1,193.3: 75%|███████▍ | 14984/20000 [00:02<00:01, 3975.10it/s]
Average ELBO = -1,193.3: 77%|███████▋ | 15473/20000 [00:03<00:01, 4211.40it/s]
Average ELBO = -1,193.3: 80%|███████▉ | 15996/20000 [00:03<00:00, 4472.29it/s]
Average ELBO = -1,148.2: 82%|████████▏ | 16483/20000 [00:03<00:00, 4575.30it/s]
Average ELBO = -1,148.2: 85%|████████▌ | 17048/20000 [00:03<00:00, 4851.30it/s]
Average ELBO = -1,148.2: 88%|████████▊ | 17550/20000 [00:03<00:00, 4818.63it/s]
Average ELBO = -1,123.7: 91%|█████████ | 18135/20000 [00:03<00:00, 5085.61it/s]
Average ELBO = -1,123.7: 94%|█████████▎| 18703/20000 [00:03<00:00, 5246.94it/s]
Average ELBO = -1,123.7: 96%|█████████▌| 19238/20000 [00:03<00:00, 4620.63it/s]
Average ELBO = -1,123.7: 99%|█████████▊| 19721/20000 [00:04<00:00, 3742.92it/s]
Average ELBO = -1,123.7: 100%|██████████| 20000/20000 [00:04<00:00, 4877.19it/s]Finished [100%]: Average ELBO = -1,111.7
0%| | 0/2000 [00:00<?, ?it/s]
1%| | 12/2000 [00:00<00:16, 118.44it/s]
1%|▏ | 25/2000 [00:00<00:16, 117.32it/s]
2%|▏ | 39/2000 [00:00<00:16, 122.23it/s]
3%|▎ | 51/2000 [00:00<00:16, 120.93it/s]
3%|▎ | 61/2000 [00:00<00:19, 100.88it/s]
4%|▎ | 70/2000 [00:00<00:21, 87.88it/s]
4%|▍ | 82/2000 [00:00<00:20, 95.55it/s]
5%|▍ | 99/2000 [00:00<00:17, 109.75it/s]
6%|▌ | 116/2000 [00:00<00:15, 122.69it/s]
7%|▋ | 142/2000 [00:01<00:12, 145.29it/s]
8%|▊ | 162/2000 [00:01<00:11, 157.19it/s]
9%|▉ | 180/2000 [00:01<00:12, 144.60it/s]
10%|▉ | 197/2000 [00:01<00:11, 151.11it/s]
11%|█ | 214/2000 [00:01<00:12, 144.01it/s]
12%|█▏ | 230/2000 [00:01<00:12, 140.98it/s]
12%|█▏ | 245/2000 [00:01<00:13, 127.33it/s]
13%|█▎ | 259/2000 [00:01<00:13, 128.37it/s]
14%|█▍ | 280/2000 [00:02<00:11, 144.82it/s]
15%|█▌ | 300/2000 [00:02<00:10, 157.18it/s]
16%|█▌ | 319/2000 [00:02<00:10, 164.46it/s]
17%|█▋ | 342/2000 [00:02<00:09, 178.68it/s]
18%|█▊ | 362/2000 [00:02<00:08, 183.01it/s]
19%|█▉ | 381/2000 [00:02<00:09, 162.13it/s]
20%|█▉ | 399/2000 [00:02<00:12, 126.56it/s]
21%|██ | 417/2000 [00:02<00:11, 138.65it/s]
22%|██▏ | 439/2000 [00:03<00:10, 154.91it/s]
23%|██▎ | 457/2000 [00:03<00:09, 157.82it/s]
24%|██▍ | 475/2000 [00:03<00:10, 140.47it/s]
25%|██▍ | 491/2000 [00:03<00:10, 141.98it/s]
25%|██▌ | 507/2000 [00:03<00:11, 128.69it/s]
26%|██▌ | 521/2000 [00:03<00:11, 130.77it/s]
27%|██▋ | 535/2000 [00:03<00:12, 114.51it/s]
27%|██▋ | 549/2000 [00:03<00:12, 120.32it/s]
28%|██▊ | 570/2000 [00:04<00:10, 137.57it/s]
29%|██▉ | 586/2000 [00:04<00:10, 133.77it/s]
30%|███ | 601/2000 [00:04<00:10, 127.78it/s]
31%|███ | 615/2000 [00:04<00:11, 119.04it/s]
31%|███▏ | 628/2000 [00:04<00:12, 114.05it/s]
32%|███▏ | 647/2000 [00:04<00:10, 129.53it/s]
33%|███▎ | 667/2000 [00:04<00:09, 143.28it/s]
34%|███▍ | 683/2000 [00:04<00:09, 138.33it/s]
35%|███▍ | 698/2000 [00:04<00:09, 132.78it/s]
36%|███▋ | 725/2000 [00:05<00:08, 155.72it/s]
37%|███▋ | 746/2000 [00:05<00:07, 168.33it/s]
38%|███▊ | 767/2000 [00:05<00:06, 178.08it/s]
39%|███▉ | 787/2000 [00:05<00:06, 183.83it/s]
40%|████ | 807/2000 [00:05<00:07, 164.30it/s]
41%|████▏ | 829/2000 [00:05<00:06, 176.69it/s]
42%|████▏ | 848/2000 [00:05<00:07, 155.85it/s]
43%|████▎ | 865/2000 [00:05<00:07, 148.24it/s]
44%|████▍ | 881/2000 [00:06<00:07, 142.47it/s]
45%|████▍ | 896/2000 [00:06<00:08, 137.96it/s]
46%|████▌ | 911/2000 [00:06<00:08, 134.22it/s]
46%|████▋ | 925/2000 [00:06<00:09, 116.74it/s]
47%|████▋ | 940/2000 [00:06<00:08, 124.64it/s]
48%|████▊ | 962/2000 [00:06<00:07, 141.05it/s]
49%|████▉ | 978/2000 [00:06<00:08, 118.11it/s]
50%|████▉ | 992/2000 [00:06<00:08, 123.23it/s]
51%|█████ | 1013/2000 [00:07<00:07, 139.81it/s]
52%|█████▏ | 1037/2000 [00:07<00:06, 158.76it/s]
53%|█████▎ | 1057/2000 [00:07<00:05, 168.88it/s]
Exception in thread Thread-6:
Traceback (most recent call last):
File "/home/wiecki/miniconda3/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
File "/home/wiecki/miniconda3/lib/python3.5/site-packages/tqdm/_tqdm.py", line 102, in run
for instance in self.tqdm_cls._instances:
File "/home/wiecki/miniconda3/lib/python3.5/_weakrefset.py", line 60, in __iter__
for itemref in self.data:
RuntimeError: Set changed size during iteration
54%|█████▍ | 1078/2000 [00:07<00:05, 176.87it/s]
55%|█████▍ | 1097/2000 [00:07<00:05, 163.95it/s]
56%|█████▌ | 1115/2000 [00:07<00:05, 167.45it/s]
57%|█████▋ | 1135/2000 [00:07<00:04, 174.30it/s]
58%|█████▊ | 1155/2000 [00:07<00:04, 179.13it/s]
59%|█████▊ | 1174/2000 [00:07<00:04, 179.48it/s]
60%|█████▉ | 1193/2000 [00:08<00:04, 177.25it/s]
61%|██████ | 1211/2000 [00:08<00:04, 164.17it/s]
61%|██████▏ | 1228/2000 [00:08<00:04, 164.48it/s]
62%|██████▏ | 1246/2000 [00:08<00:04, 168.09it/s]
63%|██████▎ | 1265/2000 [00:08<00:04, 173.01it/s]
64%|██████▍ | 1287/2000 [00:08<00:03, 183.01it/s]
65%|██████▌ | 1306/2000 [00:08<00:04, 149.82it/s]
66%|██████▌ | 1323/2000 [00:08<00:04, 143.70it/s]
67%|██████▋ | 1346/2000 [00:08<00:04, 161.23it/s]
68%|██████▊ | 1367/2000 [00:09<00:03, 172.68it/s]
70%|██████▉ | 1390/2000 [00:09<00:03, 185.08it/s]
70%|███████ | 1410/2000 [00:09<00:03, 186.49it/s]
72%|███████▏ | 1433/2000 [00:09<00:02, 197.58it/s]
73%|███████▎ | 1455/2000 [00:09<00:02, 200.65it/s]
74%|███████▍ | 1476/2000 [00:09<00:02, 194.10it/s]
75%|███████▍ | 1496/2000 [00:09<00:02, 179.14it/s]
76%|███████▌ | 1515/2000 [00:09<00:02, 170.39it/s]
77%|███████▋ | 1539/2000 [00:09<00:02, 186.37it/s]
78%|███████▊ | 1564/2000 [00:10<00:02, 199.56it/s]
79%|███████▉ | 1589/2000 [00:10<00:01, 209.68it/s]
81%|████████ | 1611/2000 [00:10<00:01, 211.40it/s]
82%|████████▏ | 1633/2000 [00:10<00:01, 206.52it/s]
83%|████████▎ | 1655/2000 [00:10<00:01, 196.99it/s]
84%|████████▍ | 1676/2000 [00:10<00:01, 183.07it/s]
85%|████████▍ | 1696/2000 [00:10<00:01, 185.91it/s]
86%|████████▌ | 1718/2000 [00:10<00:01, 192.40it/s]
87%|████████▋ | 1738/2000 [00:10<00:01, 176.37it/s]
88%|████████▊ | 1762/2000 [00:11<00:01, 191.45it/s]
89%|████████▉ | 1784/2000 [00:11<00:01, 197.58it/s]
90%|█████████ | 1805/2000 [00:11<00:01, 182.52it/s]
91%|█████████ | 1824/2000 [00:11<00:01, 152.10it/s]
92%|█████████▏| 1844/2000 [00:11<00:00, 162.35it/s]
93%|█████████▎| 1862/2000 [00:11<00:00, 161.03it/s]
94%|█████████▍| 1883/2000 [00:11<00:00, 172.46it/s]
95%|█████████▌| 1902/2000 [00:11<00:00, 164.61it/s]
96%|█████████▌| 1920/2000 [00:12<00:00, 153.81it/s]
97%|█████████▋| 1938/2000 [00:12<00:00, 159.28it/s]
98%|█████████▊| 1956/2000 [00:12<00:00, 163.15it/s]
99%|█████████▉| 1976/2000 [00:12<00:00, 172.23it/s]
100%|█████████▉| 1996/2000 [00:12<00:00, 179.58it/s]
100%|██████████| 2000/2000 [00:12<00:00, 159.78it/s]
```

```
In [14]:
```

```
step
```

```
Out[14]:
```

```
<pymc3.step_methods.hmc.nuts.NUTS at 0x7f56932e0ba8>
```

```
In [4]:
```

```
%pdb
```

```
Automatic pdb calling has been turned ON
```

```
In [6]:
```

```
# Inference button (TM)!
with hierarchical_model:
hierarchical_trace = pm.sample(draws=5000, n_advi=50000, n_nuts=20000)
```

```
Auto-assigning NUTS sampler...
Initializing NUTS...
Average ELBO = -1,091.8: 100%|██████████| 50000/50000 [00:08<00:00, 6051.64it/s]
Finished [100%]: Average ELBO = -1,091.1
100%|██████████| 20000/20000 [01:28<00:00, 226.30it/s]
100%|██████████| 5000/5000 [01:23<00:00, 59.90it/s]
```

Plotting the hierarchical model trace -its found values- from 2000 iterations onwards (right side plot) and its accumulated marginal values (left side plot)

```
In [ ]:
```

```
Auto-assigning NUTS sampler...
Initializing NUTS using advi...
Average ELBO = -1,123.7: 100%|██████████| 20000/20000 [00:03<00:00, 6007.96it/s]
Finished [100%]: Average ELBO = -1,111.7
100%|██████████| 5000/5000 [00:36<00:00, 137.46it/s]
```

```
In [7]:
```

```
pm.traceplot(hierarchical_trace);
```

The marginal posteriors in the left column are highly informative.
`mu_a`

tells us the group mean (log) radon levels. `mu_b`

tells us
that having no basement decreases radon levels significantly (no mass
above zero). We can also see by looking at the marginals for `a`

that
there is quite some differences in radon levels between counties (each
‘rainbow’ color corresponds to a single county); the different widths
are related to how much confidence we have in each paramter estimate –
the more measurements per county, the higher our confidence will be.

## Posterior Predictive Check¶

### The Root Mean Square Deviation¶

To find out which of the models explains the data better we can calculate the Root Mean Square Deviaton (RMSD). This posterior predictive check revolves around recreating the data based on the parameters found at different moments in the chain. The recreated or predicted values are subsequently compared to the real data points, the model that predicts data points closer to the original data is considered the better one. Thus, the lower the RMSD the better.

When computing the RMSD (code not shown) we get the following result:

- individual/non-hierarchical model: 0.13
- hierarchical model: 0.08

As can be seen above the hierarchical model performs better than the non-hierarchical model in predicting the radon values. Following this, we’ll plot some examples of county’s showing the actual radon measurements, the hierarchial predictions and the non-hierarchical predictions.

```
In [8]:
```

```
selection = ['CASS', 'CROW WING', 'FREEBORN']
fig, axis = plt.subplots(1, 3, figsize=(12, 6), sharey=True, sharex=True)
axis = axis.ravel()
for i, c in enumerate(selection):
c_data = data.ix[data.county == c]
c_data = c_data.reset_index(drop = True)
c_index = np.where(county_names==c)[0][0]
z = list(c_data['county_code'])[0]
xvals = np.linspace(-0.2, 1.2)
for a_val, b_val in zip(unpooled_trace['a'][1000:, c_index], unpooled_trace['b'][1000:, c_index]):
axis[i].plot(xvals, a_val + b_val * xvals, 'b', alpha=.1)
axis[i].plot(xvals, unpooled_trace['a'][1000:, c_index].mean() + unpooled_trace['b'][1000:, c_index].mean() * xvals,
'b', alpha=1, lw=2., label='individual')
for a_val, b_val in zip(hierarchical_trace['a'][1000:][z], hierarchical_trace['b'][1000:][z]):
axis[i].plot(xvals, a_val + b_val * xvals, 'g', alpha=.1)
axis[i].plot(xvals, hierarchical_trace['a'][1000:][z].mean() + hierarchical_trace['b'][1000:][z].mean() * xvals,
'g', alpha=1, lw=2., label='hierarchical')
axis[i].scatter(c_data.floor + np.random.randn(len(c_data))*0.01, c_data.log_radon,
alpha=1, color='k', marker='.', s=80, label='original data')
axis[i].set_xticks([0,1])
axis[i].set_xticklabels(['basement', 'no basement'])
axis[i].set_ylim(-1, 4)
axis[i].set_title(c)
if not i%3:
axis[i].legend()
axis[i].set_ylabel('log radon level')
```

In the above plot we have the data points in black of three selected counties. The thick lines represent the mean estimate of the regression line of the individual (blue) and hierarchical model (in green). The thinner lines are regression lines of individual samples from the posterior and give us a sense of how variable the estimates are.

When looking at the county ‘CASS’ we see that the non-hierarchical estimation is strongly biased: as this county’s data contains only households with a basement the estimated regression produces the non-sensical result of a giant negative slope meaning that we would expect negative radon levels in a house without basement!

Moreover, in the example county’s ‘CROW WING’ and ‘FREEBORN’ the non-hierarchical model appears to react more strongly than the hierarchical model to the existance of outliers in the dataset (‘CROW WING’: no basement upper right. ‘FREEBORN’: basement upper left). Assuming that there should be a higher amount of radon gas measurable in households with basements opposed to those without, the county ‘CROW WING’’s non-hierachical model seems off. Having the group-distribution constrain the coefficients we get meaningful estimates in all cases as we apply what we learn from the group to the individuals and vice-versa.

## Shrinkage¶

Shrinkage describes the process by which our estimates are “pulled” towards the group-mean as a result of the common group distribution – county-coefficients very far away from the group mean have very low probability under the normality assumption, moving them closer to the group mean gives them higher probability. In the non-hierachical model every county is allowed to differ completely from the others by just using each county’s data, resulting in a model more prone to outliers (as shown above).

```
In [9]:
```

```
hier_a = hierarchical_trace['a'][500:].mean(axis=0)
hier_b = hierarchical_trace['b'][500:].mean(axis=0)
indv_a = [unpooled_trace['a'][500:, np.where(county_names==c)[0][0]].mean() for c in county_names]
indv_b = [unpooled_trace['b'][500:, np.where(county_names==c)[0][0]].mean() for c in county_names]
```

```
In [10]:
```

```
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, xlabel='Intercept', ylabel='Floor Measure',
title='Hierarchical vs. Non-hierarchical Bayes',
xlim=(0, 3), ylim=(-3, 3))
ax.scatter(indv_a, indv_b, s=26, alpha=0.4, label = 'non-hierarchical')
ax.scatter(hier_a,hier_b, c='red', s=26, alpha=0.4, label = 'hierarchical')
for i in range(len(indv_b)):
ax.arrow(indv_a[i], indv_b[i], hier_a[i] - indv_a[i], hier_b[i] - indv_b[i],
fc="k", ec="k", length_includes_head=True, alpha=0.4, head_width=.04)
ax.legend();
```

In the shrinkage plot above we show the coefficients of each county’s non-hierarchical posterior mean (blue) and the hierarchical posterior mean (red). To show the effect of shrinkage on a single coefficient-pair (alpha and beta) we connect the blue and red points belonging to the same county by an arrow. Some non-hierarchical posteriors are so far out that we couldn’t display them in this plot (it makes the axes too wide). Interestingly, all hierarchical posteriors of the floor-measure seem to be around -0.6 indicating that having a basement in almost all county’s is a clear indicator for heightened radon levels. The intercept (which we take for type of soil) appears to differ among countys. This information would have been difficult to find if we had only used the non-hierarchial model.

Critically, many effects that look quite large and significant in the
non-hiearchical model actually turn out to be much smaller when we take
the group distribution into account (this point can also well be seen in
plot `In[12]`

in Chris’
NB).
Shrinkage can thus be viewed as a form of smart regularization that
helps reduce false-positives!

### Connections to Frequentist statistics¶

This type of hierarchical, partial pooling model is known as a random effects model in frequentist terms. Interestingly, if we placed uniform priors on the group mean and variance in the above model, the resulting Bayesian model would be equivalent to a random effects model. One might imagine that the difference between a model with uniform or wide normal hyperpriors should not have a huge impact. However, Gelman says encourages use of weakly-informative priors (like we did above) over flat priors.

## Summary¶

In this post, co-authored by Danne Elbers, we showed how a multi-level hierarchical Bayesian model gives the best of both worlds when we have multiple sets of measurements we expect to have similarity. The naive approach either pools all data together and ignores the individual differences, or treats each set as completely separate leading to noisy estimates, as shown above. By assuming that each individual data set (each county in our case) is distributed according to a group distribution – which we simultaneously estimate – we benefit from increased statistical power and smart regularization via the shrinkage effect. Probabilistic Programming in PyMC3 then makes Bayesian estimation of this model trivial.

As a follow-up we could also include other states into our model. For
this we could add yet another layer to the hierarchy where each state is
pooled at the country level. Finally, readers of my blog will notice
that we didn’t use `glm()`

here as it does not play nice with
hierarchical models yet.

## References¶

- The underlying Notebook of this blog post
- Blog post: The Inference Button: Bayesian GLMs made easy with PyMC3
- Blog post: This world is far from Normal(ly distributed): Bayesian Robust Regression in PyMC3
- Chris Fonnesbeck repo containing a more extensive analysis
- Blog post: Shrinkage in multi-level hierarchical models by John Kruschke
- Gelman, A.; Carlin; Stern; and Rubin, D., 2007, “Replication data for: Bayesian Data Analysis, Second Edition”,
- Gelman, A., & Hill, J. (2006). Data Analysis Using Regression and Multilevel/Hierarchical Models (1st ed.). Cambridge University Press.
- Gelman, A. (2006). Multilevel (Hierarchical) modeling: what it can and cannot do. Technometrics, 48(3), 432–435.

### Acknowledgements¶

Thanks to Imri Sofer for feedback and teaching us about the connections to random-effects models and Dan Dillon for useful comments on an earlier draft.