-->

自定义运算theano的定义毕业生(Defining grad of a custom Op the

2019-09-29 09:26发布

我试图定义一个定制theano运带倾斜度与pymc3使用它,但我不明白如何界定grad方法。

下面的代码是在那里我卡住了。 函数phi()是一个模拟函数(在实践中,它是一个外部程序); 为一个标量输入x它返回一个矢量(phi_0(x), phi_1(x), ...) 功能phi_diff()也为模拟函数)返回向量(dphi_0/dx, dphi_1/dx, ...)

我包phi()phi_diff()theano.Op对象,但我实现的grad功能不起作用。 theano的文档包含简单的例子,我不知道如何给他们在这种情况下适应。 任何帮助将不胜感激。

import numpy as np
import theano.tensor as T
import theano

theano.config.optimizer = "None"
theano.config.exception_verbosity = "high"


def phi(x):
    return np.arange(n) * x


def phi_diff(x):
    return np.arange(n)


class PhiOp(theano.Op):
    itypes = [theano.tensor.dscalar]
    otypes = [theano.tensor.dvector]

    def perform(self, node, inputs, output_storage):
        x = inputs[0]
        output_storage[0][0] = phi(x)

    def grad(self, inputs, output_grads):
        x = inputs[0]
        # ???
        return [PhiDiffOp()(x) * output_grads[0]]


class PhiDiffOp(theano.Op):
    itypes = [theano.tensor.dscalar]
    otypes = [theano.tensor.dvector]

    def perform(self, node, inputs, output_storage):
        x = inputs[0]
        output_storage[0][0] = phi_diff(x)


n = 5
x = 777.

phi_op = PhiOp()
x_tensor = T.dscalar("x_tensor")
phi_func = theano.function([x_tensor], phi_op(x_tensor))
np.testing.assert_allclose(phi_func(x), phi(x))

T.jacobian(phi_op(x_tensor), x_tensor)

Answer 1:

发现该溶液中,以下的变化:

def phi_diff(x):
    return np.arange(n, dtype=np.float_)

class PhiOp(theano.Op):
    def grad(self, inputs, output_grads):
        x = inputs[0]
        gg = (PhiDiffOp()(x) * output_grads[0]).sum()
        return [gg]


文章来源: Defining grad of a custom Op theano