2D Convolution (Single Channel)

~20 mincode completion

Implement conv2d_single(X, kernel) with stride 1, no padding. Return the output 2D array.

Examples

4x4 input, 2x2 all-ones kernel: each output is a 2x2 patch sum

Input
conv2d_single([[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 input, 2x2 identity-like kernel

Input
conv2d_single([[1, 0, 0], [0, 1, 0], [0, 0, 1]], [[1, 0], [0, 1]])
Output
[[2, 0], [0, 2]]

Hints

Hint 1

Sum with , and check which axis you are summing over.

Hint 2

Watch for this: off by one in output size.

Requirements

  • X: Input matrix of shape (H, W)

  • : Filter matrix of shape (Hf, Wf)

  • Return Output matrix of shape (H-Hf+1, W-Wf+1).

Constraints

  • Allowed library: NumPy only

  • Time limit: 200 ms, Memory: 64 MB

Where this shows up

~20 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 91.

Python
import numpy as np

def conv2d_single(X: np.ndarray, kernel: np.ndarray) -> np.ndarray:
    """
    Compute a valid 2D convolution with stride 1, no padding.

    Args:
        X:      Input matrix of shape (H, W)
        kernel: Filter matrix of shape (Hf, Wf)

    Returns:
        Output matrix of shape (H-Hf+1, W-Wf+1).
    """
    # YOUR CODE HERE
    pass
Loading docs…

The AI Mentor needs an account

It reads your code and the failing tests and nudges you toward the fix without handing you the answer. Free accounts get it on every problem you're working on today.