首页 文章

具有自定义“丢失”功能的渐变更新

提问于
浏览
0

我正在神经网络上的tensorflow工作,试图最大化两个数据集之间的相关性:http://ttic.uchicago.edu/~klivescu/papers/andrew_icml2013.pdf

我有一个"loss"函数有点复杂,所以我用numpy数组(并称之为corr_func())编写它,以便它可以使用张量运行我使用tf.py_func函数,我尝试更新渐变以与此处所示相同的方式How to make a custom activation function with only Python in Tensorflow?

这给了我们下面的代码

def omega_grad(op, grad):
   x = op.inputs[0]
   y = op.inputs[1]
   n_gr1 = tf_omega_grad_H1(x,y)
   n_gr2 = tf_omega_grad_H2 (x,y)
   return grad * n_gr1, grad * n_gr2

两个函数tf_omega_gradH1 / 2()是正确的,但有点长,这里要显示,但在本文中定义为给定两个输出的相关的偏导数 . 然后定义相关性

corr = py_func(corr_func, [H1,H2], tf.float32, stateful=True, name='assemblage',grad=omega_grad)
optimizer=tf.train.GradientDescentOptimizer(learning_rate).minimize(-corr)

事情是不行的,我尝试运行优化器,它引发了以下错误:

InternalError (see above for traceback): Failed to run py callback pyfunc_31: see error log.
 [[Node: gradients/assemblage_grad/PyFunc = PyFunc[Tin=[DT_FLOAT, DT_FLOAT], Tout=[DT_FLOAT], token="pyfunc_31", _device="/job:localhost/replica:0/task:0/cpu:0"](Reseau_de_neurone1/relu_layer_3, Reseau_de_neurone2/relu_layer_3)]]

如果我尝试通过运行来查看渐变,还有更多:

tf.gradients(corr,H1)

它返回None ...显然我不能很好地控制这个梯度更新,我不知道如何修复这个bug .

注意:H1和H2是我的神经网络的两个输出

更新:错误的日志是:

Traceback (most recent call last):

  File "<ipython-input-1-4ce1bb0cc21d>", line 1, in <module>
    runfile('/home/zagdoun/Bureau/tutoTensorflow/NN.py', wdir='/home/zagdoun/Bureau/tutoTensorflow')

  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", line 866, in runfile
    execfile(filename, namespace)

  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", line 94, in execfile
    builtins.execfile(filename, *where)

  File "/home/zagdoun/Bureau/tutoTensorflow/NN.py", line 344, in <module>
    _, c= sess.run([optimizer, corr],feed_dict={X : batch_X, Y : batch_Y})

  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 778, in run
    run_metadata_ptr)

  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 982, in _run
    feed_dict_string, options, run_metadata)

  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1032, in _do_run
    target_list, options, run_metadata)

  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1052, in _do_call
    raise type(e)(node_def, op, message)

InternalError: Failed to run py callback pyfunc_1: see error log.
     [[Node: gradients/assemblage_grad/PyFunc = PyFunc[Tin=[DT_FLOAT, DT_FLOAT], Tout=[DT_FLOAT], token="pyfunc_1", _device="/job:localhost/replica:0/task:0/cpu:0"](Reseau_de_neurone1/relu_layer_3, Reseau_de_neurone2/relu_layer_3)]]

Caused by op u'gradients/assemblage_grad/PyFunc', defined at:
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/spyder/utils/ipython/start_kernel.py", line 227, in <module>
    main()
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/spyder/utils/ipython/start_kernel.py", line 223, in main
    kernel.start()
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/ipykernel/kernelapp.py", line 474, in start
    ioloop.IOLoop.instance().start()
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/zmq/eventloop/ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/tornado/ioloop.py", line 887, in start
    handler_func(fd_obj, events)
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/tornado/stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/tornado/stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/ipykernel/kernelbase.py", line 276, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/ipykernel/kernelbase.py", line 228, in dispatch_shell
    handler(stream, idents, msg)
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/ipykernel/kernelbase.py", line 390, in execute_request
    user_expressions, allow_stdin)
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/ipykernel/ipkernel.py", line 196, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/ipykernel/zmqshell.py", line 501, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2717, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2827, in run_ast_nodes
    if self.run_code(code, result):
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2881, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-1-4ce1bb0cc21d>", line 1, in <module>
    runfile('/home/zagdoun/Bureau/tutoTensorflow/NN.py', wdir='/home/zagdoun/Bureau/tutoTensorflow')
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", line 866, in runfile
    execfile(filename, namespace)
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", line 94, in execfile
    builtins.execfile(filename, *where)
  File "/home/zagdoun/Bureau/tutoTensorflow/NN.py", line 324, in <module>
    optimizer=tf.train.GradientDescentOptimizer(learning_rate).minimize(-corr)
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/tensorflow/python/training/optimizer.py", line 315, in minimize
    grad_loss=grad_loss)
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/tensorflow/python/training/optimizer.py", line 386, in compute_gradients
    colocate_gradients_with_ops=colocate_gradients_with_ops)
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/tensorflow/python/ops/gradients_impl.py", line 560, in gradients
    grad_scope, op, func_call, lambda: grad_fn(op, *out_grads))
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/tensorflow/python/ops/gradients_impl.py", line 368, in _MaybeCompile
    return grad_fn()  # Exit early
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/tensorflow/python/ops/gradients_impl.py", line 560, in <lambda>
    grad_scope, op, func_call, lambda: grad_fn(op, *out_grads))
  File "/home/zagdoun/Bureau/tutoTensorflow/NN.py", line 278, in omega_grad
    n_gr1 = tf_omega_grad_H1(x,y)
  File "/home/zagdoun/Bureau/tutoTensorflow/NN.py", line 267, in tf_omega_grad_H1
    z = tf.py_func(omega_grad_H1, [X,Y],tf.float32, stateful=True)
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/tensorflow/python/ops/script_ops.py", line 189, in py_func
    input=inp, token=token, Tout=Tout, name=name)
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/tensorflow/python/ops/gen_script_ops.py", line 40, in _py_func
    name=name)
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 768, in apply_op
    op_def=op_def)
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2336, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1228, in __init__
    self._traceback = _extract_stack()

...which was originally created as op u'assemblage', defined at:
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/spyder/utils/ipython/start_kernel.py", line 227, in <module>
    main()
[elided 19 identical lines from previous traceback]
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", line 94, in execfile
    builtins.execfile(filename, *where)
  File "/home/zagdoun/Bureau/tutoTensorflow/NN.py", line 323, in <module>
    corr = py_func(assemblage, [H1,H2], tf.float32, stateful=True, name='assemblage',grad=omega_grad)
  File "/home/zagdoun/Bureau/tutoTensorflow/NN.py", line 223, in py_func
    return tf.py_func(func, inp, Tout, stateful=stateful, name=name)
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/tensorflow/python/ops/script_ops.py", line 189, in py_func
    input=inp, token=token, Tout=Tout, name=name)
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/tensorflow/python/ops/gen_script_ops.py", line 40, in _py_func
    name=name)
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 768, in apply_op
    op_def=op_def)
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2336, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/home/zagdoun/anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1228, in __init__
    self._traceback = _extract_stack()

InternalError (see above for traceback): Failed to run py callback pyfunc_1: see error log.
     [[Node: gradients/assemblage_grad/PyFunc = PyFunc[Tin=[DT_FLOAT, DT_FLOAT], Tout=[DT_FLOAT], token="pyfunc_1", _device="/job:localhost/replica:0/task:0/cpu:0"](Reseau_de_neurone1/relu_layer_3, Reseau_de_neurone2/relu_layer_3)]]

see the tensorboard graph

1 回答

  • 1

    从我可以阅读的内容来看,py_func函数不能传播渐变,但是,您可以手动指定渐变 .

    @Yaroslav Bulatov在这篇文章中回答了类似的事情:How Gradient passed by tf.py_func

    import numpy as np
    import tensorflow as tf
    
    # 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)
    

    Hense有意义的是你既不能用tf.gradients(corr,H1)也不能用GradientDescentOptimizer传播渐变 .

相关问题