This function is used to perform avgpooling 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 avgpooled matrix Sample Input Outp
(arr: np.ndarray, size: int, stride: int)
| 62 | |
| 63 | # Averagepooling Function |
| 64 | def avgpooling(arr: np.ndarray, size: int, stride: int) -> np.ndarray: |
| 65 | """ |
| 66 | This function is used to perform avgpooling on the input array of 2D matrix(image) |
| 67 | Args: |
| 68 | arr: numpy array |
| 69 | size: size of pooling matrix |
| 70 | stride: the number of pixels shifts over the input matrix |
| 71 | Returns: |
| 72 | numpy array of avgpooled matrix |
| 73 | Sample Input Output: |
| 74 | >>> avgpooling([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], 2, 2) |
| 75 | array([[ 3., 5.], |
| 76 | [11., 13.]]) |
| 77 | >>> avgpooling([[147, 180, 122],[241, 76, 32],[126, 13, 157]], 2, 1) |
| 78 | array([[161., 102.], |
| 79 | [114., 69.]]) |
| 80 | """ |
| 81 | arr = np.array(arr) |
| 82 | if arr.shape[0] != arr.shape[1]: |
| 83 | raise ValueError("The input array is not a square matrix") |
| 84 | i = 0 |
| 85 | j = 0 |
| 86 | mat_i = 0 |
| 87 | mat_j = 0 |
| 88 | |
| 89 | # compute the shape of the output matrix |
| 90 | avgpool_shape = (arr.shape[0] - size) // stride + 1 |
| 91 | # initialize the output matrix with zeros of shape avgpool_shape |
| 92 | updated_arr = np.zeros((avgpool_shape, avgpool_shape)) |
| 93 | |
| 94 | while i < arr.shape[0]: |
| 95 | # if the end of the matrix is reached, break |
| 96 | if i + size > arr.shape[0]: |
| 97 | break |
| 98 | while j < arr.shape[1]: |
| 99 | # if the end of the matrix is reached, break |
| 100 | if j + size > arr.shape[1]: |
| 101 | break |
| 102 | # compute the average of the pooling matrix |
| 103 | updated_arr[mat_i][mat_j] = int(np.average(arr[i : i + size, j : j + size])) |
| 104 | # shift the pooling matrix by stride of column pixels |
| 105 | j += stride |
| 106 | mat_j += 1 |
| 107 | |
| 108 | # shift the pooling matrix by stride of row pixels |
| 109 | i += stride |
| 110 | mat_i += 1 |
| 111 | # reset the column index to 0 |
| 112 | j = 0 |
| 113 | mat_j = 0 |
| 114 | |
| 115 | return updated_arr |
| 116 | |
| 117 | |
| 118 | # Main Function |