TheAlgorithms/Python · error · ValueError
The input array is not a square matrix
Error message
The input array is not a square matrix
What it means
maxpooling() in computer_vision/pooling_functions.py raises this ValueError when the input array's row count differs from its column count. The pooling loop assumes a square matrix: it computes one edge length for the output and iterates rows/columns symmetrically, so rectangular input would corrupt indices rather than pool correctly.
Source
Thrown at computer_vision/pooling_functions.py:27
"""
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 Output:
>>> maxpooling([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], 2, 2)
array([[ 6., 8.],
[14., 16.]])
>>> maxpooling([[147, 180, 122],[241, 76, 32],[126, 13, 157]], 2, 1)
array([[241., 180.],
[241., 157.]])
"""
arr = np.array(arr)
if arr.shape[0] != arr.shape[1]:
raise ValueError("The input array is not a square matrix")
i = 0
j = 0
mat_i = 0
mat_j = 0
# compute the shape of the output matrix
maxpool_shape = (arr.shape[0] - size) // stride + 1
# initialize the output matrix with zeros of shape maxpool_shape
updated_arr = np.zeros((maxpool_shape, maxpool_shape))
while i < arr.shape[0]:
if i + size > arr.shape[0]:
# if the end of the matrix is reached, break
break
while j < arr.shape[1]:
# if the end of the matrix is reached, break
if j + size > arr.shape[1]:
breakView on GitHub (pinned to f5988cc097)
Solutions
- Crop or pad the input to square before calling: arr[:n, :n] with n = min(arr.shape)
- Or use a library pooling op that supports rectangles: torch.nn.functional.max_pool2d, cv2, or numpy strides
- If you own the code, generalize the output shape to ((h-size)//stride+1, (w-size)//stride+1)
Example fix
# before maxpooling([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], 2, 2) # ValueError: The input array is not a square matrix # after import numpy as np arr = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]) n = min(arr.shape) maxpooling(arr[:n, :n], 2, 2)
Defensive patterns
Strategy: validation
Validate before calling
import numpy as np
arr = np.asarray(arr)
if arr.ndim != 2 or arr.shape[0] != arr.shape[1]:
n = min(arr.shape)
arr = arr[:n, :n] # or pad
maxpooling(arr.tolist(), size, stride) Type guard
def is_square(arr) -> bool:
a = np.asarray(arr)
return a.ndim == 2 and a.shape[0] == a.shape[1] Try / catch
try:
maxpooling(arr, size, stride)
except ValueError as e:
if 'square matrix' in str(e):
n = min(np.asarray(arr).shape)
return maxpooling(np.asarray(arr)[:n, :n].tolist(), size, stride)
raise Prevention
- Crop feature maps to square at load time
- Prefer torch/cv2 pooling for production pipelines
- Add shape assertions in tests: assert arr.shape[0] == arr.shape[1]
When it happens
Trigger: maxpooling([[1,2,3],[4,5,6]], 2, 2) — a 2x3 list; passing a grayscale-cropped or resized image array whose width != height; passing a numpy array of shape (h, w) with h != w.
Common situations: Feeding non-square image crops/patches into a hand-rolled pooling step; assuming the function pads or crops rectangular input like torch.nn.MaxPool2d does; converting RGBA or channel-last arrays without squeezing to a square 2-D grid.
Related errors
- invalid k value
- Vector length must match the number of nodes in the graph.
- Coefficient matrix dimensions must be nxn but received {rows
- Constant matrix must be nx1 but received {rows2}x{cols2}
- Coefficient and constant matrices dimensions must be nxn and
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/a0fc44602874d94c.
Report an issue: GitHub.