Images as Linear AlgebraMedium
Convolution as a Matrix Multiply
~18 mincode completion
Implement conv2d_as_matmul(image, kernel) for stride 1, no padding. Return the 2D output array.
Examples
4x4 input, 2x2 all-ones kernel: each output is a patch sum
- Input
- conv2d_as_matmul([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], [[1, 1], [1, 1]])
- Output
- [[14, 18, 22], [30, 34, 38], [46, 50, 54]]
3x3 identity-like kernel on a diagonal image
- Input
- conv2d_as_matmul([[1, 0, 0], [0, 1, 0], [0, 0, 1]], [[1, 0], [0, 1]])
- Output
- [[2, 0], [0, 2]]
Hints
Hint 1
Use a matrix product rather than nested loops, and check which operand transposes.
Hint 2
Watch for this: flipped the kernel as in true mathematical convolution.
Requirements
image: (H, W) array: (kh, kw) array
Return (H - kh + 1, W - kw + 1) array
Constraints
Allowed library: NumPy only
Time limit: 200 ms, Memory: 64 MB
Where this shows up
~18 min
••••••••••••••••
8 employers weight this skill
4 autonomy companies, 1 defense company, 1 health and bio company, 1 enterprise vendor, 1 AI product company. Top match scores 92.
Python
import numpy as np
def conv2d_as_matmul(image, kernel):
"""
Valid 2D cross-correlation via im2col and a matrix-vector product.
Args:
image: (H, W) array
kernel: (kh, kw) array
Returns:
(H - kh + 1, W - kw + 1) array
"""
# YOUR CODE HERE
pass