how to fit a method belonging to an instance with pymc3?

后端 未结 3 1376
名媛妹妹
名媛妹妹 2020-11-30 14:12

I failed to fit a method belonging to an instance of a class, as a Deterministic function, with PyMc3. Can you show me how to do that ?

For simplicity, my case is su

3条回答
  •  無奈伤痛
    2020-11-30 14:40

    I finally converged toward the successful code below:

    import numpy as np
    import theano
    from scipy.interpolate import interp1d
    import pymc3 as pm3
    theano.config.compute_test_value = 'ignore'
    theano.config.on_unused_input = 'ignore'
    
    class cprofile:
        observations = np.array([6.25,2.75,1.25,1.25,1.5,1.75,1.5,1])
        x = np.arange(0,18,0.5)
        observed_x = np.array([0.3,1.4,3.1,5,6.8,9,13.4,17.1])    
    
        def doMAP(self):
            model = pm3.Model()
            with model:
                t = pm3.Uniform("t",0,5)
                y = pm3.Uniform("y",0,5)
                z = pm3.Uniform("z",0,5)
                obs=pm3.Normal('obs',
                  mu=FunctionIWantToFit(self)(t,y,z),
                  sd=0.1,observed=self.observations)
                start = pm3.find_MAP()
                print('start: ',start)
    
    class FunctionIWantToFit(theano.gof.Op):
        itypes=[theano.tensor.dscalar,
                theano.tensor.dscalar,
                theano.tensor.dscalar]
        otypes=[theano.tensor.dvector]
    
        def __init__(self, cp):
            self.cp = cp # note cp is an instance of the 'cprofile' class
    
        def perform(self,node, inputs, outputs):
            t, y, z = inputs[0], inputs[1], inputs[2]
    
            xxx = self.cp.x
            temp = t+y*xxx+z*xxx**2
            interpolated_concentration = interp1d(xxx,temp)   
            outputs[0][0] = interpolated_concentration(self.cp.observed_x)
    
    testcp=cprofile()
    testcp.doMAP()
    

    thanks to the answer by Dario because I was too slow to understand the first answer by myself. I get it retrospectively but I strongly think the pymc3 doc is painfully unclear. It should contain very simple and illustrative examples.

    However I didn’t succed in doing anything that work following the comment by Chris. Could anyone explain and/or give an example ?

    One more thing: I don’t know whether my example above is efficient or could be simplified. In particular it gives me the impression the instance ‘testcp’ is copied twice in memory. More comments/answers are welcome to go further.

提交回复
热议问题