tf.custom_gradient
仅接受一个Tensor x
,如果此操作需要多个输入呢?
例如,要定义需要输入x
和label
的Softmax的梯度?
感谢@AllenLavoie的建议,我使用Python列表作为输入。
def self_define_op_multiple_inputs():
@tf.custom_gradient
def loss_func(input_):
x = input_[0]
label = input_[2]
def grad(dy):
return [dy, dy]
return x - label, grad
x = tf.range(10, dtype=tf.float32)
y = tf.range(10, dtype=tf.int32)
loss = loss_func([x, y])
if __name__ == '__main__':
self_define_op_multiple_inputs()
似乎它将Python list
转换为Tensor
。上面的代码段将引发一个TypeError
:
TypeError: Cannot convert a list containing a tensor of dtype <dtype: 'int32'> to <dtype: 'float32'> (Tensor is: <tf.Tensor 'range_1:0' shape=(10,) dtype=int32>)
如何解决?
答案 0 :(得分:0)
我相信您需要像tf Graph这样的输入:+ n_input是输入数字
x = tf.placeholder("float", [None, n_input])
y = tf.placeholder("float", [None])
这能回答您的问题吗?
答案 1 :(得分:0)
昨天我遇到了类似的问题,找到了这篇文章,我相信我知道您遇到了什么。问题在于,在使用@ tf.custom_gradient时,其装饰的函数可能具有多个输入(而不是张量列表)。看下面的代码(请注意,这只是一个没有实际意义的测试代码):
@tf.custom_gradient
def loop1(x,a):
def grad(dy):
return dy*3,dy*2
n = tf.multiply(x,a)
return n,grad
通过使用两个输入x和a,您必须在grad函数中分别返回两个渐变。 dy * 3对应于x的梯度,dy * 2对应于a的梯度。
我认为在此功能中,文档使人们非常困惑,但是您仍然可以使用多个输入,只需确保您具有相同数量的渐变,否则会遇到错误。