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