user2085779
user2085779

Reputation:

AttributeError: __exit__ with pymc

I am using anaconda python on Ubuntu 12.04 When I try to execute following python code

import pymc as pm
import numpy as np

trace = None
with pm.Model() as model:
    alpha = pm.Normal('alpha', mu=0, sd=20)
    beta = pm.Normal('beta', mu=0, sd=20)
    sigma = pm.Uniform('sigma', lower=0, upper=20)

    y_est = alpha + beta * x

    likelihood = pm.Normal('y', mu=y_est, sd=sigma, observed=y)

    start = pm.find_MAP()
    step = pm.NUTS(state=start)
    trace = pm.sample(2000, step, start=start, progressbar=False)

    pm.traceplot(trace);

I get following error

AttributeError                            Traceback (most recent call last)
<ipython-input-7-0d27d14303ac> in <module>()
      3 
      4 trace = None
----> 5 with pm.Model() as model:
      6     alpha = pm.Normal('alpha', mu=0, sd=20)
      7     beta = pm.Normal('beta', mu=0, sd=20)

AttributeError: __exit__

How can I fix it ? What is the problem here?

Upvotes: 0

Views: 1608

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121486

pm.Model() is not a context manager; it doesn't implement the requisite methods. You probably are running a version of pymc where that functionality has not yet been added.

Just assign it to a variable and use directly, after creating the elements:

alpha = pm.Normal('alpha', mu=0, sd=20)
beta = pm.Normal('beta', mu=0, sd=20)
sigma = pm.Uniform('sigma', lower=0, upper=20)
# etc.
model = pm.Model([alpha, beta, sigma, ...])

The model fitting tutorial uses a function to produce the inputs.

Upvotes: 1

Related Questions