# how to perform max/mean pooling on a 2d array using numpy

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about how to perform max/mean pooling on a 2d array using numpy in Python. So Here I am Explain to you all the possible Methods here.

## how to perform max/mean pooling on a 2d array using numpy?

1. how to perform max/mean pooling on a 2d array using numpy?

If the image size is evenly divisible by the kernal size, you can reshape the array and use `max` or `mean` as you see fit

2. perform max/mean pooling on a 2d array using numpy

If the image size is evenly divisible by the kernal size, you can reshape the array and use `max` or `mean` as you see fit

## Method 1

You could use scikit-image block_reduce:

```import numpy as np
import skimage.measure

a = np.array([
[  20,  200,   -5,   23],
[ -13,  134,  119,  100],
[ 120,   32,   49,   25],
[-120,   12,    9,   23]
])
skimage.measure.block_reduce(a, (2,2), np.max)
```

Gives:

```array([[200, 119],
[120,  49]])```

## Method 2

If the image size is evenly divisible by the kernal size, you can reshape the array and use `max` or `mean` as you see fit

```import numpy as np

mat = np.array([[  20,  200,   -5,   23],
[ -13,  134,  119,  100],
[ 120,   32,   49,   25],
[-120,   12,   9,   23]])

M, N = mat.shape
K = 2
L = 2

MK = M // K
NL = N // L
print(mat[:MK*K, :NL*L].reshape(MK, K, NL, L).max(axis=(1, 3)))
# [[200, 119], [120, 49]]
```

If you don’t have an even number of kernels, you’ll have to handle the boundaries separately. (As pointed out in the comments, this results in the matrix being copied, which will affect performance).

```mat = np.array([[20,  200,   -5,   23, 7],
[-13,  134,  119,  100, 8],
[120,   32,   49,   25, 12],
[-120,   12,   9,   23, 15],
[-57,   84,   19,   17, 82],
])
# soln
# [200, 119, 8]
# [120, 49, 15]
# [84, 19, 82]
M, N = mat.shape
K = 2
L = 2

MK = M // K
NL = N // L

# split the matrix into 'quadrants'
Q1 = mat[:MK * K, :NL * L].reshape(MK, K, NL, L).max(axis=(1, 3))
Q2 = mat[MK * K:, :NL * L].reshape(-1, NL, L).max(axis=2)
Q3 = mat[:MK * K, NL * L:].reshape(MK, K, -1).max(axis=1)
Q4 = mat[MK * K:, NL * L:].max()

# compose the individual quadrants into one new matrix
soln = np.vstack([np.c_[Q1, Q3], np.c_[Q2, Q4]])
print(soln)
# [[200 119   8]
#  [120  49  15]
#  [ 84  19  82]]```

## Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.