我使用tensorflow编写了简单的代码。我认为下面的代码应该有效。这段代码的目标很简单。只计算简单的加法。
import tensorflow as tf
import numpy as np
data = 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 run
run_metadata_ptr)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 915, in _run
feed_dict_string, options, run_metadata)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 965, in _do_run
target_list, options, run_metadata)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 985, in _do_call
raise 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 placeholder
name=name)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_array_ops.py", line 1748, in _placeholder
name=name)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/op_def_library.py", line 749, in apply_op
op_def=op_def)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2380, in create_op
original_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"]()]]
我刚刚复制了对错误至关重要的内容。我花了很多时间来处理这个简单的代码,但我没有看到任何问题。任何提示将不胜感激。
答案 0 :(得分:0)
您使用x
作为变量初始值设定项,因此在执行x
时需要提供tf.initialize_all_variables()
:
import tensorflow as tf
import numpy as np
data = 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
希望有所帮助!