PyMC中的装饰器

时间:2014-06-03 01:01:48

标签: python decorator python-decorators pymc mcmc

我有三个关于装饰器的问题,我无法找到答案:

Q1)PyMC中装饰器的参数(@Deterministic,@ Stochastic)表示什么?

Q2)

@pymc.stochastic(dtype=int)
def switchpoint(value=10, t_l=0, t_h=110):
    def logp(value, t_l, t_h):
        if value > t_h or value < t_l:
            return -np.inf
        else:
            return -np.log(t_h - t_l + 1)
    def random(t_l, t_h):
        from numpy.random import random
        return np.round( (t_l - t_h) * random() ) + t_l

1)打印switchpoint.logp #prints log-probability as expected

2)print switchpoint.random #does不生成随机数

3)print switchpoint.random()#生成一个随机数

4)print switchpoint.logp() #error

如果2没有工作,3工作,那么1应该没有工作,并且instaed 4应该工作(这与我观察到的相反)。有人可以解释发生了什么吗?

Q3)

@pymc.stochastic(dtype=int)
def switchpoint(value=1900, t_l=1851, t_h=1962):
    if value > t_h or value < t_l:
        # Invalid values
        return -np.inf
    else:
        # Uniform log-likelihood
        return -np.log(t_h - t_l + 1)

如果我输入logp,这部分代码会执行吗?

这里没有指定它是switchpoint.logp吗?

1 个答案:

答案 0 :(得分:2)

Q1)随机记录的所有参数的含义都记录在案here。确定性的论据是相同的,加上记录here的其他论据。

Q2)行为的差异在于PyMC内部有一些神奇的实际执行switchpoint.logp函数并将其转换为Python property,而switchpoint.random没有得到这个治疗,并作为一种功能保持。

如果你对实际发生的事情感到好奇,这里有一些相关的source

def get_logp(self):
    if self.verbose > 1:
        print '\t' + self.__name__ + ': log-probability accessed.'
    logp = self._logp.get()
    if self.verbose > 1:
        print '\t' + self.__name__ + ': Returning log-probability ', logp

    try:
        logp = float(logp)
    except:
        raise TypeError, self.__name__ + ': computed log-probability ' + str(logp) + ' cannot be cast to float'

    if logp != logp:
        raise ValueError, self.__name__ + ': computed log-probability is NaN'

    # Check if the value is smaller than a double precision infinity:
    if logp <= d_neg_inf:
        if self.verbose > 0:
            raise ZeroProbability, self.errmsg + ": %s" %self._parents.value
        else:
            raise ZeroProbability, self.errmsg

    return logp

def set_logp(self,value):
    raise AttributeError, 'Potential '+self.__name__+'\'s log-probability cannot be set.'

logp = property(fget = get_logp, fset=set_logp, doc="Self's log-probability value conditional on parents.")

还有一些其他的东西,比如logp函数中的LazyFunction,但这是基本的想法。

Q3)stochastic装饰器中有一些(更多)魔术,它使用代码内省来确定random中是否定义了logpswitchpoint个子函数。如果是,则使用logp子函数来计算logp,如果不是,则仅使用switchpoint本身。该源代码为here

# This gets used by stochastic to check for long-format logp and random:
if probe:
    # Define global tracing function (I assume this is for debugging??)
    # No, it's to get out the logp and random functions, if they're in there.
    def probeFunc(frame, event, arg):
        if event == 'return':
            locals = frame.f_locals
            kwds.update(dict((k,locals.get(k)) for k in keys))
            sys.settrace(None)
        return probeFunc

    sys.settrace(probeFunc)

    # Get the functions logp and random (complete interface).
    # Disable special methods to prevent the formation of a hurricane of Deterministics
    cur_status = check_special_methods()
    disable_special_methods()
    try:
        __func__()
    except:
        if 'logp' in keys:
            kwds['logp']=__func__
        else:
            kwds['eval'] =__func__
    # Reenable special methods.
    if cur_status:
        enable_special_methods()

for key in keys:
    if not kwds.has_key(key):
        kwds[key] = None

for key in ['logp', 'eval']:
    if key in keys:
        if kwds[key] is None:
            kwds[key] = __func__

同样,还有更多的东西在进行,而且相当复杂,但这是基本的想法。