python - GradientTape : LookupError: No gradient defined for operation 'IteratorGetNext' (op type: IteratorGetNext) 中的简单 Keras 网络

标签 python tensorflow keras gradient tensorflow2.0

我构建了一个非常简单的 TensorFlow Keras 模型,只有一个密集层。它在 GradientTape 外面工作得很好块,但在 GradientTape 内阻止它引发 LookupError: No gradient defined for operation 'IteratorGetNext' (op type: IteratorGetNext)
重现代码:

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import tensorflow as tf
import numpy as np

print(tf.__version__)

model = Sequential()
model.add(Dense(1, input_shape=(16,)))

fake_data = np.random.random((1, 16))

print(model.predict(fake_data).shape) # works
with tf.GradientTape() as tape:
    print(model.predict(fake_data).shape) # LookupError: No gradient defined for operation 'IteratorGetNext' (op type: IteratorGetNext)

这似乎在 TensorFlow 2.0.0 中有效,但在 TensorFlow 2.1.0 和 2.2.0 中失败

Here是一个复制问题的笔记本。

最佳答案

尝试以这种方式重新定义 GradientTape 中的预测操作

with tf.GradientTape() as tape:
    print(model(fake_data).shape)

关于python - GradientTape : LookupError: No gradient defined for operation 'IteratorGetNext' (op type: IteratorGetNext) 中的简单 Keras 网络,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61923379/

相关文章:

tensorflow - 访问神经网络权重和神经元激活

python - LSTM 不会过度拟合训练数据

python - 从 python 3.6 上的 tensorflow 切换到 python 3.5

python - 我如何知道在 tf.keras 中实现了哪个版本的 Keras API?

python - Keras my_layer.output 返回 KerasTensor 对象而不是 Tensor 对象(在自定义损失函数中)

python - 将 x 和 y 抖动添加到 seaborn 线性图中是否会改变拟合值?

python - MySQLdb._exceptions.ProgrammingError

python - OpenMDAO 内部记录器效率低?

python - 使用 Google 的自定义搜索 JSON API 的搜索结果不一致

python - Tensorflow Hub 和 JS : how to fine-tune a pre-trained model and export it for using in Tensorflow. js?