2-D convolution (cross-correlation) with stride and padding
Problem
Apply a 2-D kernel to a single-channel image as deep-learning frameworks do (no kernel flip). Zero-pad by padding on every side; output size is floor((H + 2p − kh)/stride) + 1 per dimension.
Signature
def conv2d(image, kernel, stride: int = 1, padding: int = 0) -> np.ndarray: ...Examples
The visible tests, as an interactive Python session would show them: each call and the value it should give.
>>> close(conv2d([[1,2,3],[4,5,6],[7,8,9]], [[1,0],[0,-1]]), [[-4.0, -4.0], [-4.0, -4.0]])
True
>>> close(conv2d([[1,2,3],[4,5,6],[7,8,9]], [[1]], stride=2), [[1.0, 3.0], [7.0, 9.0]])
TrueHints
Apply the kernel as cross-correlation — no flip.
Output size = floor((H + 2p - kh)/stride) + 1 per dimension; zero-pad by padding on every side.
Use offset indexing over the window rather than per-pixel loops.
Reference solution
import numpy as np
def conv2d(image, kernel, stride=1, padding=0):
img = np.asarray(image, float); ker = np.asarray(kernel, float)
if padding:
img = np.pad(img, padding)
H, W = img.shape; kh, kw = ker.shape
oh = (H - kh) // stride + 1; ow = (W - kw) // stride + 1
out = np.zeros((oh, ow))
for i in range(oh):
for j in range(ow):
out[i, j] = (img[i * stride:i * stride + kh, j * stride:j * stride + kw] * ker).sum()
return outWhat a strong solution covers
- Correct output shape formula.
- Correct window indexing with stride.
- Explains cross-correlation vs convolution.
- Discusses im2col/GEMM vectorisation, multi-channel extension, and receptive fields.
Common mistakes
- flipping the kernel
- off-by-one output sizes with stride > 1.