【发布时间】:2019-10-28 12:16:48
【问题描述】:
假设我们有一个使用 BatchNormalization 的简单 Keras 模型:
model = tf.keras.Sequential([
tf.keras.layers.InputLayer(input_shape=(1,)),
tf.keras.layers.BatchNormalization()
])
如何在 GradientTape 中实际使用它?以下似乎不起作用,因为它不更新移动平均线?
# model training... we want the output values to be close to 150
for i in range(1000):
x = np.random.randint(100, 110, 10).astype(np.float32)
with tf.GradientTape() as tape:
y = model(np.expand_dims(x, axis=1))
loss = tf.reduce_mean(tf.square(y - 150))
grads = tape.gradient(loss, model.variables)
opt.apply_gradients(zip(grads, model.variables))
特别是,如果您检查移动平均线,它们保持不变(检查 model.variables,平均值始终为 0 和 1)。我知道可以使用 .fit() 和 .predict(),但我想使用 GradientTape,但我不知道该怎么做。某些版本的文档建议更新 update_ops,但这似乎不适用于 Eager 模式。
特别是,以下代码在经过上述训练后不会输出任何接近 150 的值。
x = np.random.randint(200, 210, 100).astype(np.float32)
print(model(np.expand_dims(x, axis=1)))
【问题讨论】:
-
查看答案更新
-
我同意你的看法(关于培训与评估的评论),这就是 .fit() 似乎有效的原因?知道如何让它在我的设置中工作吗?
标签: python tensorflow keras batch-normalization gradienttape