介紹
在二維矩陣的四周填充0
應用場景
在卷積操作中,一般使用 padding='SAME'
填充0,但有時不靈活,我們想自己去進行補零操作,此時可以使用tf.keras.layers.ZeroPadding2D
語法
1 __init__( 2 padding=(1, 1), 3 data_format=None, 4 **kwargs 5 )
參數
-
padding:整數,或者2個整數的元組,或者2個整數的2個元組的元組
-
整數:以上下、左右對稱的方式填充0
例子:1,表示上下各填充一行0,即:行數加2;左右各填充一列0,即:列數加2 -
2個整數的元組:第一個整數表示上下對稱的方式填充0;第二個整數表示左右對稱的方式填充0
例子:(1,1),表示上下各填充一行0,即:行數加2;左右各填充一列0,即:列數加2 -
2個整數的2個元組的元組:表示
((top_pad, bottom_pad), (left_pad, right_pad))
-
-
data_format:字符串, “channels_last” (默認) 或 “channels_first”, 表示輸入中維度的順序。
- channels_last 對應輸入形狀 (batch, height, width, channels)
- channels_first 對應輸入尺寸為 (batch, channels, height, width)。
默認為在 Keras 配置文件 ~/.keras/keras.json 中的 image_data_format 值。 如果你從未設置它,將使用 “channels_last”。
輸入形狀:
4維 tensor :
- 如果 data_format 是 “channels_last”: (batch, rows, cols, channels)
- 如果 data_format 是 “channels_first”: (batch, channels, rows, cols)
輸出形狀:
4維 tensor :
- 如果 data_format 是 “channels_last”: (batch, padded_rows, padded_cols, channels)
- 如果 data_format 是 “channels_first”: (batch, channels, padded_rows, padded_cols)
例子
構建2維矩陣
import numpy as np import tensorflow as tf np.set_printoptions(threshold=np.inf) np.random.seed(1) arr=np.random.randint(1,9,(4,4)) print(arr)
執行結果:
1 [[6 4 5 1] 2 [8 2 4 6] 3 [8 1 1 2] 4 [5 8 6 5]]
例1
傳遞1個整數,填充0:
1 arr=arr.reshape(1,4,4,1) 2 inp=tf.keras.Input((4,4,1)) 3 x=tf.keras.layers.ZeroPadding2D(1)(inp) 4 model=tf.keras.Model(inp,x) 5 res=model(arr) 6 tf.print(tf.squeeze(res))
例2
傳遞2個整數的tuple,填充0:
1 arr=arr.reshape(1,4,4,1) 2 inp=tf.keras.Input((4,4,1)) 3 x=tf.keras.layers.ZeroPadding2D((1,2))(inp) 4 model=tf.keras.Model(inp,x) 5 res=model(arr) 6 print(tf.squeeze(res).numpy())
執行結果:
1 [[0 0 0 0 0 0 0 0] 2 [0 0 6 4 5 1 0 0] 3 [0 0 8 2 4 6 0 0] 4 [0 0 8 1 1 2 0 0] 5 [0 0 5 8 6 5 0 0] 6 [0 0 0 0 0 0 0 0]]
例3
1 arr=arr.reshape(1,4,4,1) 2 inp=tf.keras.Input((4,4,1)) 3 x=tf.keras.layers.ZeroPadding2D(((1,2),(3,4)))(inp) 4 model=tf.keras.Model(inp,x) 5 res=model(arr) 6 print(tf.squeeze(res).numpy())
執行結果:
1 [[0 0 0 0 0 0 0 0 0 0 0] 2 [0 0 0 6 4 5 1 0 0 0 0] 3 [0 0 0 8 2 4 6 0 0 0 0] 4 [0 0 0 8 1 1 2 0 0 0 0] 5 [0 0 0 5 8 6 5 0 0 0 0] 6 [0 0 0 0 0 0 0 0 0 0 0] 7 [0 0 0 0 0 0 0 0 0 0 0]]
原文連接:https://www.malaoshi.top/show_1EF5LMACXvfQ.html