TensorFlow 中的占位符
占位符是 Tensorflow 中的一个变量,稍后将为其分配数据。它使我们能够在不需要数据的情况下创建流程或操作。会话开始时,数据被输入占位符,会话开始运行。我们可以使用占位符将数据输入到张量流图中。
Syntax: tf.compat.v1.placeholder(dtype, shape=None, name=None)
Parameters:
- dtype: the datatype of the elements in the tensor that will be fed.
- shape : by default None. The tensor’s shape that will be fed , it is an optional parameter. One can feed a tensor of any shape if the shape isn’t specified.
- name: by default None. The operation’s name , optional parameter.
Returns:
A Tensor that can be used to feed a value but cannot be evaluated directly.
示例 1:
Python3
# 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))
Python3
# 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: [20. 30. 40. 50.]
解释:
- 万一出现任何错误,急切模式将被禁用。
- 占位符是使用 tf.placeholder() 方法创建的,该方法具有 dtype 'tf.float32',None 表示我们没有指定任何大小。
- 在输入数据之前创建操作。
- 该操作将 10 添加到张量。
- 使用 tf.Session() 创建和启动会话。
- Session.run 将我们创建的操作和要输入的数据作为参数并返回结果。
示例 2:
Python3
# 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.]]