我目前正在用 python 开发一个“四胜” Actor 评论家代理。在尝试反向传播之前收集的 Action 概率分布时,我遇到了以下错误:ZeroDivisionError:整数除法或除以零
我能够重现错误:
import tensorflow as tf
with tf.GradientTape() as tape:
t = tf.Variable([1.])
concat = tf.concat(values=[t[0], t[0]], axis=0)
concat_sum = tf.reduce_sum(concat)
grads = tape.gradient(concat_sum, t)
我确实知道这个问题在这个代码示例中可能听起来微不足道。为什么这里会出现错误,我仍然无法理解!如果连接张量的第一个元素并最终将它们相加,则不应与相同:
with tf.GradientTape() as tape:
t = tf.Variable([1.])
result = t + t
grads = tape.gradient(result, t)
为什么一个可以生成有效的渐变,而另一个却不能?
我正在我的 CPU (Ubuntu 20.04.3 LTS) 上运行 Tensorflow 版本 2.7.0
最佳答案
当您尝试连接标量时会发生这种情况,这是不受支持的。 Tensorflow 在 eager 模式下不会引发错误,这显然是一个错误。 suggestion而是使用tf.stack
:
import tensorflow as tf
with tf.GradientTape() as tape:
t = tf.Variable([1.])
result = t + t
grads = tape.gradient(result, t)
tf.print(grads)
with tf.GradientTape() as tape:
t = tf.Variable([1.])
stack = tf.stack(values=[t[0], t[0]], axis=0)
concat_sum = tf.reduce_sum(stack)
grads = tape.gradient(concat_sum, t)
tf.print(grads)
[2]
[2]
关于python - Tensorflow:张量的单个元素连接期间出现 ZeroDivisionError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70190336/