Keras 的 MaxPooling1D 和 GlobalMaxPooling1D 函数有什么区别?

What is the difference between Keras' MaxPooling1D and GlobalMaxPooling1D functions?

MaxPooling1D 和 GlobalMaxPooling1D 都被描述为时间数据的最大池化操作。

keras.layers.pooling.MaxPooling1D(pool_size=2, strides=None, padding='valid')

我知道 GlobalMaxPooling1D 没有输入参数。 keras.layers.pooling.GlobalMaxPooling1D()

我只是想直观地了解一下他们两个在工作方式上有何不同?

Td;lr GlobalMaxPooling1D 时间数据取最大向量 步骤维度。因此,形状为 [10, 4, 10] 的张量在全局池化后变为形状为 [10, 10] 的张量。 MaxPooling1D 也采用最大步数,但每个步幅限制为 pool_size。因此 pooling_size=2stride=1 的 [10, 4, 10] 张量是 MaxPooling(pooling_size=2, stride=1)

之后的 [10, 3, 10] 张量

带图形辅助的长答案

假设我们有一个包含 4 个词的简单句子,并且我们对这些词进行了一些向量编码(例如 word2vec 嵌入)。当然,您通常不会 max pool over 和嵌入 Tensor,但这应该作为一个例子。全局池也适用于跨渠道,但我将在本图中省略。最后,填充会使事情变得稍微复杂一些,但我们在这里也不需要它。

假设我们有 MaxPooling1D(pool_size=2, strides=1). 那么

the  [[.7, -0.2, .1]   | pool size is two                  
boy   [.8, -.3,  .2]   | so look at two words at a time    | stride=1 will
will  [.2, -.1,  .4]     and take the max over those       | move the pool down
live  [.4  -.4,  .8]]    2 vectors. Here we looking         1 word. Now we look  
                            'the' and 'boy'.                'boy' and 'will' and 
                                                            take the max.

所以这将导致 [1, 3, 3] 张量,每个时间步长都是 2D 池中的最大值。由于我们有 3 个池,因此我们有效地将时间步从 4 下采样到 3。

然而,如果我们使用 GlobalMaxPooling1D,我们将只取该句子的最大向量(张量),它可能是单词 'live' 的向量表示。

确实,这是 GlobalMaxPooling1D 在 keras 中的定义方式

class GlobalMaxPooling1D(_GlobalPooling1D):
    """Global max pooling operation for temporal data.
    # Input shape
        3D tensor with shape: `(batch_size, steps, features)`.
    # Output shape
        2D tensor with shape:
        `(batch_size, features)`
    """

    def call(self, inputs):
        return K.max(inputs, axis=1)

希望对您有所帮助,请让我澄清任何问题。

此外,这里还有一个您可以尝试的示例:

import numpy as np
from keras.models import Sequential
from keras.layers import Dense, LSTM, GlobalMaxPooling1D, MaxPooling1D

D = np.random.rand(10, 6, 10)

model = Sequential()
model.add(LSTM(16, input_shape=(6, 10), return_sequences=True))
model.add(MaxPooling1D(pool_size=2, strides=1))
model.add(LSTM(10))
model.add(Dense(1))
model.compile(loss='binary_crossentropy', optimizer='sgd')

# print the summary to see how the dimension change after the layers are 
# applied

print(model.summary())

# try a model with GlobalMaxPooling1D now

model = Sequential()
model.add(LSTM(16, input_shape=(6, 10), return_sequences=True))
model.add(GlobalMaxPooling1D())
model.add(Dense(1))
model.compile(loss='binary_crossentropy', optimizer='sgd')

print(model.summary())

@ThePassenger [x, y, z] 可以看作是你有一个 "array" 和 x 元素,其中每个元素都是一个有 y 行和 z 列的矩阵。但也因为你有一个矩阵 aith x 行和 y 列,并且对于每个元素你都有一个 z 元素数组。

池只是减少张量的一种方法,例如,如果你有一个 x 行和 y 列的矩阵,应用池化可以得到一个 x-n 行和相同的 y-m 列的矩阵。