TensorFlow学习笔记3——Placeholders and feed_dict
1. Placeholders
placeholders,顾名思义,就是占位的意思,举个例子:我们定义了一个关于x,y的函数 f(x,y)=2x+y,但是我们并不知道x,y的值,那么x,y就是等待确定的值输入的placeholders。
我们如下定义一个placeholders:
tf.placeholder(dtype, shape=None, name=None)
一个简单的实例如下:
1 a = tf.placeholder(tf.float32, shape=[3]) 2 b = tf.constant([5, 5, 5], tf.float32) 3 c =a + b 4 with tf.Session() as sess: 5 print(sess.run(c, feed_dict={a: [1, 2, 3]}))
输出:
[ 6. 7. 8.]
看到那个 feed_dict 吗?顺理成章,我们接下来聊聊 feed_dict .
2. feed_dict
刚刚上面不是说“x,y就是等待确定的值输入的placeholders”吗?ok,我们就是通过feed_dict输入那个placeholders苦苦等待的确定的值。
再看一个例子:
1 # create Operations, Tensors, etc (using the default graph) 2 a = tf.add(2, 5) 3 b = tf.multiply(a, 3) 4 # start up a `Session` using the default graph 5 sess = tf.Session() 6 # define a dictionary that says to replace the value of `a` with 15 7 replace_dict = {a: 15} 8 # Run the session, passing in `replace_dict` as the value to `feed_dict` 9 sess.run(b, feed_dict=replace_dict) # returns 45