小编tmm*_*m13的帖子

定制Theano Op进行数值积分

我正在尝试编写一个自定义的Theano Op,它在数值上集成了两个值之间的函数.Op是PyMC3的自定义可能性,涉及一些积分的数值计算.我不能简单地使用@as_op装饰器,因为我需要使用HMC来执行MCMC步骤.任何帮助将不胜感激,因为这个问题似乎已经走到了好几次,但一直没有得到解决(如/sf/ask/2579711081/,Theano:实现一个积分函数).

显然,一种解决方案是在Theano中编写一个数值积分器,但是当非常好的积分器已经可用时,这似乎是浪费精力,例如通过scipy.integrate.

为了保持这个最小的例子,让我们尝试在Op中集成0到1之间的函数.以下在Op之外集成了Theano函数,并且在我的测试已经消失的情况下产生了正确的结果.

import theano
import theano.tensor as tt
from scipy.integrate import quad

x = tt.dscalar('x')
y = x**4 # integrand
f = theano.function([x], y)

print f(0)
print f(1)

ans = integrate.quad(f, 0, 1)[0]

print ans
Run Code Online (Sandbox Code Playgroud)

但是,尝试在Op中进行集成似乎要困难得多.我目前的最大努力是:

import numpy as np
import theano
import theano.tensor as tt
from scipy import integrate

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

    def make_node(self, x):
        x = tt.as_tensor_variable(x)
        return theano.Apply(self, [x], [x.type()])

    def perform(self, node, inputs, output_storage):
        x = inputs[0]
        z …
Run Code Online (Sandbox Code Playgroud)

python theano pymc3

5
推荐指数
1
解决办法
870
查看次数

标签 统计

pymc3 ×1

python ×1

theano ×1