Placeholder in Python
Placeholder指占位符,允许用户先不传入数据,在之后必要时再传入。
Python 的打印字符串时经常用到占位符:
- 比如用
.format
做占位符:
msg = "{0} models trained in {1}s".format
print(msg(5, 60))
它允许我们先用大括号占位,待获取参数后再传入;并且它定义了一种字符串的格式,可以重复利用,只需要传入不同的参数。
- 也可以用
%
占位:
msg = "%s models trained in %s s" % (5, 60)
Tensorflow 中的占位符
Tensorflow 通过 computational graph 进行前向传播以及反向传播计算梯度。在TF1代,通常用tf.Variable
存储可训练参数;用tf.placeholder
存放训练数据。为什么要在computational graph中引入占位符?因为它允许在创建computational graph时不必立刻传入数据,而在训练网络时再传入。占位符的另外一个好处是,不必在computational graph中创建大量的常量节点,提高计算效率。如果为每个batch的数据都创建一个常量节点,那么computational graph将会变得非常庞大。通过 tf.placeholder
占位则避免了这个问题,新的batch data 到来时,直接填入占位符即可。
A placeholder is a variable in Tensorflow to which data will be assigned sometime later on. It enables us to create processes or operations without the requirement for data. Data is fed into the placeholder as the session starts, and the session is run. We can feed data into tensorflow graphs using placeholders.
在TF2代中,取消了tf.placeholder
,代之以集成度更高的keras.Input
。因此我们可以把keras.Input
看作一个占位符。详见Replacing placeholder for tensorflow v2
实际上,TF2相对于1代的升级远不止于此,比如再也不用写Session.run
了。谷歌在2019年9月才新发布了TF2,其中包括了 Keras的一些高度集成的函数,大大方便了神经网络的搭建。
虽然作为用户,已经在TF中看不到tf.placeholder
的身影了。但广义上的placeholder
在编程时还是会经常用到的。
Tensorflow 与 Pytorch 中的计算图
Tensorflow 的计算图是静态的。比如当我们写 model=Sequential(...)
时,计算图就已经生成了。
而 Pytorch 的计算图是动态生成的。在前向传播的过程中,Pytorch 才逐步生成计算图。