tensorflow - 使用 tensorflow 2.0 的 GradientTape() 计算梯度的问题
问题描述
使用 tensorflow 2.0 和 GradientTape() 函数,第一个 tape.gradient() 给出正确的梯度张量,但第二个 tape.gradient() 给出“无”。为什么第二个值是“无”?我希望在一秒钟内分别计算出梯度。
import tensorflow as tf
import numpy as np
x = tf.constant([ [1.0, 2.0], [3.0, 4.0], [5.0, 6.0] ])
y0 = tf.constant([ [4.0], [8.0], [12.0] ])
w = tf.Variable( [[1.0], [1.0]] )
with tf.GradientTape() as tape:
y = tf.matmul(x, w)
print("y : ", y.numpy())
loss = tf.reduce_sum(y-y0)
print("loss : ", loss.numpy())
grad = tape.gradient(loss, w) # gradient calculation is correct
print("gradient : ", grad.numpy())
mu = 0.01
w = w - mu*grad
with tf.GradientTape() as tape:
y = tf.matmul(x, w)
print("y : ", y.numpy())
loss = tf.reduce_sum(y-y0)
print("loss : ", loss.numpy())
grad = tape.gradient(loss, w) # gradient value go to 'None'
print("gradient : ", grad)
解决方案
您正在通过分配覆盖w
a Tensor
(不是a ) 。默认情况下,仅跟踪变量。你有两个选择。Variable
w = w - mu*grad
GradientTape
- 推荐:替换
w = w - mu*grad
为w.assign(w - mu*grad)
。这保持w
为 aVariable
并且是更新变量值的方式。 - 您可以在
GradientTape
. 在第二个磁带上下文中,tape.watch(w)
在开头添加(在 之前matmul
)。
推荐阅读
- python - 如何判断脚本需要什么版本的 Python?
- c++ - 快速 regex_search/replace,或明确的替换指示?
- django - Django left join(只有两个模型)
- javascript - 如何在淘汰赛js中设置外部模板URL
- javascript - html中的动态下拉
- google-apps-script - 用于复制和重命名文件夹结构的 Google App 脚本,包括更新文件夹中包含的文档和工作表中的字段?
- salesforce - 全日历时间问题
- pandas - 熊猫数据框转换
- javascript - 最小和最大长度的 jQuery 验证不适用于 Bootstrap 4
- docker-compose - 如何使 graylog 4 和 elasticticsearch 7 与 docker compose 一起使用