python - 用 numpy 实现最大/平均池(有步幅)
问题描述
我想知道如何用 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]])
推荐阅读
- docker - 为什么基于 ARM 的 Go 应用程序的 Dockerfile 从运行时路径中删除“linux_arm”?
- python - 启动器中的致命错误:无法使用 Python 创建进程来启动 Jupyter Lab
- javascript - React 钩子状态在父组件中更新但子组件没有收到新的道具
- javascript - 'Uncaught SyntaxError:Cannot use import statement outside a module' 导入 fs 时
- mysql - 在mysql中计算信息
- flutter-layout - 如何格式化 FormBuilderRate(Flutter Form Builder 包)?
- javascript - 在Angular 8中使用files.upload将文件上传到slack api时获得'invalid_form_data'响应
- javascript - 选择文件后如何处理用户删除文件以 HTML 形式?
- javascript - 如何通过客户端的 JWT cookie 强制注销用户
- google-sheets - 电子表格公式汇总过去 3 个月的值