python

Python中tf.placeholder函数怎么使用

小亿
99
2023-12-23 16:33:18
栏目: 编程语言

在Python中,tf.placeholder函数用于定义一个可占位的tensor,可以在TensorFlow的计算图中作为输入节点。当执行计算图时,可以通过传入具体的值来填充这个占位符。

tf.placeholder函数的用法如下:

tf.placeholder(
    dtype,
    shape=None,
    name=None
)

参数说明:

示例代码:

import tensorflow as tf

# 定义一个占位符
x = tf.placeholder(dtype=tf.float32, shape=(None, 2), name='input')

# 创建一个计算图
y = tf.reduce_sum(x, axis=1)

# 创建一个会话
with tf.Session() as sess:
    # 使用feed_dict参数传入具体的值来填充占位符
    result = sess.run(y, feed_dict={x: [[1, 2], [3, 4], [5, 6]]})
    print(result)  # 输出[3.  7. 11.]

在上述代码中,首先通过tf.placeholder定义了一个占位符x,数据类型为tf.float32,形状为(None, 2),表示可以接受任意行、2列的输入。然后,在计算图中使用了这个占位符x,通过tf.reduce_sumx的第二个维度进行求和操作。最后,在会话中使用sess.run执行计算图时,通过feed_dict参数将具体的值[[1, 2], [3, 4], [5, 6]]传入占位符x,计算得到结果[3. 7. 11.]

0
看了该问题的人还看了