【问题标题】:problem to calculate gradient using GradientTape() of tensorflow 2.0使用 tensorflow 2.0 的 GradientTape() 计算梯度的问题
【发布时间】:2019-09-05 15:58:15
【问题描述】:

使用 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)

【问题讨论】:

    标签: tensorflow


    【解决方案1】:

    通过分配w = w - mu*grad,您正在用Tensor不是Variable)覆盖w。默认情况下,GradientTape 仅跟踪变量。你有两个选择。

    1. 推荐:将w = w - mu*grad 替换为w.assign(w - mu*grad)。这会将w 保留为Variable,并且是更新变量值的方法。
    2. 您可以在GradientTape 中显式跟踪非变量。在第二个磁带上下文中,在开头添加tape.watch(w)matmul 之前)。

    【讨论】:

      猜你喜欢
      • 2020-09-19
      • 1970-01-01
      • 2019-11-16
      • 2020-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-16
      相关资源
      最近更新 更多