Tensorflow 2.0返回带有梯度ttype = INT32上的意外输出



以下代码应输出y = x*x的梯度for x = 2,即4的值。但是,当使用tensorflow 2.0.0--alpha0。如下一个摘要所示,当X的定义更改以使用tf.float32而不是tf.int32时,输出更改为4.的正确值。在这种情况下正确工作?

print(tf.__version__)
x = tf.constant(2, dtype=tf.int32)
with tf.GradientTape() as tape:
  tape.watch(x)
  y = x ** 2
  print(tape.gradient(y, x))

输出:

2.0.0-alpha0
None

请注意下一个片段中对tf.float32的更改:

print(tf.__version__)
x = tf.constant(2, dtype=tf.float32)
with tf.GradientTape() as tape:
  tape.watch(x)
  y = x ** 2
  print(tape.gradient(y, x))

输出:

2.0.0-alpha0
tf.Tensor(4.0, shape=(), dtype=float32)

原因是tf.gradient不会通过整数张量传播梯度。在此GitHub问题中已引用了这一点:

https://github.com/tensorflow/tensorflow/issues/20524

最新更新