Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyMC: Setting Constraints when fitting Models

I am trying to set constraints when fitting variables via a MCMC approach with PyMC For instance, I defined the following stochastic models in PyMC

import pymc as pm
a=pm.Uniform('a',lower=0.,upper=1.,value=0.2)
b=pm.Uniform('b',lower=0.,upper=1.,value=0.2)

How can I define the model so that b is always smaller or equals to a? Is this a valid approach?

a=pm.Uniform('a',lower=0.,upper=1.,value=0.2)
b=pm.Uniform('b',lower=0.,upper=b,value=0.2) #used a as the upper bound for b
like image 407
user3695689 Avatar asked Nov 10 '22 06:11

user3695689


1 Answers

I believe you mean 'upper=a'.

I think you can define 'b' as a stochastic variable, dependent on 'a', as in the following:

import pymc as pm
import numpy as np
import scipy.stats as scs

@pm.stochastic
def b(value=0.0, a=a):
    def logp(value, a):
        if 0 <= value <= a:
            return np.log(1/a)
        else:
            return -np.inf

    def random(a):
        return scs.uniform(0, a).rvs()

Now you can test out the variable by calling 'b.random()' and you should see a uniform distribution bounded above by 'a' ('a.value').

Have a look at the PyMC documentation on variables.

like image 164
Dylan Avatar answered Jan 01 '23 20:01

Dylan