Computational graph & Placeholder

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 才逐步生成计算图。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值