python - Tensorflow:张量的单个元素连接期间出现 ZeroDivisionError

标签 python tensorflow tensor tensorflow2.x

我目前正在用 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/

相关文章:

android - 需要 Tensorflow 建议

tensorflow - 使用 tf.data.TFRecordDataset 读取 TF2 摘要文件

anaconda - 无法使用 conda 安装依赖项

python-3.x - 如何构建一个与 autograd 兼容的 Pytorch 模块,可以像图像一样调整张量的大小?

python - Python 中有没有一种方法可以检查 os.environ 的条目是变量还是 shell 函数?

python - 为每行生成特定数量的 1,但仅限于 x = 0 的情况

python - 如何提高Python脚本的内存效率

python - "freeze" tensorflow 中的一些变量/范围 : stop_gradient vs passing variables to minimize

python - 使用嵌套循环时索引 i 超出数组范围

python - TensorFlow:如何在急切执行期间将 DeferredTensor 转换为 Tensor(以执行组标准化)?