如何养活本地占位符?

时间:2018-06-24 02:17:44

标签: tensorflow placeholder local-variables

我想提供一个在函数中定义的占位符。以下是一个简化的示例。

#!/usr/bin/python

import tensorflow as tf

def CreateInference():
    x2 = tf.placeholder(tf.float32, (None))
    w2 = tf.get_variable('w2', initializer=1.0)
    b2 = tf.get_variable('b2', initializer=2.0)
    y2 = w2 * x2 + b2

y2 = CreateInference()

writer = tf.summary.FileWriter('./graphs', tf.get_default_graph())
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
#    print (sess.run(y2, feed_dict={x2:2.0}))

writer.close()

该图已正确创建,如以下Tensorboard图所示。

enter image description here

问题是feed_dict={x2:2.0}不起作用,因为x2是在函数CreateInference中使用的局部变量。有人可以告诉我在上面的示例中如何访问和提供变量x2的值吗?

1 个答案:

答案 0 :(得分:1)

为什么不做明显的对象并返回对象的引用

#!/usr/bin/python

import tensorflow as tf

def CreateInference():
    x2 = tf.placeholder(tf.float32, (None))
    w2 = tf.get_variable('w2', initializer=1.0)
    b2 = tf.get_variable('b2', initializer=2.0)
    y2 = w2 * x2 + b2
    return x2, y2

x2, y2 = CreateInference()

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print (sess.run(y2, feed_dict={x2:2.0}))