Neural Mastery
← Practice
Practice: 2D Convolution From Scratchmedium

Practice: 2D Convolution From Scratch

medium Neural Networks by Hand 15–20 min

NumPy allowed · plain Python earns 10 bonus points

New to this topic? Computer Vision — Overview
Study this concept first →

Implement a 2D spatial convolution operation from scratch without external libraries, the core layer in CNN architectures.

Task

Implement convolve2d(image, kernel). Apply the kernel across all valid positions without padding. Output dimension is (H - Kh + 1) x (W - Kw + 1).

Function Signature

convolve2d(image: list[list[float]], kernel: list[list[float]]) -> list[list[float]]

Examples

Example 1: 3x3 image with 2x2 edge filter
Input: image = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] kernel = [[1, 0], [0, -1]]
Output: [[-4, -4], [-4, -4]]
Example 2: Identity kernel matching image dimensions
Input: image = [[5]] kernel = [[2]]
Output: [[10]]

Constraints

  • image height H >= Kh, width W >= Kw
  • kernel is non-empty 2D grid
  • Returns 2D list of numbers
Python3Saved ✓
def convolve2d(image: list[list[float]], kernel: list[list[float]]) -> list[list[float]]:
"""Compute 2D valid cross-correlation / convolution between image and kernel.
Return the (H - Kh + 1) x (W - Kw + 1) output grid.
"""
# Your code here
pass

Case 1: 3x3 image with 2x2 edge filter
Input: image = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] kernel = [[1, 0], [0, -1]]
Expected: [[-4, -4], [-4, -4]]
Case 2: Identity kernel matching image dimensions
Input: image = [[5]] kernel = [[2]]
Expected: [[10]]