Loading the problem
Implement the forward pass of a 2-D convolution over a single channel image.
Zero pad the input by padding pixels on all four sides, then slide the kernel
with the given stride, and at each position take the elementwise product with
the window and sum it.
out_h = (H + 2 * padding - kH) // stride + 1
out_w = (W + 2 * padding - kW) // stride + 1
Two things to get right:
Return an array of shape (out_h, out_w). If the padded input is smaller than
the kernel, return an empty (0, 0) array.
def conv2d(x, kernel, stride=1, padding=0):
Input
x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
kernel = np.array([[1, 0], [0, 1]])
conv2d(x, kernel, stride=1, padding=0)
Output
array([[ 6., 8.],
[12., 14.]])
Reasoning
The kernel adds the top left and bottom right of each 2 by 2 window: 1 + 5 = 6, 2 + 6 = 8, 4 + 8 = 12 and 5 + 9 = 14.
(0, 0) array.Check runs the visible cases against a fresh kernel. Submit runs the hidden ones too.
⇧↵run cell