forked from pymc-devs/pymc-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdisaster_model.py
155 lines (141 loc) · 2.33 KB
/
disaster_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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
"""
A model for the disasters data with a changepoint
changepoint ~ U(1851, 1962)
early_mean ~ Exp(1.)
late_mean ~ Exp(1.)
disasters[t] ~ Poi(early_mean if t <= switchpoint, late_mean otherwise)
"""
import arviz as az
import theano.tensor as tt
from numpy import arange, array
import pymc3 as pm
__all__ = ["disasters_data", "switchpoint", "early_mean", "late_mean", "rate", "disasters"]
# Time series of recorded coal mining disasters in the UK from 1851 to 1962
disasters_data = array(
[
4,
5,
4,
0,
1,
4,
3,
4,
0,
6,
3,
3,
4,
0,
2,
6,
3,
3,
5,
4,
5,
3,
1,
4,
4,
1,
5,
5,
3,
4,
2,
5,
2,
2,
3,
4,
2,
1,
3,
2,
2,
1,
1,
1,
1,
3,
0,
0,
1,
0,
1,
1,
0,
0,
3,
1,
0,
3,
2,
2,
0,
1,
1,
1,
0,
1,
0,
1,
0,
0,
0,
2,
1,
0,
0,
0,
1,
1,
0,
2,
3,
3,
1,
1,
2,
1,
1,
1,
1,
2,
4,
2,
0,
0,
1,
4,
0,
0,
0,
1,
0,
0,
0,
0,
0,
1,
0,
0,
1,
0,
1,
]
)
year = arange(1851, 1962)
with pm.Model() as model:
switchpoint = pm.DiscreteUniform("switchpoint", lower=year.min(), upper=year.max())
early_mean = pm.Exponential("early_mean", lam=1.0)
late_mean = pm.Exponential("late_mean", lam=1.0)
# Allocate appropriate Poisson rates to years before and after current
# switchpoint location
rate = tt.switch(switchpoint >= year, early_mean, late_mean)
disasters = pm.Poisson("disasters", rate, observed=disasters_data)
# Initial values for stochastic nodes
start = {"early_mean": 2.0, "late_mean": 3.0}
tr = pm.sample(1000, tune=500, start=start)
pm.plot_trace(tr)