使用 tensorflow 2.0 和 GradientTape(( 函数,第一个 tape.gradient(( 给出正确的梯度张量,但第二个 tape.gradient(( 给出 'None'。 为什么第二个值是"无"?我希望在一秒钟内分别计算梯度。
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 = w - mu*grad
来覆盖Tensor
(不是Variable
(覆盖w
。默认情况下,GradientTape
仅跟踪变量。您有两种选择。
- 建议:将
w = w - mu*grad
替换为w.assign(w - mu*grad)
。这会将w
保留为Variable
,并且是更新变量值的方法。 - 您可以在
GradientTape
中显式跟踪非变量。在第二个磁带上下文中,在最开头(matmul
之前(添加tape.watch(w)
。