Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132932 views
License: OTHER
1
import numpy as np
2
import pymc as pm
3
4
5
data = np.loadtxt("../../Chapter3_MCMC/data/mixture_data.csv", delimiter=",")
6
7
8
p = pm.Uniform("p", 0, 1)
9
10
assignment = pm.Categorical("assignment", [p, 1 - p], size=data.shape[0])
11
12
taus = 1.0 / pm.Uniform("stds", 0, 100, size=2) ** 2 # notice the size!
13
centers = pm.Normal("centers", [150, 150], [0.001, 0.001], size=2)
14
15
"""
16
The below deterministic functions map an assignment, in this case 0 or 1,
17
to a set of parameters, located in the (1, 2) arrays `taus` and `centers.`
18
"""
19
20
21
@pm.deterministic
22
def center_i(assignment=assignment, centers=centers):
23
return centers[assignment]
24
25
26
@pm.deterministic
27
def tau_i(assignment=assignment, taus=taus):
28
return taus[assignment]
29
30
# and to combine it with the observations:
31
observations = pm.Normal("obs", center_i, tau_i,
32
value=data, observed=True)
33
34
# below we create a model class
35
model = pm.Model([p, assignment, taus, centers])
36
37
38
map_ = pm.MAP(model)
39
map_.fit()
40
mcmc = pm.MCMC(model)
41
mcmc.sample(100000, 50000)
42
43