如何使用GradientDescentOptimizer?

时间:2017-12-11 06:36:06

标签: optimization tensorflow

#!/usr/bin/env python
# vim: set noexpandtab tabstop=2 shiftwidth=2 softtabstop=-1 fileencoding=utf-8:

import tensorflow as tf

x = tf.placeholder(dtype=tf.float32, shape=[2])
loss = tf.reduce_sum(tf.square(x))
train_op = tf.train.GradientDescentOptimizer(0.01).minimize(loss)

init = tf.global_variables_initializer()

with tf.Session() as sess:
    session.run(init)
    for i in range(10):
        sess.run(train_op)
        print x.eval(), loss.eval()

我有上面的代码。当我运行它时,我得到以下错误。我想优化x。我不明白为什么它说没有要优化的变量。任何人都可以帮我理解错误以及如何正确使用GradientDescentOptimizer吗?感谢。

$ ./main.py
Traceback (most recent call last):
  File "./main.py", line 8, in <module>
    train_op = tf.train.GradientDescentOptimizer(0.01).minimize(loss)
  File "/usr/local/lib/python2.7/site-packages/tensorflow/python/training/optimizer.py", line 343, in minimize
    grad_loss=grad_loss)
  File "/usr/local/lib/python2.7/site-packages/tensorflow/python/training/optimizer.py", line 408, in compute_gradients
    raise ValueError("No variables to optimize.")
ValueError: No variables to optimize.

1 个答案:

答案 0 :(得分:0)

正如错误中所述,您没有定义任何将在模型中训练时训练的变量,x只是一个占位符。