Neural Mastery
← Practice
Multi-Channel 2D Convolutionmedium

Multi-Channel 2D Convolution

medium Neural Networks by Hand 20 min

NumPy allowed · plain Python earns 10 bonus points

Compute the core 3D tensor inner product across all input channels for a convolutional filter.

Task

Implement conv2d_multi_channel(x, kernel, bias=0.0, stride=1, padding=0): pad each of the C input channels with padding zeros. Then slide the 3D filter (C, kH, kW) over the spatial dimensions with stride stride. At each location, sum the element-wise products across all channels and spatial kernel coordinates, add bias, and round to 4 decimal places.

Function Signature

conv2d_multi_channel(x: list[list[list[float]]], kernel: list[list[list[float]]], bias: float = 0.0, stride: int = 1, padding: int = 0) -> list[list[float]]

Examples

Example 1: 2-channel 3x3 input 2x2 kernel stride 1 no pad
Input: x = [[[1, 2], [3, 4]], [[0.5, 0.5], [0.5, 0.5]]] kernel = [[[1, 0], [0, 1]], [[2, 2], [2, 2]]] bias = 0.5 stride = 1 padding = 0
Output: [[9.5]]
Example 2: Single channel 3x3 kernel with padding 1
Input: x = [[[1, 2], [3, 4]]] kernel = [[[0, 0, 0], [0, 1, 0], [0, 0, 0]]] bias = 0 stride = 1 padding = 1
Output: [[1, 2], [3, 4]]
Example 3: Strided multi-channel conv stride 2
Input: x = [[[1, 2, 3], [4, 5, 6], [7, 8, 9]]] kernel = [[[1, 1], [1, 1]]] bias = 1 stride = 2 padding = 0
Output: [[13]]

Constraints

  • len(x) == len(kernel) >= 1
  • 1 <= H, W <= 64
  • 1 <= kH, kW <= 15
  • stride >= 1
  • padding >= 0
Python3Saved ✓
def conv2d_multi_channel(x: list[list[list[float]]], kernel: list[list[list[float]]], bias: float = 0.0, stride: int = 1, padding: int = 0) -> list[list[float]]:
"""Perform 2D discrete cross-correlation on multi-channel input (C, H, W) with a 3D kernel (C, kH, kW).

Args:
x: Input feature maps of shape (C, H, W).
kernel: Filter weights of shape (C, kH, kW).
bias: Additive scalar bias.
stride: Spatial sliding stride.
padding: Zero-padding applied to borders.

Returns:
Single output feature map matrix (H_out, W_out) rounded to 4 decimals.
"""
pass

Case 1: 2-channel 3x3 input 2x2 kernel stride 1 no pad
Input: x = [[[1, 2], [3, 4]], [[0.5, 0.5], [0.5, 0.5]]] kernel = [[[1, 0], [0, 1]], [[2, 2], [2, 2]]] bias = 0.5 stride = 1 padding = 0
Expected: [[9.5]]
Case 2: Single channel 3x3 kernel with padding 1
Input: x = [[[1, 2], [3, 4]]] kernel = [[[0, 0, 0], [0, 1, 0], [0, 0, 0]]] bias = 0 stride = 1 padding = 1
Expected: [[1, 2], [3, 4]]
Case 3: Strided multi-channel conv stride 2
Input: x = [[[1, 2, 3], [4, 5, 6], [7, 8, 9]]] kernel = [[[1, 1], [1, 1]]] bias = 1 stride = 2 padding = 0
Expected: [[13]]