仅使用NumPy的Maxpooling 2x2数组 [英] Maxpooling 2x2 array only using numpy

查看:35
本文介绍了仅使用NumPy的Maxpooling 2x2数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用numpy进行最大池化方面的帮助。 我正在学习数据科学的Python,在这里我必须为2x2矩阵做最大池和平均池,输入可以是8x8或更多,但我必须为每个2x2矩阵做最大池。我已使用

创建了一个矩阵
k = np.random.randint(1,64,64).reshape(8,8)
因此,我将得到8x8矩阵作为随机输出。从结果中,我要执行2x2最大池化。提前感谢

推荐答案

您不必自己计算必要的步长,只需注入两个辅助维度即可创建一个4d数组,该数组是2x2分块矩阵的2D集合,然后对各块取元素最大值:

import numpy as np

# use 2-by-3 size to prevent some subtle indexing errors
arr = np.random.randint(1, 64, 6*4).reshape(6, 4)

m, n = arr.shape
pooled = arr.reshape(m//2, 2, n//2, 2).max((1, 3))

上述内容的一个示例:

>>> arr
array([[40, 24, 61, 60],
       [ 8, 11, 27,  5],
       [17, 41,  7, 41],
       [44,  5, 47, 13],
       [31, 53, 40, 36],
       [31, 23, 39, 26]])

>>> pooled
array([[40, 61],
       [44, 47],
       [53, 40]])

对于不采用2x2数据块的完全通用数据块池:

import numpy as np

# again use coprime dimensions for debugging safety
block_size = (2, 3)
num_blocks = (7, 5)
arr_shape = np.array(block_size) * np.array(num_blocks)
numel = arr_shape.prod()
arr = np.random.randint(1, numel, numel).reshape(arr_shape)

m, n = arr.shape  # pretend we only have this
pooled = arr.reshape(m//block_size[0], block_size[0],
                     n//block_size[1], block_size[1]).max((1, 3))

这篇关于仅使用NumPy的Maxpooling 2x2数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆