2D Convolution: Slide the Kernel, Shrink the Map

Neural NetworksMedium+20 XP+15

2D Convolution: Slide the Kernel, Shrink the Map

A convolution slides a small kernel across an image and records a dot product at every stop. That single operation is what lets a CNN detect the same edge in the top-left corner and the bottom-right one using the same handful of weights.

Task: write conv2d(image, kernel) for a single channel, stride 1, no padding. Return the output map with every value rounded to 4 decimal places.

  • Output size is (H - kh + 1) × (W - kw + 1).
  • If the kernel is larger than the image in either direction, return an empty list.
  • Do not flip the kernel. This is cross-correlation — what every deep learning framework calls convolution.

Notice how the output shrinks. Stack twenty of these and the map has shrunk by twenty pixels in each direction, which is the entire reason padding exists as an option.

0.0
?
?
?

Step it across one column at a time, recording a score at each stop.

Examples

image = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]
kernel = [[1.0, 0.0], [0.0, 1.0]]
returns [[6.0, 8.0], [12.0, 14.0]]
image = [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]
kernel = [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]
returns [[9.0]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run