Inserting pymc symbollic variables into theano shared array


#1

Pymc Noob here. I am trying to create a vector whose value depends on two parameters n, the number of days to next holiday, and p, the number of days since previous holiday. If n == p == 0, then the vector takes on value

[0., 1., 1., 0., 0., 1., 0., 0., 0., 1., 0.]

Otherwise it takes on

[1., 0., 0., lambda_23, 1-lambda_23, 0.,1-lambda_34, lambda_34, lambda_41, 0., 1-lambda_41].

So each day in the time series has a transition probability vector depending on the daily n, p values. lambda_23, lambda_34, lambda_41 are pymc3 symbolic values defined in some model. For example:

with pm.Model() as model:
    lambda_23 = pm.Uniform('lambda_23', 0, 1)
    lambda_34 = pm.Uniform('lambda_34', 0, 1)
    lambda_41 = pm.Uniform('lambda_41', 0, 1)

I tried this but it won’t work

n = tt.iscalar('n')
p = tt.iscalar('p')

trans_mat_holiday = theano.shared(
    np.array([0., 1., 1., 0., 0., 1., 0., 0., 0., 1., 0.],
        dtype=NPFLOAT), 'trans_mat_holiday')

theano.config.compute_test_value = 'ignore'
f_get_trans_prob = theano.function([n, p],
    tt.switch(tt.eq(n, 0) & tt.eq(p, 0), 
        trans_mat_holiday, 
        Op_NonHolidayTransitionProbabilities()(
            lambda_23, lambda_34, lambda_41)) )

where Op_NonHolidayTransitionProbabilities is defined as:

class Op_NonHolidayTransitionProbabilities(theano.Op):
    __props__ = ()

    itypes = [tt.dscalar, tt.dscalar, tt.dscalar]
    otypes = [tt.dvector]

    def perform(self, node, inputs, output_storage):
        lambda_23 = inputs[0]
        lambda_34 = inputs[1]
        lambda_41 = inputs[2]
        z=output_storage[0]
        z[0] = theano.shared(np.array([1., 0., 0., lambda_23, 1-lambda_23, 0.,
            1-lambda_34, lambda_34, lambda_41, 0., 1-lambda_41]) )

This is the error

MissingInputError: Input 0 of the graph (indices start from 0), used to compute Op_NonHolidayTransitionProbabilities(lambda_23, lambda_34, lambda_41), was not provided and not given a value. Use the Theano flag exception_verbosity='high', for more information on this error.

#2

You should stack and set_subtensor the shared tensors with the symbolic variables into a symbolic tensor, not into a shared array.


#3

Thanks! That works out nicely.