In [1]:
import numpy as np
import matplotlib.pyplot as plt
# Intialize random number generator
np.random.seed(123)
# True parameter values
alpha, sigma = 1, 1
beta = [1, 2.5]
# Size of dataset
size = 100
# Predictor variable
X1 = np.linspace(0, 1, size)
X2 = np.linspace(0,.2, size)
# Simulate outcome variable
Y = alpha + beta[0]*X1 + beta[1]*X2 + np.random.randn(size)*sigma
In [2]:
%matplotlib inline
fig, axes = plt.subplots(1, 2, sharex=True, figsize=(10,4))
axes[0].scatter(X1, Y)
axes[1].scatter(X2, Y)
axes[0].set_ylabel('Y'); axes[0].set_xlabel('X1'); axes[1].set_xlabel('X2');
In [3]:
from pymc3 import Model, Normal, HalfNormal
In [4]:
basic_model = Model()
with basic_model:
# Priors for unknown model parameters
alpha = Normal('alpha', mu=0, sd=10)
beta = Normal('beta', mu=0, sd=10, shape=2)
sigma = HalfNormal('sigma', sd=1)
# Expected value of outcome
mu = alpha + beta[0]*X1 + beta[1]*X2
# Likelihood (sampling distribution) of observations
Y_obs = Normal('Y_obs', mu=mu, sd=sigma, observed=Y)
In [22]:
basic_model = Model()
with basic_model:
# Priors for unknown model parameters
alpha = Normal('alpha', mu=0, sd=10)
beta = Normal('beta', mu=0, sd=10, shape=2)
sigma = HalfNormal('sigma', sd=1)
# Expected value of outcome
mu = alpha + beta[0]*X1 + beta[1]*X2
# Likelihood (sampling distribution) of observations
Y = Normal('Y_obs', mu=mu, sd=sigma)
In [23]:
alpha = Normal('alpha', mu=0, sd=10)
beta = Normal('beta', mu=0, sd=10, shape=2)
sigma = HalfNormal('sigma', sd=1)
# Expected value of outcome
mu = alpha + beta[0]*X1 + beta[1]*X2
# Likelihood (sampling distribution) of observations
Y = Normal('Y_obs', mu=mu, sd=sigma)
In [5]:
from pymc3 import find_MAP
map_estimate = find_MAP(model=basic_model)
print(map_estimate)
In [7]:
from scipy import optimize
from pymc3 import NUTS, sample
with basic_model:
# obtain starting values via MAP
start = find_MAP(fmin=optimize.fmin_powell)
# instantiate sampler
step = NUTS(scaling=start)
# draw 2000 posterior samples
trace = sample(2000, step, start=start)
In [8]:
from pymc3 import traceplot
traceplot(trace);
In [9]:
from pymc3 import summary
summary(trace)
In [13]:
type(basic_model)
Out[13]:
In [14]:
type(trace)
Out[14]:
In [15]:
dir(trace)
Out[15]:
In [17]:
trace.varnames
Out[17]:
In [18]:
trace.get_values('alpha')
Out[18]:
In [19]:
dir(basic_model)
Out[19]:
In [20]:
basic_model.observed_RVs
Out[20]:
In [21]:
basic_model.unobserved_RVs
Out[21]:
In [ ]: