目录
系列文章目录
第一章:pad函数在tf和pytorch中的区别
前言
一、pad是什么?
二、tensorflow 中的pad函数
1.tensorflow1.x中的pad函数
2.tensorflow2.x中的pad函数
三、pytorch 中的pad函数
总结
第一章 pad函数在tf和pytorch中的区别
tensorflow和Pytorch是目前为止深度学习相关的两大主流框架之一,我们避免不了要经常将两者代码相互转换,文本是记录两者pad函数之间的异同点,以供参考,写得不对的地方还望批评指正。
深度学习中最常用的操作是卷积(现在又提出啥MLP效果好于卷积的这些卷出天际的东西不在此讨论范围之内),卷积往往意味着feature map的变小,pad操作是在feature map周围做出填充,使得feature map保持更多的信息。
tf1.15官网连接
tf.pad函数主要是用来对tensor的大小进行扩展,包括水平、垂直、深度(通道)等。
pad(tensor, paddings, mode="CONSTANT", name=None, constant_values=0)
pad填充的例子如下所示:
t = tf.constant([[1, 2, 3], [4, 5, 6]])
paddings = tf.constant([[1, 1,], [2, 2]])
# 'constant_values' is 0.
# rank of 't' is 2.
tf.pad(t, paddings, "CONSTANT") # [[0, 0, 0, 0, 0, 0, 0],
# [0, 0, 1, 2, 3, 0, 0],
# [0, 0, 4, 5, 6, 0, 0],
# [0, 0, 0, 0, 0, 0, 0]]
tf.pad(t, paddings, "REFLECT") # [[6, 5, 4, 5, 6, 5, 4],
# [3, 2, 1, 2, 3, 2, 1],
# [6, 5, 4, 5, 6, 5, 4],
# [3, 2, 1, 2, 3, 2, 1]]
tf.pad(t, paddings, "SYMMETRIC") # [[2, 1, 1, 2, 3, 3, 2],
# [2, 1, 1, 2, 3, 3, 2],
# [5, 4, 4, 5, 6, 6, 5],
# [5, 4, 4, 5, 6, 6, 5]]
含义比较清楚,这里不多废话,直接说重点,一句话概括,tf的pad函数能够对tensor的所有维度进行填充操作,也就是说输入的tensor假设是[NCHW]的维度,经过pad后四个维度都有可能改变;
主要功能和tensorflow1.x中一样,这里不再累述。
按照国际惯例,照例放出pytorch 的pad函数的解释:
pytorch pad函数
See torch.nn.ConstantPad2d
, torch.nn.ReflectionPad2d
, and torch.nn.ReplicationPad2d
for concrete examples on how each of the padding modes works. Constant padding is implemented for arbitrary dimensions. Replicate padding is implemented for padding the last 3 dimensions of 5D input tensor, or the last 2 dimensions of 4D input tensor, or the last dimension of 3D input tensor. Reflect padding is only implemented for padding the last 2 dimensions of 4D input tensor, or the last dimension of 3D input tensor.
请看上述文字中标红的部分,pytorch中只用constant 模式能够对所有维度进行操作,而其余模式只能操作有限维度的tensor
pytorch pad函数跟tf中的pad函数在constant模式下基本是一样的,但是在其他模式下,pytorch pad功能弱于tensorflow pad函数,某些情况下pytorch需要通过numpy或者pytorch的concatenate操作来达到tensorflow相同的功能。