【Keras】AveragePooling1D层和GlobalAveragePooling1D层

AveragePooling1D层

tf.keras.layers.AveragePooling1D(
    pool_size=2, strides=None, padding="valid", data_format="channels_last", **kwargs
)
  • 平均池化用于时序数据。
  • 下采样输入表示,通过对被定义为pool_size的窗口取平均值。窗口根据步长strides进行切换。
  • 当使用"valid" (padding)填充选项时,结果的输出的形状为:output_shape = (input_shape - pool_size + 1) / strides)
  • 示例代码1:
>>> x = tf.constant([1., 2., 3., 4., 5.])
>>> x = tf.reshape(x, [1, 5, 1])
>>> x
<tf.Tensor: shape=(1, 5, 1), dtype=float32, numpy=
  array([[[1.],
          [2.],
          [3.],
          [4.],
          [5.]], dtype=float32)>
>>> avg_pool_1d = tf.keras.layers.AveragePooling1D(pool_size=2,
...    strides=1, padding='valid')
>>> avg_pool_1d(x)
<tf.Tensor: shape=(1, 4, 1), dtype=float32, numpy=
array([[[1.5],
        [2.5],
        [3.5],
        [4.5]]], dtype=float32)>
  • 当使用"same"(padding)填充选项时,输出形状:output_shape = input_shape / strides
  • 示例代码2:
>>> x = tf.constant([1., 2., 3., 4., 5.])
>>> x = tf.reshape(x, [1, 5, 1])
>>> x
<tf.Tensor: shape=(1, 5, 1), dtype=float32, numpy=
  array([[[1.],
          [2.],
          [3.],
          [4.],
          [5.]], dtype=float32)>
>>> avg_pool_1d = tf.keras.layers.AveragePooling1D(pool_size=2,
...    strides=1, padding='same')
>>> avg_pool_1d(x)
<tf.Tensor: shape=(1, 5, 1), dtype=float32, numpy=
array([[[1.5],
        [2.5],
        [3.5],
        [4.5],
        [5.]]], dtype=float32)>

参数:

  • pool_size:平均池化窗口的大小;
  • strides:步长,如果是None,它默认值为pool_size。
  • data_format:字符串,可选项为“channels_last”和“channels_first”。也就是输入中的维度排序,channels_last 对应于inputs with shape (batch, steps, features),channels_first 对应于 inputs with shape (batch, features, steps)。

GlobalAveragePooling1D层

tf.keras.layers.GlobalAveragePooling1D(data_format="channels_last", **kwargs)

示例代码:

>>> input_shape = (2, 3, 4)
>>> x = tf.random.normal(input_shape)
>>> y = tf.keras.layers.GlobalAveragePooling1D()(x)
>>> print(y.shape)
(2, 4)

调用参数:

  • inputs:一个三维的tensor。
  • mask:二元的tensor,它的shape是(batch_size, steps),表明给定的step是否应该被masked(也就是从平均值里剔除)。

官方文档:

  • https://keras.io/api/layers/pooling_layers/average_pooling1d/
  • https://keras.io/api/layers/pooling_layers/global_average_pooling1d/

你可能感兴趣的:(NLP,keras,深度学习,python)