占位符比变量更基本。它只是我们在未来时间分配数据的变量。占位符是在执行时才输入值的节点。如果我们的网络输入依赖于一些外部数据,并且我们不希望我们的图在定义开发时依赖于任何实际值,那么占位符就是我们需要的数据类型。事实上,我们可以在没有任何数据的情况下构建图。因此,占位符不需要任何初始值;只有一个数据类型(例如 float32)和一个张量形状,因此即使它还没有任何存储值,图形仍然知道要计算什么。
创建占位符的一些示例如下:
- a = tf.placeholder(tf.float32, shape=[5])
- b = tf.placeholder(dtype=tf.float32, shape=None, name=None)
- X = tf.placeholder(tf.float32, shape=[None, 784], name='input')
- Y = tf.placeholder(tf.float32, shape=[None, 10], name='label')
-
- # 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.]
Explanation:
- # 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.]]