Skip to content

Instantly share code, notes, and snippets.

@fredcallaway
Created November 10, 2016 06:11
Show Gist options
  • Save fredcallaway/1903a395f9118323de8a1a02e40492f4 to your computer and use it in GitHub Desktop.
Save fredcallaway/1903a395f9118323de8a1a02e40492f4 to your computer and use it in GitHub Desktop.
Stochastic matrix in pymc3
import numpy as np
import pymc3 as pm
import theano
class StochasticMatrix(pm.Continuous):
"""A stochastic matrix has rows that sum to 1."""
def __init__(self, theta, *args, **kwargs):
shape = (theta.shape[-1], theta.shape[-1])
kwargs.setdefault('shape', shape)
super(StochasticMatrix, self).__init__(*args, **kwargs)
self.theta = theta
self.row_distribution = pm.Dirichlet.dist(a=self.theta, transform=None)
def logp(self, value):
results, updates = theano.scan(self.row_distribution.logp, value)
return results.sum()
def random(self):
return pm.Dirichlet('rand', self.theta).random(size=len(self.theta))
with Model() as model:
transition = StochasticMatrix('transition', theta=np.array([1, 1]), testval=np.array([[1, 0], [1, 0]]))
trace = pm.sample(5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment