MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / maxpooling

Function maxpooling

computer_vision/pooling_functions.py:8–60  ·  view source on GitHub ↗

This function is used to perform maxpooling on the input array of 2D matrix(image) Args: arr: numpy array size: size of pooling matrix stride: the number of pixels shifts over the input matrix Returns: numpy array of maxpooled matrix Sample Input Outp

(arr: np.ndarray, size: int, stride: int)

Source from the content-addressed store, hash-verified

6
7# Maxpooling Function
8def maxpooling(arr: np.ndarray, size: int, stride: int) -> np.ndarray:
9 """
10 This function is used to perform maxpooling on the input array of 2D matrix(image)
11 Args:
12 arr: numpy array
13 size: size of pooling matrix
14 stride: the number of pixels shifts over the input matrix
15 Returns:
16 numpy array of maxpooled matrix
17 Sample Input Output:
18 >>> maxpooling([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], 2, 2)
19 array([[ 6., 8.],
20 [14., 16.]])
21 >>> maxpooling([[147, 180, 122],[241, 76, 32],[126, 13, 157]], 2, 1)
22 array([[241., 180.],
23 [241., 157.]])
24 """
25 arr = np.array(arr)
26 if arr.shape[0] != arr.shape[1]:
27 raise ValueError("The input array is not a square matrix")
28 i = 0
29 j = 0
30 mat_i = 0
31 mat_j = 0
32
33 # compute the shape of the output matrix
34 maxpool_shape = (arr.shape[0] - size) // stride + 1
35 # initialize the output matrix with zeros of shape maxpool_shape
36 updated_arr = np.zeros((maxpool_shape, maxpool_shape))
37
38 while i < arr.shape[0]:
39 if i + size > arr.shape[0]:
40 # if the end of the matrix is reached, break
41 break
42 while j < arr.shape[1]:
43 # if the end of the matrix is reached, break
44 if j + size > arr.shape[1]:
45 break
46 # compute the maximum of the pooling matrix
47 updated_arr[mat_i][mat_j] = np.max(arr[i : i + size, j : j + size])
48 # shift the pooling matrix by stride of column pixels
49 j += stride
50 mat_j += 1
51
52 # shift the pooling matrix by stride of row pixels
53 i += stride
54 mat_i += 1
55
56 # reset the column index to 0
57 j = 0
58 mat_j = 0
59
60 return updated_arr
61
62
63# Averagepooling Function

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected