Skip to content

← Neural Network Layers step 6 of 9

Medium Primitives

Implement Max Pooling 1D

Max pooling summarizes each window by its largest value. The result is a value, not the index of that value. For a window containing only negative values, choose the largest negative value; do not replace it with zero.

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

Start Window Maximum
0 [1, 3] 3
2 [2, 5] 5

Return [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 max_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 maximum. 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…