python - 如何喂占位符?

标签 python tensorflow

我正在尝试实现一个简单的前馈网络。但是,我不知道如何提供 Placeholder。这个例子:

import tensorflow as tf

num_input  = 2
num_hidden = 3
num_output = 2

x  = tf.placeholder("float", [num_input, 1])
W_hidden = tf.Variable(tf.zeros([num_hidden, num_input]))
W_out    = tf.Variable(tf.zeros([num_output, num_hidden]))
b_hidden = tf.Variable(tf.zeros([num_hidden]))
b_out    = tf.Variable(tf.zeros([num_output]))

h = tf.nn.softmax(tf.matmul(W_hidden,x) + b_hidden)

sess = tf.Session()

with sess.as_default():
    print h.eval()

给我以下错误:

  ...
    results = self._do_run(target_list, unique_fetch_targets, feed_dict_string)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 419, in _do_run
    e.code)
tensorflow.python.framework.errors.InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder' with dtype float and shape dim { size: 2 } dim { size: 1 }
     [[Node: Placeholder = Placeholder[dtype=DT_FLOAT, shape=[2,1], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
Caused by op u'Placeholder', defined at:
  File "/home/sfalk/workspace/SemEval2016/java/semeval2016-python/slot1_tf.py", line 8, in <module>
    x  = tf.placeholder("float", [num_input, 1])
  ...

我试过了

tf.assign([tf.Variable(1.0), tf.Variable(1.0)], x)
tf.assign([1.0, 1.0], x)

但这显然不起作用。

最佳答案

要提供占位符,请使用 Session.run()(或 Tensor.eval())的 feed_dict 参数。假设您有以下带有占位符的图表:

x = tf.placeholder(tf.float32, shape=[2, 2])
y = tf.constant([[1.0, 1.0], [0.0, 1.0]])
z = tf.matmul(x, y)

如果您想评估 z,您必须为 x 提供一个值。你可以这样做:

sess = tf.Session()
print sess.run(z, feed_dict={x: [[3.0, 4.0], [5.0, 6.0]]})

有关详细信息,请参阅 documentation on feeding .

关于python - 如何喂占位符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33810990/

相关文章:

python - 用于分类的图像转换器

python - 凯拉斯错误 "You must feed a value for placeholder tensor"

python - 缺少标签的深度多任务学习

python - 如何检索 tf.image.decode_jpeg 返回的图像张量的高度和高度?

python - 使用 py.test 的项目

python - 在Python中返回具有给定id的二维列表的行(副本)的最有效(最快)的方法是什么?

python - 如何使用 . 在 python 3.7 中导入 dstk

python - 访问 Pandas 中的组

python - 如何在 Python 3 中使用 unicode 字符作为变量?

python - tensorflow 无效参数错误 : You must feed a value for placeholder tensor with dtype float