TensorFlow 占位符(Placeholder)用法详解与实战示例


发布日期 : 2020-04-17 16:52:06 UTC

访问量: 10 次浏览

Tensorflow中的占位符

占位符是Tensorflow中的一个变量,数据将在以后的某个时候被分配给它。
它使我们能够在没有数据要求的情况下创建流程或操作。
当会话开始时,数据被送入占位符,会话被运行。
我们可以使用占位符将数据送入tensorflow图中。

语法:
tf.compat.v1.placeholder(dtype, shape=None, name=None)

参数:

  • dtype:张量中元素的数据类型,将被输入。
  • shape : 默认为None:将被输入的张量的形状,它是一个可选参数。如果没有指定形状,人们可以输入任何形状的张量。
  • name: 默认为None:操作的名称,可选参数。

返回值:

一个张量,可以用来输入一个值,但不能直接评估。

示例 1:

# importing packages
import tensorflow.compat.v1 as tf

# disabling eager mode
tf.compat.v1.disable_eager_execution()

# creating a placeholder
a = tf.placeholder(tf.float32, None)

# creating an operation
b = a + 10

# creating a session
with tf.Session() as session:

    # feeding data in the placeholder
    operation_res = session.run(b, feed_dict={a: [10, 20, 30, 40]})
    print("after executing the operation: " + str(operation_res))

输出:

after executing the operation: [20. 30. 40. 50.]

解释:

  • 在有任何错误的情况下,急切模式被禁用。
  • 一个占位符是用 tf.placeholder() 方法创建的,它的dtype是’tf.float32’, None表示我们没有指定任何尺寸。
  • 操作是在输入数据之前创建的。
  • 该操作在张量上增加了10。
  • 使用 tf.Session() 创建并启动一个会话。
  • Session.run将我们创建的操作和要输入的数据作为参数,并返回结果。

示例 2:

# importing packages
import tensorflow.compat.v1 as tf

# disabling eager mode
tf.compat.v1.disable_eager_execution()

# creating a tensorflow graph
graph = tf.Graph()
with graph.as_default():

    # creating a placeholder
    a = tf.placeholder(tf.float64, shape=(3, 3), name='tensor1')

    # creating an operation
    b = a ** 2

# array1 will be fed into 'a'
array1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Creating a session, and running the graph
with tf.Session(graph=graph) as session:

    # run the session until it reaches node b,
    # then input an array of values into a
    operation_res = session.run(b, feed_dict={a: array1})
    print("after executing the operation: ")
    print(operation_res)

输出:

after executing the operation:
[[ 1. 4. 9.]
[16. 25. 36.]
[49. 64. 81.]]