1 | initial version |
The method for executing max/mean pooling on a 2-dimensional array using numpy is:
import numpy as np
array = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]])
pool_size = (2, 2) # Pooling window size
stride = 2 # Stride length
max_pooled = np.max(pooling_array(array, pool_size, stride), axis=(2, 3))
mean_pooled = np.mean(pooling_array(array, pool_size, stride), axis=(2, 3))
Note: pooling_array
is a function that returns a padded and reshaped array with the same dimensions as array
and is not built-in with numpy. It can be defined as follows:
def pooling_array(array, pool_size, stride):
# Pad array with zeros to handle border conditions
array = np.pad(array, ((0, 0), (0, 1), (0, 1)), mode='constant')
# Reshape array to handle window sizes
shape = ((array.shape[0] - pool_size[0]) // stride + 1,
(array.shape[1] - pool_size[1]) // stride + 1,
pool_size[0], pool_size[1])
strides = (array.strides[0] * stride, array.strides[1] * stride,
array.strides[0], array.strides[1])
return np.lib.stride_tricks.as_strided(array, shape=shape, strides=strides)