使用numpy实现带步幅的最大/平均池化。

13

我想知道如何使用numpy实现简单的最大/平均池化。 我正在阅读Max and mean pooling with numpy,但不幸的是它假定步长与内核大小相同。 有没有numpythonic的方法可以做到这一点? 同时,如果对任何维度都有效当然很好,但这不是必要的。

1个回答

20

以下是使用 stride_tricks 的纯 numpy 实现:

import numpy as np
from numpy.lib.stride_tricks import as_strided


def pool2d(A, kernel_size, stride, padding=0, pool_mode='max'):
   '''
    2D Pooling

    Parameters:
        A: input 2D array
        kernel_size: int, the size of the window over which we take pool
        stride: int, the stride of the window
        padding: int, implicit zero paddings on both sides of the input
        pool_mode: string, 'max' or 'avg'
    '''
    # Padding
    A = np.pad(A, padding, mode='constant')

    # Window view of A
    output_shape = ((A.shape[0] - kernel_size) // stride + 1,
                    (A.shape[1] - kernel_size) // stride + 1)
    
    shape_w = (output_shape[0], output_shape[1], kernel_size, kernel_size)
    strides_w = (stride*A.strides[0], stride*A.strides[1], A.strides[0], A.strides[1])
    
    A_w = as_strided(A, shape_w, strides_w)

    # Return the result of pooling
    if pool_mode == 'max':
        return A_w.max(axis=(2, 3))
    elif pool_mode == 'avg':
        return A_w.mean(axis=(2, 3))

例子:

>>> A = np.array([[1, 1, 2, 4],
                  [5, 6, 7, 8],
                  [3, 2, 1, 0],
                  [1, 2, 3, 4]])

>>> pool2d(A, kernel_size=2, stride=2, padding=0, pool_mode='max')

array([[6, 8],
       [3, 4]])

输入图像描述

https://cs231n.github.io/convolutional-networks/


很好,你也可以将这个方法用于2D数组的堆栈(通常是卷积层的输出),使用np.array([pool2d(channel, kernel_size=2, stride=2, padding=0, pool_mode='max') for channel in A])。当然,前提是A是3D数组。 - fabda01

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接