MaxPooling2D
類別tf_keras.layers.MaxPooling2D(
pool_size=(2, 2), strides=None, padding="valid", data_format=None, **kwargs
)
用於 2D 空間資料的最大池化操作。
通過針對輸入的每個通道,取輸入視窗(大小由 pool_size
定義)中的最大值,來沿其空間維度(高度和寬度)對輸入進行下採樣。視窗沿每個維度移動 strides
的距離。
當使用 "valid"
填充選項時,得到的輸出空間形狀(行數或列數)為:output_shape = math.floor((input_shape - pool_size) / strides) + 1
(當 input_shape >= pool_size
時)
當使用 "same"
填充選項時,得到的輸出形狀為:output_shape = math.floor((input_shape - 1) / strides) + 1
例如,當 strides=(1, 1)
且 padding="valid"
時
>>> x = tf.constant([[1., 2., 3.],
... [4., 5., 6.],
... [7., 8., 9.]])
>>> x = tf.reshape(x, [1, 3, 3, 1])
>>> max_pool_2d = tf.keras.layers.MaxPooling2D(pool_size=(2, 2),
... strides=(1, 1), padding='valid')
>>> max_pool_2d(x)
<tf.Tensor: shape=(1, 2, 2, 1), dtype=float32, numpy=
array([[[[5.],
[6.]],
[[8.],
[9.]]]], dtype=float32)>
例如,當 strides=(2, 2)
且 padding="valid"
時
>>> x = tf.constant([[1., 2., 3., 4.],
... [5., 6., 7., 8.],
... [9., 10., 11., 12.]])
>>> x = tf.reshape(x, [1, 3, 4, 1])
>>> max_pool_2d = tf.keras.layers.MaxPooling2D(pool_size=(2, 2),
... strides=(2, 2), padding='valid')
>>> max_pool_2d(x)
<tf.Tensor: shape=(1, 1, 2, 1), dtype=float32, numpy=
array([[[[6.],
[8.]]]], dtype=float32)>
用法 # 範例
>>> input_image = tf.constant([[[[1.], [1.], [2.], [4.]],
... [[2.], [2.], [3.], [2.]],
... [[4.], [1.], [1.], [1.]],
... [[2.], [2.], [1.], [4.]]]])
>>> output = tf.constant([[[[1], [0]],
... [[0], [1]]]])
>>> model = tf.keras.models.Sequential()
>>> model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2),
... input_shape=(4, 4, 1)))
>>> model.compile('adam', 'mean_squared_error')
>>> model.predict(input_image, steps=1)
array([[[[2.],
[4.]],
[[4.],
[4.]]]], dtype=float32)
例如,當 stride=(1, 1) 且 padding="same" 時
>>> x = tf.constant([[1., 2., 3.],
... [4., 5., 6.],
... [7., 8., 9.]])
>>> x = tf.reshape(x, [1, 3, 3, 1])
>>> max_pool_2d = tf.keras.layers.MaxPooling2D(pool_size=(2, 2),
... strides=(1, 1), padding='same')
>>> max_pool_2d(x)
<tf.Tensor: shape=(1, 3, 3, 1), dtype=float32, numpy=
array([[[[5.],
[6.],
[6.]],
[[8.],
[9.],
[9.]],
[[8.],
[9.],
[9.]]]], dtype=float32)>
參數
(2, 2)
將取 2x2 池化視窗中的最大值。如果僅指定一個整數,則兩個維度將使用相同的視窗長度。pool_size
。"valid"
或 "same"
其中之一(不區分大小寫)。"valid"
表示不填充。"same"
會均勻地在輸入的左/右或上/下填充,使輸出的高度/寬度維度與輸入相同。channels_last
(預設) 或 channels_first
其中之一。輸入中維度的順序。channels_last
對應於形狀為 (batch, height, width, channels)
的輸入,而 channels_first
對應於形狀為 (batch, channels, height, width)
的輸入。如果未指定,則使用在您的 TF-Keras 設定檔 ~/.keras/keras.json
(如果存在) 中找到的 image_data_format
值,否則使用 'channels_last'。預設為 'channels_last'。輸入形狀
data_format='channels_last'
:形狀為 (batch_size, rows, cols, channels)
的 4D 張量。data_format='channels_first'
:形狀為 (batch_size, channels, rows, cols)
的 4D 張量。輸出形狀
data_format='channels_last'
:形狀為 (batch_size, pooled_rows, pooled_cols, channels)
的 4D 張量。data_format='channels_first'
:形狀為 (batch_size, channels, pooled_rows, pooled_cols)
的 4D 張量。返回
表示最大池化值的秩為 4 的張量。有關輸出形狀,請參閱上方。