I am trying to implement a custom pooling method - aka - even sum pooling (sum of all even numbers in the kernel). I looked into the max-pooling implementation here
EDIT
For example, if my input is
A = np.array([[1, 1, 2, 4],
[5, 6, 7, 8],
[3, 2, 1, 0],
[1, 2, 3, 4]])
My output should be
[[ 6 14]
[ 4 4]]
Based on the implementation here, I did the below code, with two additional helper functions
import numpy as np from numpy.lib.stride_tricks import as_strided
def even_sum_pooling(matrix):
n = matrix.shape[0]
summ = 0
for i in range(n):
if matrix[i]% 2 == 0:
summ +=matrix[i]
return summ
def total(row):
summ = 0
for num in row:
summ +=num
return summ
def pool2d(A, kernel_size, stride, padding, pool_mode='max'):
'''
2D Pooling
Parameters:
A: input 2D array
kernel_size: int, the size of the window
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)
kernel_size = (kernel_size, kernel_size)
A_w = as_strided(A, shape = output_shape + kernel_size,
strides = (stride*A.strides[0],
stride*A.strides[1]) + A.strides)
A_w = A_w.reshape(-1, *kernel_size)
# Return the result of pooling
temp = np.apply_along_axis(even_sum_pooling, 2, A_w)
return np.apply_along_axis(total,1,temp).reshape(output_shape)
This works but I am interested in how I can change the last two code lines to 1 line.
How do I do that? Please suggest.