函数中的 tensorflow 占位符

tensorflow placeholder in function

现在,我有一些代码如下:

import tensorflow as tf

x = tf.placeholder(tf.float32, [1, 3])
y = x * 2

with tf.Session() as sess:
    result = sess.run(y, feed_dict={x: [2, 4, 6]})
    print(result)

我想为函数提供值。

下面是一个明显的错误。 我应该怎么做?

import tensorflow as tf

def place_func():
    x = tf.placeholder(tf.float32, [1, 3])
    y = x * 2

with tf.Session() as sess:
    result = sess.run(y, feed_dict={x: [2, 4, 6]})
    print(result)

一个选项是 运行 函数内部的会话,如下所示:

import tensorflow as tf

def my_func(data):
    x = tf.placeholder(tf.float32, [1, 3])
    y = x * 2
    return sess.run(y, feed_dict = {x: data})

with tf.Session() as sess:
    result = my_func([[2, 4, 6]])
    print(result)

您还可以创建一个 class 并让 x 成为该 class 的一个字段。