如何梯度通过了tf.py_func [英] How Gradient passed by tf.py_func

查看:98
本文介绍了如何梯度通过了tf.py_func的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是更快的R-CNN在tensorflow实现.结果 的 proposal_layer 实施通过蟒

This is Faster R-CNN implement in tensorflow.
The proposal_layer is implement by python

我很好奇如果梯度可以通过结果,通过 权重和偏见正在不断变化结果 所以我认为梯度递送回成功

i am curious about if gradient can pass by tf.py_func
the weights and biases are keep changing
so I think the gradient deliver back successful

然后我做一个小的测试

import tensorflow as tf
import numpy as np

def addone(x):
    # print type(x)
    return x + 1

def pyfunc_test():
    # create data
    x_data = tf.placeholder(dtype=tf.float32, shape=[None])
    y_data = tf.placeholder(dtype=tf.float32, shape=[None])

    w = tf.Variable(tf.constant([0.5]))
    b = tf.Variable(tf.zeros([1]))

    y1 = tf.mul(w, x_data, name='y1')
    y2 = tf.py_func(addone, [y1], tf.float32)
    y = tf.add(y2, b)

    loss = tf.reduce_mean(tf.square(y - y_data))
    optimizer = tf.train.GradientDescentOptimizer(0.5)
    train = optimizer.minimize(loss)

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())

        for step in xrange(201):
            ran = np.random.rand(115).astype(np.float32)
            ans = ran * 1.5 + 3
            dic = {x_data: ran, y_data: ans}
            tt, yy, yy1= sess.run([train, y1, y2], feed_dict=dic)
            if step % 20 == 0:
                print 'step {}'.format(step)
                print '{}, {}'.format(w.eval(), b.eval())

        test = sess.run(y, feed_dict={x_data:[1]})
        print 'test = {}'.format(test)


if __name__ == '__main__':
    pyfunc_test()

可变不断变化,但保持的值初始化后禁止改变

Variable b keep changing, but w keep the value after initialize and never change

得到的值,点击 GET

sess.run(tf.gradients(loss, b), feed_dict=dic) get value
sess.run(tf.gradients(loss, w), feed_dict=dic) get {TypeError}Fetch argument None has invalid type <type 'NoneType'>

我知道有些问题,建议使用<6>和<7>点击 但我不能找到这些在较快rcnn回购(在后的顶部链接)点击 我在做错事或失去了一些东西,这样冷冻

I know some questions suggest use tf.RegisterGradient and gradient_override_map
but I can't find these in the faster rcnn repo(link on top of post)
am I do something wrong or missing something so that w is freeze

推荐答案

的梯度(只检查).有此要旨通过@harpone其显示了如何使用梯度超控的地图为py_func.

Gradient of py_func is None (just check ops.get_gradient_function(y2.op)). There's this gist by @harpone which shows how to use gradient override map for py_func.

这里是你的示例修改为使用该配方

Here's your example modified to use that recipe

import numpy as np
import tensorflow as tf

def addone(x):
    # print(type(x)
    return x + 1

def addone_grad(op, grad):
    x = op.inputs[0]
    return x

from tensorflow.python.framework import ops
import numpy as np

# Define custom py_func which takes also a grad op as argument:
def py_func(func, inp, Tout, stateful=True, name=None, grad=None):

    # Need to generate a unique name to avoid duplicates:
    rnd_name = 'PyFuncGrad' + str(np.random.randint(0, 1E+8))

    tf.RegisterGradient(rnd_name)(grad)  # see _MySquareGrad for grad example
    g = tf.get_default_graph()
    with g.gradient_override_map({"PyFunc": rnd_name}):
        return tf.py_func(func, inp, Tout, stateful=stateful, name=name)

def pyfunc_test():

    # create data
    x_data = tf.placeholder(dtype=tf.float32, shape=[None])
    y_data = tf.placeholder(dtype=tf.float32, shape=[None])

    w = tf.Variable(tf.constant([0.5]))
    b = tf.Variable(tf.zeros([1]))

    y1 = tf.mul(w, x_data, name='y1')
    y2 = py_func(addone, [y1], [tf.float32], grad=addone_grad)[0]
    y = tf.add(y2, b)

    loss = tf.reduce_mean(tf.square(y - y_data))
    optimizer = tf.train.GradientDescentOptimizer(0.01)
    train = optimizer.minimize(loss)

    print("Pyfunc grad", ops.get_gradient_function(y2.op))
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())

        for step in range(10):
            #            ran = np.random.rand(115).astype(np.float32)
            ran = np.ones((115)).astype(np.float32)
            ans = ran * 1.5 + 3
            dic = {x_data: ran, y_data: ans}
            tt, yy, yy1= sess.run([train, y1, y2], feed_dict=dic)
            if step % 1 == 0:
                print('step {}'.format(step))
                print('{}, {}'.format(w.eval(), b.eval()))

        test = sess.run(y, feed_dict={x_data:[1]})
        print('test = {}'.format(test))


if __name__ == '__main__':
    pyfunc_test()

这篇关于如何梯度通过了tf.py_func的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆