-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathunpooled_model.py
62 lines (51 loc) · 1.48 KB
/
unpooled_model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# -*- coding: utf-8 -*-
"""Module to make models available to notebooks after the ones in which they
are introduced
This module implements Python code from 05-unpooled_model.ipynb in order to
enable model use in later notebooks.
"""
import numpy as np
import pandas as pd
import pystan
import clean_data
# Unpooled model, from 05-unpooled_model.ipynb
unpooled_data = """
data {
int<lower=0> N;
int<lower=1, upper=85> county[N];
vector[N] x;
vector[N] y;
}
"""
unpooled_parameters = """
parameters {
vector[85] a;
real beta;
real<lower=0, upper=100> sigma;
}
"""
unpooled_transformed_parameters = """
transformed parameters {
vector[N] y_hat;
for (i in 1:N)
y_hat[i] = beta * x[i] + a[county[i]];
}
"""
unpooled_model = """
model {
y ~ normal(y_hat, sigma);
}
"""
unpooled_data_dict = {'N': len(clean_data.log_radon),
'county': clean_data.county + 1,
'x': clean_data.floor_measure,
'y': clean_data.log_radon}
unpooled_fit = pystan.stan(model_code=unpooled_data + unpooled_parameters +
unpooled_transformed_parameters + unpooled_model,
data=unpooled_data_dict,
iter=1000,
chains=2)
unpooled_estimates = pd.Series(unpooled_fit['a'].mean(0),
index=clean_data.mn_counties)
unpooled_se = pd.Series(unpooled_fit['a'].std(0),
index=clean_data.mn_counties)