我编写了一个简单的TensorFlow代码。我认为下面的代码应该可以运行。代码的目标很简单,仅仅是计算简单的加法。
import tensorflow as tfimport numpy as npdata = np.array([[35.0, 40.0, 45.0]]).astype(np.float32)print np.shape(data)x = tf.placeholder(tf.float32, [1, 3], name='x')y = tf.Variable(x + 5, name='y')model = tf.initialize_all_variables()with tf.Session() as sess: sess.run(model) result = sess.run(y, feed_dict={x: data}) print result
但是,解释器显示了类似这样的错误信息:
Traceback (most recent call last):File "basic_compare.py", line 12, in <module>sess.run(model)File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 717, in runrun_metadata_ptr)File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 915, in _runfeed_dict_string, options, run_metadata)File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 965, in _do_runtarget_list, options, run_metadata)File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 985, in _do_callraise type(e)(node_def, op, message)tensorflow.python.framework.errors.InvalidArgumentError: You must feed a value for placeholder tensor 'x' with dtype float and shape [1,3] [[Node: x = Placeholder[dtype=DT_FLOAT, shape=[1,3], _device="/job:localhost/replica:0/task:0/gpu:0"]()]]Caused by op u'x', defined at:File "basic_compare.py", line 6, in <module>x = tf.placeholder(tf.float32, [1, 3], name='x')File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/array_ops.py", line 1332, in placeholdername=name)File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_array_ops.py", line 1748, in _placeholdername=name)File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/op_def_library.py", line 749, in apply_opop_def=op_def)File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2380, in create_oporiginal_op=self._default_original_op, op_def=op_def)File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1298, in __init__self._traceback = _extract_stack()InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'x' with dtype float and shape [1,3] [[Node: x = Placeholder[dtype=DT_FLOAT, shape=[1,3], _device="/job:localhost/replica:0/task:0/gpu:0"]()]]
我只复制了与错误相关的关键部分。我在这个简单的代码上花了很多时间,但没有发现任何问题。任何建议都会非常感激。
回答:
您将 x
用作变量初始化器,因此在执行 tf.initialize_all_variables()
时需要为 x
提供数据:
import tensorflow as tfimport numpy as npdata = np.array([[35.0, 40.0, 45.0]]).astype(np.float32)print np.shape(data)x = tf.placeholder(tf.float32, [1, 3], name='x')y = tf.Variable(x, name='y')model = tf.initialize_all_variables()with tf.Session() as sess: sess.run(model, feed_dict={x: data}) result = sess.run(y) print result
希望这对您有帮助!