Skip to content

← Shapes and Strides step 4 of 9

Easy Primitives

Remove the channel axis while preserving the batch

Jump to the task

Implement drop_channel(x) for a tensor with shape (batch, 1, features). Return the same values with shape (batch, features). Preserve both the batch and feature axes, including when either has length one.

Why the starter fails

Calling squeeze() without a dimension removes every axis of length one:

input shape    squeeze() result    required result
(4, 1, 3)      (4, 3)             (4, 3)
(1, 1, 3)      (3,)               (1, 3)
(2, 1, 1)      (2,)               (2, 1)
(1, 1, 1)      ()                 (1, 1)

The starter works only when both batch and features are greater than one. A small final batch can expose the missing batch axis, but a single feature can cause the same kind of mistake.

Remove only the channel axis

squeeze(dim=1) removes axis 1 when its length is one and leaves every other axis in place. Here, axis 1 is the channel axis you want to remove.

Use an explicit dimension when you need to preserve other length-one axes. The argument-free form is useful when removing all such axes is intentional.

Your task

def drop_channel(x: torch.Tensor) -> torch.Tensor

For example, values [[[1., 2., 3.]]] should become [[1., 2., 3.]], with shape (1, 3) rather than (3,).