【问题标题】:TensorFlow: how to do python function with custom gradients without eval?TensorFlow:如何在没有 eval 的情况下使用自定义渐变执行 python 函数?
【发布时间】:2017-09-19 23:52:56
【问题描述】:

我正在尝试在 python 中编写一些自定义 TensorFlow 函数(使用tf.py_func),我想在 python 中计算结果和梯度。我正在使用gradient_override_map 技巧(例如来自https://gist.github.com/harpone/3453185b41d8d985356cbe5e57d67342How to make a custom activation function with only Python in Tensorflow?)。

然而,当正向函数获取一个 numpy 数组作为输入时,梯度函数获取Tensors。这是一个问题,取决于函数何时被调用,因为可能没有默认会话,和/或可能还没有包含所有必需值的 feed_dict(例如,在 tf.train 优化器中)。

如何执行 py_func,其中前向和后向函数都获取(并返回)numpy 数组?

示例代码:

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

def sin_func(x):
    return np.sin(x)

def sin_grad_func(op, grad):
    x = op.inputs[0].eval()
    grad = grad.eval() # <--- this is what I'd like to avoid
    output_grad = np.cos(x) * grad
    return tf.convert_to_tensor(output_grad)

def py_func(func, inp, Tout, stateful=True, name=None, grad_func=None):
    grad_name = 'PyFuncGrad_' + str(np.random.randint(0, 1E+8))
    tf.RegisterGradient(grad_name)(grad_func)
    g = tf.get_default_graph()
    with g.gradient_override_map({"PyFunc": grad_name}):
        return tf.py_func(func, inp, Tout, stateful=stateful, name=name)

with tf.Session() as sess:
    np_x = np.linspace(0, np.pi, num=1000, dtype=np.float32)
    x = tf.constant(np_x)
    y = py_func(sin_func,
                [x],
                [tf.float32],
                name='np_sin',
                grad_func=sin_grad_func)
    y = y[0]
    gr = tf.gradients(y, [x])
    tf.global_variables_initializer().run()
    plt.plot(y.eval())
    plt.plot(gr[0].eval())

【问题讨论】:

    标签: numpy tensorflow


    【解决方案1】:

    如果您想在渐变函数中包含任意 Python 代码,最简单的解决方案是在 sin_grad_func() 内创建另一个 tf.py_func()

    def sin_grad_func_impl(x, grad):
        return np.cos(x) * grad
    
    def sin_grad_func(op, grad):
        return tf.py_func(sin_grad_func_impl, [x, grad], grad.dtype)
    

    【讨论】:

      猜你喜欢
      • 2022-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-29
      • 2020-03-14
      • 2022-06-14
      • 2022-01-03
      相关资源
      最近更新 更多