【问题标题】:tensorflow placeholder in function函数中的张量流占位符
【发布时间】:2023-03-13 00:20:02
【问题描述】:

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

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)

【问题讨论】:

    标签: python tensorflow placeholder


    【解决方案1】:

    一种选择是在函数内部运行会话,如下所示:

    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)
    

    您也可以创建一个类,并让 x 成为该类的一个字段。

    【讨论】:

    • 为什么将“数据”输入占位符而不直接用于计算“y”?我们不能只说 y = data * 2 吗?我注意到对 tensorflow 函数的输入数据使用占位符。但我不知道这背后的原因是什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-23
    • 2017-12-01
    • 2017-10-01
    • 2020-02-07
    • 2018-02-01
    • 1970-01-01
    相关资源
    最近更新 更多