TensorFlow之placeholder

In TensorFlow, there is a special kind of node, both can be regarded as a constant variable can also be seen, it is the placeholder. It is actually a placeholder placeholder placeholder in advance in the drawing, but it does not need to initialization values.

The reason that constants placeholder can be seen both as variables can also be seen, because the data to fill the placeholder, the value in the figure can not be modified to do (i.e., modify the value of the function can not assign the like); however in addition to map and can continue to pass different values. FIG when running, dynamically set the value of the placeholder.

For example, in the training, the need to constantly pass different data (such as images) in the figure, this time you can choose to use placeholder placeholder in advance, and then continue to replace the placeholder data in the training. Of course, TensorFlow there are other more efficient data reading method, only for example herein.

In TensorFlow1, the prototype tf.placeholder function is as follows:

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

The meaning of the parameters described below:

dtype: Data type placeholders.

shape: placeholders Shape, i.e. the length of each dimension.

name: the name of the placeholder.

Write example, assume that we need to implement a matrix multiplication, a matrix wherein a matrix needs to read in the list, and to make another matrix multiplication calculation, as follows:

import tensorflow as tf
tf1 = tf.compat.v1
B = [[1, 1], [1, 1], [1, 1]]
Graph = tf1.Graph()
with Graph.as_default():
    A_tf = tf1.placeholder(dtype=tf.float32, shape=[2, 3], name='A')
    B_tf = tf1.constant(B, dtype=tf.float32, shape=[3, 2], name='B')
    C_tf = tf1.matmul(A_tf, B_tf)
with tf1.Session(graph=Graph) as sess:
    A1 = [[1, 2, 3], [1, 2, 3]]
    A2 = [[4, 5, 6], [4, 5, 6]]
    A_list = [A1, A2]
    for A in A_list:
        C = sess.run(C_tf, feed_dict={A_tf: A})
        print('\n', C)

In line 14, performs matrix multiplication operation, and the value of the placeholder character A_tf by feed_dict parameter. feed_dict is a dictionary object, all the placeholders can be passed through this parameter. After executing the above code, the following output:


 [[6. 6.]
 [6. 6.]]

 [[15. 15.]
 [15. 15.]]

Note: When the execution path contains a placeholder, the placeholder comprising all must pass a specific value, i.e. by the value of the placeholder feed_dict path contains all incoming.

Published 105 original articles · won praise 17 · views 110 000 +

Guess you like

Origin blog.csdn.net/qq_38890412/article/details/104068142