0

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

我有一个“损失”函数,它有点复杂,所以我用 numpy 数组(并称之为 corr_func())来编写它,以便它可以与张量一起运行我使用 tf.py_func 函数,我尝试更新以与此处所示相同的方式渐变如何在 Tensorflow 中仅使用 Python 制作自定义激活函数?

这给了我们以下代码

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)

它返回无......显然我不能很好地控制这个渐变更新,我不知道如何修复这个错误。

注意: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)]]

见张量板图

4

1 回答 1

1

据我所知,py_func 函数无法传播渐变,但是,您可以手动指定渐变。

@Yaroslav Bulatov 在这篇文章中回答了类似的问题:梯度如何通过 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)

因此,您既不能使用 tf.gradients(corr,H1) 也不能使用 GradientDescentOptimizer 传播渐变是有道理的。

于 2017-07-19T09:52:48.217 回答