Skip to content

Instantly share code, notes, and snippets.

@joezuntz
Created February 1, 2012 17:33
Show Gist options
  • Save joezuntz/1718237 to your computer and use it in GitHub Desktop.
Save joezuntz/1718237 to your computer and use it in GitHub Desktop.
Example of using pymc to display and fit a graphical model
from numpy import sqrt,exp,log,pi
import numpy as np
import pymc
#Example script showing how to fit
#Generate some fake data to fit.
#Use fixed mean and variance
true_mu = 2.4
true_sigma = 0.7
N = 100
observations = np.random.randn(N)*true_sigma + true_mu
#Generate the PyMC nodes (random variables).
#The first two declare only the priors.
#The last gives the dependence of the probability on the parents
#and sets the observed value - this is the data.
mu = pymc.Uniform('mu',lower=-5,upper=5)
sigma = pymc.Uniform('sigma',lower=0.01,upper=2.0)
P = pymc.Normal('Observed Samples', mu=mu, tau=sigma**-2, value=observations, observed=True)
#Build a model out of these three variables
model = pymc.Model([mu,sigma,P])
#Make a slightly pretty graph out of it
graph = pymc.graph.graph(model)
graph.write_png("graph.png")
#Get the maximum posterior fit to the model
#We could also sample in various ways and do other things with it instead.
fitter = pymc.MAP(model)
fitter.fit()
print "Maximum posterior mu = ", mu.value
print "Maximum posterior sigma = ", sigma.value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment