我如何判断 tf op 是否具有梯度?

How can I tell if a tf op has a gradient or not?

我有兴趣在 tensorflow 中使用 SparseTensor,但是,我经常得到

LookupError: No gradient defined for operation ...

显然没有为稀疏张量的许多操作定义梯度计算。在实际编写和 运行 我的代码之前,是否有任何简单的方法来检查操作是否具有梯度?

tensorflow.python.framework.ops中有一个get_gradient_function函数。它接受一个操作和 returns 一个相应的梯度操作。示例:

import tensorflow as tf
from tensorflow.python.framework.ops import get_gradient_function

a = tf.add(1, 2, name="Add_these_numbers")
b = tf.multiply(a, 3, name='mult')

mult = tf.get_default_graph().get_operation_by_name('mult')
print(get_gradient_function(mult))  # <function _MulGrad at 0x7fa29950dc80>

tf.stop_gradient(a, name='stop')
stop = tf.get_default_graph().get_operation_by_name('stop')
print(get_gradient_function(stop))  # None