tf.pad用法

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

Args:

  • tensor: A Tensor.
  • paddings: A Tensor of type int32.
  • mode: One of "CONSTANT", "REFLECT", or "SYMMETRIC" (case-insensitive)
  • name: A name for the operation (optional).
  • constant_values: In "CONSTANT" mode, the scalar pad value to use. Must be same type as tensor.

Returns:

A Tensor. Has the same type as tensor.

Raises:

ValueError: When mode is not one of "CONSTANT", "REFLECT", or "SYMMETRIC".

作用

Pads a tensor.
This operation pads a tensor according to the paddings you specify. paddings is an integer tensor with shape [n, 2], where n is the rank of tensor. For each dimension D of input, paddings[D, 0] indicates how many values to add before the contents of tensor in that dimension, and paddings[D, 1] indicates how many values to add after the contents of tensor in that dimension. If mode is "REFLECT" then both paddings[D, 0] and paddings[D, 1] must be no greater than tensor.dim_size(D) - 1. If mode is "SYMMETRIC" then both paddings[D, 0] and paddings[D, 1] must be no greater than tensor.dim_size(D).
The padded size of each dimension D of the output is:
paddings[D, 0] + tensor.dim_size(D) + paddings[D, 1]

例子

import tensorflow as tf

# 可以看到张量有四个维度。
x=tf.Variable([[[[1,1],
                 [2,2]],
               [[3,3],
                [4,4]]]],tf.float32)

# tf.pad的每一个[a,b]的矩阵中,a表示在相应维前面加a层值,b表示在相应维后面加b层值。
x=tf.pad(x,[[1,0],[1,0],[1,0],[1,0]])
'''
即,第一个[1,0]表示在张量x的第一维前面添1个值,得到:
[[[[0,1,1],
   [0,2,2]],
  [[0,3,3],
   [0,4,4]]]]
第二个[1,0]表示在第二维前面添1层值,得到:
[[[[0,0,0],
   [0,1,1],
   [0,2,2]],
  [[0,0,0],
   [0,3,3],
   [0,4,4]]]]
第三个[1,0]表示在第三维前面添1层值,得到:
[[[[0,0,0],
   [0,0,0],
   [0,0,0]]
   [[0,0,0],
   [0,1,1],
   [0,2,2]],
  [[0,0,0],
   [0,3,3],
   [0,4,4]]]]
第四个[1,0]表示在第四维前面添1层值,得到:
[[[[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,1],
   [0,2,2]],
  [[0,0,0],
   [0,3,3],
   [0,4,4]]]]
'''

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(x))
# 输出
[[[[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 1]
   [0 2 2]]
  [[0 0 0]
   [0 3 3]
   [0 4 4]]]]

你可能感兴趣的:(tf.pad用法)