python - 使用 numpy 实现最大/平均池化(带步幅)

标签 python python-3.x numpy conv-neural-network

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

最佳答案

这是一个使用 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]])

enter image description here

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

关于python - 使用 numpy 实现最大/平均池化(带步幅),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54962004/

相关文章:

python - Kivy 弹出窗口显示背景小部件

python - 如何在数字所在的确切位置裁剪图像?

python - 将 numpy 数组转换为 numpy 记录数组

python - ctypes:c_uint8 是否支持位字段?

python - 有什么方法可以像字典一样从列表中的元组中获取值吗?

带有 Waitress WSGI 的 Python Flask 无法与 Heroku 一起使用

python - 在 Python3 中使用 %x 格式化不好吗?

python - 奥杜 12 : How to send a Inbox message to Specific User?

python - Peewee ORM——获取除了在另一个查询中共享的行之外的所有行

python - Keras 中不带 for 循环的 One-hot 编码