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]]]]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 酒阁醉醉醉何人, 龙涎紫烟,萦盏无回时。 红炉梅酒相思处,院深不见来时路。 月白风起仙人暮, 墨染河星,难掩相思怒...
    手握瓷杯阅读 400评论 6 3
  • 你看空中飘落的雪花在风雨的陪伴下若隐若现,像不像我对你的思念? 愿你一切安好,晚安!
    何时再出发阅读 152评论 1 0
  • 早就想去南通水上乐园玩了,好不容易等到暑假,好不容易等到爸爸有空,真的很不容易哦 上火车前来个留影,预祝旅途愉快 ...
    永泰水产阅读 760评论 0 0