tf.pad原理和用法

 tf.pad(tensor, paddings, mode="CONSTANT", name=None, constant_values=0): 

tensor:就是输入,paddings,就是需要扩张的维度,后面其他的参数的可以不管

tf.pad()就是扩充维度,比如

t=tf.constant([1,2,3])

这是一个一维向量,可以通过print(t.get_shape())看维度

先介绍一个概念,paddings=[a,b,c,d],分别从不同维度加0,

因为是一维向量,所以tf.pad(t,[[1,1]])只能从左右加0输出结果为[[0 1 2 3 0]],

t=tf.constant([[1,2,3]])时,则是一个二维矩阵,就加了一个[],shape=(1,3)

如果a=[1,1],b=[2,2],则上下加一排0,左右加2排0,结果为

[[0 0 0 0 0 0 0]
 [0 0 1 2 3 0 0]

 [0 0 0 0 0 0 0]]

在二维上面加0,当c=[1,1],t=tf.constant([[[1,2,3], [2,3,4],[2,1,4]],
                                                               [[1,2,3], [2,3,4],[2,1,4]],

                                                               [[1,2,3],  [2,3,4],[2,1,4]]])

扫描二维码关注公众号,回复: 1859597 查看本文章

时,即paddings=[[1,1],[2,2],[1,1]]输出为下面所示,shape=(3,3,3)变成了(5,7,5)

完整代码

import tensorflow as tf

t=tf.constant([[[1,2,3], [2,3,4],[2,1,4]],
               [[1,2,3], [2,3,4],[2,1,4]],
               [[1,2,3],  [2,3,4],[2,1,4]]])
t2=tf.constant([[1,2,3]])
print(t.get_shape)
print(t2.get_shape())

a=tf.pad(t,[[1,1], [2,2],[1,1]])
c=tf.pad(t2,[[1,1],[2,2]])

with tf.Session() as sess:
    a,c=sess.run([a,c])
    print(a)
    print(a.shape)
    print(c)


[[[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 1 2 3 0]
  [0 2 3 4 0]
  [0 2 1 4 0]
  [0 0 0 0 0]
  [0 0 0 0 0]]


 [[0 0 0 0 0]
  [0 0 0 0 0]
  [0 1 2 3 0]
  [0 2 3 4 0]
  [0 2 1 4 0]
  [0 0 0 0 0]
  [0 0 0 0 0]]


 [[0 0 0 0 0]
  [0 0 0 0 0]
  [0 1 2 3 0]
  [0 2 3 4 0]
  [0 2 1 4 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]]]


猜你喜欢

转载自blog.csdn.net/qwe2508/article/details/79725701