在TensorFlow中使用tf.placeholder时获取异常

时间:2019-03-12 07:50:03

标签: python tensorflow

我是Python和TensorFlow的新手。有人可以解释一下为什么我在执行以下简单代码时出现错误-

import tensorflow as tf

#Model parameters
w = tf.Variable([.4], dtype =tf.float32)
b = tf.Variable([-4], dtype = tf.float32)

x = tf.placeholder(tf.float32)

linear_model = w*x +b

sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)

print(sess.run(linear_model))

错误堆栈跟踪为-

_call_tf_sessionrun run_metadata中的文件“ C:\ Users \ Administrator \ AppData \ Roaming \ Python \ Python37 \ site-packages \ tensorflow \ python \ client \ session.py”,行1407)

tensorflow.python.framework.errors_impl.InvalidArgumentError:您必须使用dtype float [[{{node Placeholder}}]]来输入占位符张量“ Placeholder”的值

1 个答案:

答案 0 :(得分:2)

错误是正确的。您要评估linear_model。此时,您必须指定x

import tensorflow as tf

#Model parameters
w = tf.Variable([.4], dtype =tf.float32)
b = tf.Variable([-4], dtype = tf.float32)

x = tf.placeholder(tf.float32)

linear_model = w*x +b

sess = tf.Session()
init = tf.global_variables_initializer()
### This works fine!
sess.run(init)

### Now you have to specify x...
print(sess.run(linear_model, {x: 0}))

这给了

[-4.]