tf.placeholder、feed_dict用法说明

函数形式:

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

参数:
dtype:数据类型。常用的是tf.float32,tf.float64等数值类型
shape:数据形状。默认是None,就是一维值,也可以是多维(比如[2,3], [None, 3]表示列是3,行不定)
name:名称


为什么要用placeholder?


       Tensorflow的设计理念称之为计算流图,在编写程序时,首先构筑整个系统的graph,代码并不会直接生效,这一点和python的其他数值计算库(如Numpy等)不同,graph为静态的,类似于docker中的镜像。然后,在实际的运行时,启动一个session,程序才会真正的运行。这样做的好处就是:避免反复地切换底层程序实际运行的上下文,tensorflow帮你优化整个系统的代码。我们知道,很多python程序的底层为C语言或者其他语言,执行一行脚本,就要切换一次,是有成本的,tensorflow通过计算流图的方式,帮你优化整个session需要执行的代码,还是很有优势的。

       所以placeholder()函数是在神经网络构建graph的时候在模型中的占位,此时并没有把要输入的数据传入模型,它只会分配必要的内存。等建立session,在会话中,运行模型的时候通过feed_dict()函数向占位符喂入数据。

       placeholder有点像在定义函数的时候用到的参数。我们在写函数内部代码的时候,虽然用到了参数,但并不知道参数所代表的值。只有在调用函数的时候,我们才把具体的值传递给参数。

代码示例:
 

import tensorflow as tf
import numpy as np
 
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
 
output = tf.multiply(input1, input2)
 
with tf.Session() as sess:
    print sess.run(output, feed_dict = {input1:[3.], input2: [4.]})
 
import tensorflow as tf
import numpy as np
 
x = tf.placeholder(tf.float32, shape=(1024, 1024))
y = tf.matmul(x, x)
 
with tf.Session() as sess:
    #print(sess.run(y))  # ERROR:此处x还没有赋值
    rand_array = np.random.rand(1024, 1024)
    print(sess.run(y, feed_dict={x: rand_array})) 

 

feed_dict

刚学tensorflow的时候,以为feed_dict是和placeholder配对使用的。比如下面的代码,说明了feed_dict的基本用法:

import tensorflow as tf

a = tf.placeholder(dtype=tf.float32)
b = tf.placeholder(dtype=tf.float32)
c = tf.add(a, b)

with tf.Session() as sess:
    print sess.run(c, feed_dict = {a: 1.0, b: 2.0})

OK, 其实feed_dict可以喂东西给其他tensor,不止placeholder这一种。例如,下面的代码:

import tensorflow as tf

a = tf.placeholder(dtype=tf.float32)
b = tf.constant(2.0)
c = tf.add(a, b)

with tf.Session() as sess:
    print sess.run(c, feed_dict = {a: 1.0, b: 3.0})

运行的结果为4,这里利用feed_dict将3.0送给了tensor b。
总结一下,知道了这种原理,对于模型恢复的理解很有帮助。机器学习系统伴随着tensor的流动(tensorflow的寓意即为此,神经网络等等,其实就是tensor的线性变换和非线性激活),也许,我们只拿到了中间的tensor。举例而言,你在做图片分类的工作,训练过程中,graph的placeholder为任意size的像素矩阵,但当你恢复模型的时候,已经有预处理完的图片像素tensor,这时就可以直接将其导入对应的tensor中即可,前提是知道对应的tensor的name或者符号,此时或许需要用到tf.get_tensor_by_name这个函数。feed_dict的灵活运用,也能反映出对graph思想理解。

------------------------------------------ 
原文:

https://blog.csdn.net/kdongyi/article/details/82343712 

https://www.jianshu.com/p/ec261a65e3c9

猜你喜欢

转载自blog.csdn.net/lcczzu/article/details/91416211