首页 > 解决方案 > 使用 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)

标签: tensorflow

解决方案


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

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

推荐阅读