Skip to content

← CNNs from Scratch step 4 of 15

Medium Primitives

Implement Average Pooling 1D

Average pooling summarizes each window by its arithmetic mean: sum the values and divide by the number of entries in the window. Fractional and negative outputs are valid; do not round the result to an integer.

Worked example: for x = [1, 3, 2, 5, 4], kernel_size = 2 and stride = 2:

Start Window Mean
0 [1, 3] 2
2 [2, 5] 3.5

Each mean is the sum of its two window values divided by 2. Return [2, 3.5]. The next start index would be 4, but only one value remains. This exercise uses no padding and includes only complete windows; do not add a partial-window result. Stride is the distance between starts, so smaller strides can create overlapping windows.

Your task

Implement avg_pool1d(x, kernel_size, stride) for a nonempty 1D floating-point tensor x of shape (L,). Both integer parameters are positive, and kernel_size <= L.

For output index i, take x[i * stride : i * stride + kernel_size] and return its mean. The output is a 1D tensor with length (L - kernel_size) // stride + 1. There is no padding or dilation. Use basic tensor slicing and reductions rather than a built-in pooling operation.

When stride is larger than kernel_size, some input values are skipped between windows. Always move the window start by stride and discard any incomplete final window.

Explore the positions: the shared window diagram below shows indices, not data values or the reduction result. Keep padding at 0 and dilation at 1 to match this exercise; use Next position to inspect each complete window.

Loading visualization…