函數:python
tf.compat.v1.pad
tf.pad
函數表達式以下:dom
tf.pad(
tensor,
paddings,
mode='CONSTANT',
name=None,
constant_values=0
)
函數用途:對各個維度進行填充,paddingide
輸入:函數
padding shape舉個例子:spa
要求:pad 維度爲(n,2) n:爲tensor 的維度個數; code
第一組:orm
input tensor,shape【3,4,5】三維 tensorblog
padding shape:【3,2】input
第二組:it
input tensor,shape【3,4,5,6】四維 tensor
padding shape:【4,2】
padding 的每一維度,都有兩個數,第一個表示前面添加幾維度,第二個表示 後面添加幾維度;
padded 填充以後的每一維度:
The padded size of each dimension D of the output is:
paddings[D, 0] + tensor.dim_size(D) + paddings[D, 1]
if mode == "REFLECT" or mode == "SYMMETRIC":
paddings[D, 0] + paddings[D, 1] <= tensor.dim_size(D) - 1
舉個例子-》填充後的tensor shape:
tensor shape : (3,5,4)
padding = [[1,1],[2,2],[1,0]]
padded shape: (3+1+1,5+2+2,4+1+0)= (5,9,5)
REFLECT:的填充方式使用的是一種經過對稱軸進行對稱複製的方式進行填充(複製時不包括對稱軸,邊界的那一列是對稱軸),經過使用tensor邊緣做爲對稱;
SYMMETRIC:的填充方式於REFLECT填充方式相似,也是按照對稱軸就是複製的,只是它包括對稱軸(邊界外的線是對稱軸)。
舉例一:(來自官方):
1 t = tf.constant([[1, 2, 3], [4, 5, 6]]) #shape(2,3) 2 paddings = tf.constant([[1, 1,], [2, 2]]) # shape(2,2),第一維度,前面補一維度,後面補一維度;第二維度,前面補兩維度,後面補兩維度; 3 # 'constant_values' is 0. 4 # rank of 't' is 2. 5 tf.pad(t, paddings, "CONSTANT") # [[0, 0, 0, 0, 0, 0, 0], 6 # [0, 0, 1, 2, 3, 0, 0], 7 # [0, 0, 4, 5, 6, 0, 0], 8 # [0, 0, 0, 0, 0, 0, 0]] 9 10 tf.pad(t, paddings, "REFLECT") # [[6, 5, 4, 5, 6, 5, 4], 11 # [3, 2, 1, 2, 3, 2, 1], # 黃色爲對稱軸 12 # [6, 5, 4, 5, 6, 5, 4], 13 # [3, 2, 1, 2, 3, 2, 1]] 14 15 tf.pad(t, paddings, "SYMMETRIC") # [[2, 1, 1, 2, 3, 3, 2], 16 # [2, 1, 1, 2, 3, 3, 2], # 17 # [5, 4, 4, 5, 6, 6, 5], 18 # [5, 4, 4, 5, 6, 6, 5]]
舉例二:
import tensorflow as tf import numpy as np m1 = tf.random_normal([1,2,3,4],mean=0.0,stddev=1.0,dtype=tf.float32) m2 = tf.pad(m1,[[2,0],[0,0],[0,0],[0,0]],constant_values = 1) m2_s = tf.shape(m2) # shape(3,2,3,4) with tf.Session() as sess: print(sess.run(m1)) print(sess.run(m2)) print(sess.run(m2_s))
output:
# m1 [[[[-1.8582115 -1.170714 -0.4478178 2.0172668 ] [-0.74805504 -0.08016825 -0.7742696 -0.02516617] [-0.8256318 0.591446 -0.00889379 1.7998788 ]] [[ 0.00565176 -0.31549874 1.5197186 0.07842494] [ 0.00609808 1.9219669 -0.42632174 1.5106113 ] [ 0.67241013 -0.38563538 -0.976289 0.2032768 ]]]] #m2 [[[[ 1. 1. 1. 1. ] [ 1. 1. 1. 1. ] [ 1. 1. 1. 1. ]] [[ 1. 1. 1. 1. ] [ 1. 1. 1. 1. ] [ 1. 1. 1. 1. ]]] [[[ 1. 1. 1. 1. ] [ 1. 1. 1. 1. ] [ 1. 1. 1. 1. ]] [[ 1. 1. 1. 1. ] [ 1. 1. 1. 1. ] [ 1. 1. 1. 1. ]]] [[[-1.2366703 -1.0050759 -0.3843815 1.0201392 ] [-1.3438475 0.8829414 -1.3399163 1.078826 ] [-0.09356844 0.35896888 1.5112561 0.28352356]] [[ 0.45909956 -0.23824279 -0.31440428 1.1913226 ] [-0.40780786 0.58995795 -0.9147027 0.05860058] [-0.0659609 1.4536899 -0.12121342 -0.9752257 ]]]] #output shape [3 2 3 4]