Python `gradient'在构建TensorFlow图时提供AttributeError

Python `gradient'在构建TensorFlow图时提供AttributeError,python,tensorflow,Python,Tensorflow,我试图学习如何在TensorFlow中构建一个图,但却陷入了一个看似琐碎的操作中。这就是我所拥有的 import tensorflow as tf def loss(x, y): tf.reduce_mean(tf.square(x - y)) xx = tf.random_normal([]) noise = tf.random_normal([]) yy = 3 * xx + 2 + noise W = tf.get_variable("W", []) W.assign(5) b = t

我试图学习如何在TensorFlow中构建一个图,但却陷入了一个看似琐碎的操作中。这就是我所拥有的

import tensorflow as tf
def loss(x, y):
  tf.reduce_mean(tf.square(x - y))
xx = tf.random_normal([])
noise = tf.random_normal([])
yy = 3 * xx + 2 + noise
W = tf.get_variable("W", [])
W.assign(5)
b = tf.get_variable("b", [])
b.assign(0)
with tf.GradientTape() as t:
  current_loss = loss(W*xx+b, yy)
dW = t.gradient(current_loss, W)
在这一点上,我得到了一个AttributeError,如下所示

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-7-26d05a240ccc> in <module>()
      1 with tf.GradientTape() as t:
      2   current_loss = loss(W*xx+b, yy)
----> 3 dW = t.gradient(current_loss, W)

/usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/backprop.py in gradient(self, target, sources, output_gradients, unconnected_gradients)
    944         flat_sources,
    945         output_gradients=output_gradients,
--> 946         unconnected_gradients=unconnected_gradients)
    947 
    948     if not self._persistent:

/usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/imperative_grad.py in imperative_grad(tape, target, sources, output_gradients, unconnected_gradients)
     70       sources,
     71       output_gradients,
---> 72       compat.as_str(unconnected_gradients.value))

AttributeError: 'NoneType' object has no attribute '_id'
---------------------------------------------------------------------------
AttributeError回溯(最近一次呼叫上次)
在()
1,tf.GradientTape()为t:
2电流损耗=损耗(W*xx+b,yy)
---->3 dW=t.梯度(电流损耗,W)
/渐变中的usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/backprop.py(自、目标、源、输出渐变、未连接渐变)
944个平面光源,
945输出梯度=输出梯度,
-->946未连接的_渐变=未连接的_渐变)
947
948如果不是自己的话:
/命令梯度中的usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/祈使梯度.py(磁带、目标、源、输出梯度、未连接梯度)
70个来源,
71输出_梯度,
--->72协调as_str(未连接的梯度值))
AttributeError:“非类型”对象没有属性“\u id”

我做错了什么?如何得到梯度?提前感谢。

如果您不想使用即时执行,则需要稍微修改上面的代码。当您想在非紧急执行模式下使用TensorFlow时,需要有两个主要部分:

  • 构建图表
  • 运行图表
  • 因此,我按照以下逻辑重新编写了上面的示例:

    import tensorflow as tf
    import numpy as np
    
    # Building the graph
    xx = tf.constant(np.random.normal(loc=0.0, scale=1.0))
    noise = tf.constant(np.random.normal(loc=0.0, scale=1.0))
    yy = 3 * xx + 2 + noise
    
    W = tf.Variable(5.0, name="W")
    b = tf.Variable(0.0, name="b")
    
    current_loss = tf.reduce_mean(tf.square(tf.scalar_mul(W,xx)+b - yy))
    dW = tf.gradients(current_loss, W, name='dW')[0]
    
    # Initialisation operation
    init = tf.global_variables_initializer()
    
    # Creating a session and running the graph
    with tf.Session() as sess:
        sess.run(init)
    
        dW_np = sess.run(dW)
    
    print(dW_np)
    
    您的
    loss()
    函数不会返回任何内容。这就是为什么您有
    属性错误
    (因为
    当前损失
    )。您应该添加
    return
    语句


    关于你对上一个答案的评论
    GradientTape
    用于紧急执行,因此您应该在程序开始时添加
    tf。启用紧急执行()。如果你想在图形模式下构建,你应该使用
    tf.gradients()
    tf.train.Optimizer
    子类的
    compute\u gradients()
    方法(例如
    tf.train.GradientDescentOptimizer
    )。

    我知道这是可行的。但本练习的目的是在不急于执行的情况下构建一个图,并从中构建自定义NN层。我不知道是什么原因导致了上述错误以及如何避免。对不起,我误解了你的问题!我将更新我的答案。我不应该在急切执行模式之外使用
    GradientTape
    ?我没有发现任何文档提到这一点。如果您查看回溯,您将看到它是在eager模块中定义的:
    /usr/local/lib/python3.6/dist packages/tensorflow/python/eager/backprop.py
    。另见答案。