1. tf.pad()
函数形式及参数
tf.pad(tensor,paddings, mode='CONSTANT',name=None)
tensor:就是要填充的张量 paddings :代表每一维填充多少行或列 参考:https://blog.csdn.net/qq_40994943/article/details/85331327,https://www.cnblogs.com/chenzhen0530/p/10816149.html mode 可以取三个值,表示三种不同的填充方法,分别是"CONSTANT" ,“REFLECT”,“SYMMETRIC” 1.mode=“CONSTANT” 直接填充0 2.mode="REFLECT"映射填充,上下(第1维)填充顺序和paddings是相反的,左右(第0维)顺序补齐。 3.mode="SYMMETRIC"对称填充,上下(第1维)填充顺序是和paddings相同的,左右(第0维)对称补齐。
以示例进行解释
对一维tensor进行填充:
import tensorflow as tf
t = tf.constant([[1, 2, 3]])
paddings = tf.constant([[1, 2], [3, 4]])
t_padding = tf.pad(t, paddings)
with tf.Session() as sess:
print(sess.run(t_padding))
一维填充的输出结果
[[0 0 0 0 0 0 0 0 0 0]
[0 0 0 1 2 3 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]]
可以看到输出是一个二维矩阵并且在矩阵向上填充1行,向下填充两行,右边填充4行,左边填充3行。是在默认mode=“CONSTANT”下填充的,因此,填充的时0。 对二维tensor进行填充:
import tensorflow as tf
t = tf.constant([[1, 2, 3], [4, 5, 6]])
paddings = tf.constant([[1, 2], [3, 4]])
t_padding = tf.pad(t, paddings)
with tf.Session() as sess:
print(sess.run(t_padding ))
二维填充的输出结果
[[0 0 0 0 0 0 0 0 0 0]
[0 0 0 1 2 3 0 0 0 0]
[0 0 0 4 5 6 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]]
可以看到填充结果与一维填充效果一致,维度没有改变,仍是二维。 对三维tensor进行填充:
import tensorflow as tf
t = tf.constant([[[1, 2, 3], [3, 4, 5]], [[5, 6, 7], [7, 8, 9]]])
paddings = tf.constant([[1, 2], [3, 4], [5, 6]])
t_padding = tf.pad(t, paddings)
with tf.Session() as sess:
print(sess.run(t_padding))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0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0]]
[[0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0]]]
可以看出在第2维上方填充1个二维矩阵,下方填充2个二维矩阵。在第一维上方填充三个一维向量下方填充四个一维向量。在第0维上左边填充5个0右边填充6个0.
mode=REFLECT的效果
import tensorflow as tf
t = tf.constant([[2,3,4],[5,6,7]])
paddings = tf.constant([[1,1],[2,2]])
t_padding = tf.pad(t, paddings, mode="REFLECT")
with tf.Session() as sess:
print(sess.run(t_padding))
结果如下:
[[7, 6, 5, 6, 7, 6, 5],
[4, 3, 2, 3, 4, 3, 2],
[7, 6, 5, 6, 7, 6, 5],
[4, 3, 2, 3, 4, 3, 2]]
mode=SYMMETRIC的效果
import tensorflow as tf
t = tf.constant([[2,3,4],[5,6,7]])
paddings = tf.constant([[1,1],[2,2]])
t_padding = tf.pad(t, paddings, mode="SYMMETRIC")
with tf.Session() as sess:
print(sess.run(t_padding))
结果如下:
[[3, 2, 2, 3, 4, 4, 3],
[3, 2, 2, 3, 4, 4, 3],
[6, 5, 5, 6, 7, 7, 6],
[6, 5, 5, 6, 7, 7, 6]]
|