使用 AdamOptimizer 时出现未初始化值错误

Uninitialized Value Error when using AdamOptimizer

我试图在 Tensorflow 中构建一个简约的梯度计算示例。但是我总是收到 FailedPreconditionError 错误。这是我正在做的事情:

sess = tf.Session()  
x1 = tf.placeholder(tf.float32, [None, 1], name="x1")  
x2 = tf.placeholder(tf.float32, [None, 1], name="x2")  
grad_a1_ph = tf.placeholder(tf.float32, [1], name="grad_a1_ph")  
a1 = tf.Variable(tf.ones([1]), name="a1")  
a2 = tf.Variable(tf.ones([1]), name="a2")  
sess.run(tf.global_variables_initializer())  
adam = tf.train.AdamOptimizer(learning_rate=0.01)
w = a1**2*x1**2 + a2**2*x2**2

所以我试图将函数 w(x1, x2) 最小化,它只是 a1、a2、x1 和 x2 中的二次函数,因此即 a1=0 应该给出最小值。

grad_a1 = adam.compute_gradients(loss=w, var_list=[a1])

我可以计算 dw/da1 在 x1 = 2, x2 = 1

x1_np = 2 * np.ones([1]).reshape(1, 1)
x2_np = 1 * np.ones([1]).reshape(1, 1)
grad_a1_buffer = sess.run(grad_a1, feed_dict={x1:x1_np, x2:x2_np})

它给出了预期的结果 8。
现在我尝试应用我刚刚使用以下代码计算的梯度:

updateGrads = adam.apply_gradients(zip([grad_a1_ph],[a1]))
sess.run(updateGrads, feed_dict={grad_a1_ph:grad_a1_buffer[0][0]})

我在 FailedPreconditionError 上的 sess.run():

ailedPreconditionError: Attempting to use uninitialized value beta1_power
 [[Node: beta1_power/read = Identity[T=DT_FLOAT, _class=["loc:@a1"], _device="/job:localhost/replica:0/task:0/gpu:0"](beta1_power)]]

变量 a1 肯定已初始化,因为如果我提供 x1 和 x2 的值,我计算 w 或 dw/da1 没有任何问题。
如果有人指出我的示例可能有什么问题,那将是一个很大的帮助。

非常感谢
马丁

您需要致电

sess.run(tf.global_variables_initializer())

之后(不是之前)

adam = tf.train.AdamOptimizer(learning_rate=0.01)

或任何其他创建变量的操作。