Problems
Loading...
1 / 1

Implement a Simple CNN Layer (NumPy)

Neural Networks
Medium

Implement a single 2D convolution layer forward pass for channel-first tensors.

Input/Output Shapes

Input: x of shape (N, C_in, H, W)
Weights: W of shape (C_out, C_in, KH, KW)
Bias: b of shape (C_out,)
Output: y of shape (N, C_out, H_out, W_out)
where H_out = H - KH + 1, W_out = W - KW + 1

Convolution Formula

y[n,cout,i,j]=cinuvx[n,cin,i+u,j+v]W[cout,cin,u,v]+b[cout]Sum over all input channels and kernel positions\begin{align*} y[n, c_{\text{out}}, i, j] &= \sum_{c_{\text{in}}} \sum_{u} \sum_{v} x[n, c_{\text{in}}, i + u, j + v] \cdot W[c_{\text{out}}, c_{\text{in}}, u, v] + b[c_{\text{out}}] \\ &\text{Sum over all input channels and kernel positions} \end{align*}
Loading visualization...

Examples

Input: x = np.ones((1,1,3,3)) (all ones)

Kernel: W = np.ones((1,1,2,2)), b = [0]

Process: Each 2×2 patch sums to 4

Output: [[[[4., 4.], [4., 4.]]]] (2×2 output)

Requirements

  • NumPy only. No torch/tensorflow/sklearn
  • Must work for batch (N>1)
  • Must be vectorized; explicit Python loops over N, C_in, C_out are okay but try to avoid inner H/W loops
  • Return float array
  • Use valid convolution (no padding, stride=1)

Constraints

  • N ≤ 8, C_in ≤ 4, C_out ≤ 4, H,W ≤ 10
  • Must run within 500 ms
Try Similar Problems