In [1]:
!date
%matplotlib inline
In [2]:
import pymc
import numpy as np
import spacepy.plot as spp # for the style
import matplotlib.pyplot as plt
import spacepy.toolbox as tb
In [3]:
# create some test data
x = np.arange(100) * 0.3
f = 0.1 * x**2 - 2.6 * x - 1.5
np.random.seed(76523654)
noise = np.random.normal(size=100) * 1. # create some Gaussian noise
f = f + noise # add noise to the data
plt.plot(x, f, '.')
Out[3]:
In [4]:
# the traditional chi-square fit
z = np.polyfit(x, f, 2)
print('The chi-square result: ', z)
In [8]:
#priors
sig = pymc.Uniform('sig', 0.0, 100.0, value=1.)
a = pymc.Uniform('a', -10.0, 10.0, value= 0.0)
b = pymc.Uniform('b', -10.0, 10.0, value= 0.0)
c = pymc.Uniform('c', -10.0, 10.0, value= 0.0)
In [9]:
#model
@pymc.deterministic(plot=False)
def mod_quadratic(x=x, a=a, b=b, c=c):
return a*x**2 + b*x + c
In [10]:
#likelihood
y = pymc.Normal('y', mu=mod_quadratic, tau=1.0/sig**2, value=f, observed=True)
#———————————————————–
In [12]:
# Now, go to command line and run the following (or alternatively put them in a file):
R = pymc.MCMC((sig, a, b, c, y)) # build the model
R.sample(50000, 1000, thin=10, burn_till_tuned=True) # populate and run it
R.stats()
pymc.Matplot.summary_plot(R)
pymc.Matplot.plot(R)
R.summary()
In [23]:
R.stats()['a']['mean']
Out[23]:
In [31]:
ind = np.random.random_integers(len(R.trace('a')[...])-1, size=1000)
vals = np.zeros([len(x), len(ind)], dtype=float)
for ii, trace in enumerate(ind):
vals[:,ii] = R.trace('a')[...][trace]*x**2 + R.trace('b')[...][trace]*x + R.trace('c')[...][trace]
plt.plot(x, vals[:,ii], c='r', alpha=0.1)
plt.plot(x, f, '.', label='Data', c='b')
# plt.plot(x,z[0]*x**2 + z[1]*x + z[2], label='Chi sq', c='g')
plt.plot(x, R.stats()['a']['mean']*x**2 +
R.stats()['b']['mean']*x +
R.stats()['c']['mean'], 'k.-', label='Bayes')
plt.legend(loc='upper left')
Out[31]:
In [ ]:
In [13]:
# get the median absolute deviation of the residuals for each method
res1 = np.abs(f-z[0]*x**2 + z[1]*x + z[2])
mad1 = tb.medAbsDev(res1)
res2 = np.abs(f-R.a.value*x**2 +
R.b.value*x +
R.c.value)
mad2 = tb.medAbsDev(res2)
print('Chi sq MedAbsDev: {0}'.format(mad1))
print('Bayes MedAbsDev: {0}'.format(mad2))
In [14]:
print(z, (R.a.value, R.b.value, R.c.value))
In [ ]:
In [ ]:
In [ ]:
In [ ]: