I am trying to write my own gradient function for 'my_op', which for example contains only a call to tf.identity () (ideally, this could be any chart).
import tensorflow as tf from tensorflow.python.framework import function def my_op_grad(x): return [tf.sigmoid(x)] @function.Defun(a=tf.float32, python_grad_func=my_op_grad) def my_op(a): return tf.identity(a) a = tf.Variable(tf.constant([5., 4., 3., 2., 1.], dtype=tf.float32)) sess = tf.Session() sess.run(tf.initialize_all_variables()) grad = tf.gradients(my_op(a), [a])[0] result = sess.run(grad) print(result) sess.close()
Unfortunately, I get the following error:
Traceback (most recent call last): File "custom_op.py", line 19, in <module> grad = tf.gradients(my_op(a), [a])[0] File "/Users/njk/tfm/lib/python3.5/site-packages/tensorflow/python/framework/function.py", line 528, in __call__ return call_function(self._definition, *args, **kwargs) File "/Users/njk/tfm/lib/python3.5/site-packages/tensorflow/python/framework/function.py", line 267, in call_function compute_shapes=False) File "/Users/njk/tfm/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 2285, in create_op raise TypeError("Input #%d is not a tensor: %s" % (idx, a)) TypeError: Input
I know that you can create a custom C ++ operation, but in my case I just need to write my own gradient for a function that can be easily written in Python using standard TensorFlow operations, so I would like to avoid writing unnecessary C ++ code .
In addition, I am using an upstream version of TensorFlow from GitHub.