Skip to content

← CNNs from Scratch step 9 of 15

Medium End-to-End

Simple CNN

Implement the forward pass of a small convolutional neural network (CNN) for one one-dimensional signal. It has one filter and returns one number: filter the signal, apply ReLU, keep the largest activation, then apply a scalar weight and bias.

The parameters are supplied. Do not train the network or update them.

Inputs and output

  • x has shape (L,) and conv_w has shape (K,), with 1 <= K <= L. They are floating-point tensors with the same dtype and device.
  • conv_b, fc_w and fc_b are Python floats.
  • Return the prediction as a Python float, leaving the inputs unchanged.

Layer sequence

  1. Convolution: slide conv_w over x with stride 1 and no padding. For i from 0 through L - K, compute conv[i] = sum(x[i + j] * conv_w[j] for j in range(K)) + conv_b. This gives L - K + 1 values. Use the kernel in its given order, without reversing it.
  2. ReLU: replace each negative convolution value with zero.
  3. Global max pooling: take the maximum over all remaining positions. The result is one scalar, not a shorter sequence of local maxima.
  4. Output layer: return pooled * fc_w + fc_b. Apply no activation after this step, so the prediction can be negative and is not a probability.

For x=[2, -1, 3], conv_w=[1, 2] and conv_b=1, the convolution gives [1, 6]. ReLU keeps both values and global pooling returns 6. With fc_w=0.5 and fc_b=2, the prediction is 5.0.

If every convolution value is nonpositive, pooling returns zero and the prediction equals fc_b. If K=L, there is only one convolution position, but all four steps still apply.