Skip to content

← Tensor Foundations step 2 of 7

Easy Framework

Reshape a Tensor

Reshaping changes how values are grouped into dimensions. It keeps their logical order: reading the input and output in row-major order gives the same sequence. It does not swap rows and columns.

Your task

Implement reshape_tensor(x, shape).

  • x is a tensor and shape is a list of target dimensions.
  • The supplied shape is valid and has the same total number of elements as x.
  • Return a tensor with that shape, preserving the values, dtype and device. Leave x unchanged. You do not need to guarantee that the result shares storage.

For x=[[1, 2, 3], [4, 5, 6]], reshaping to [3, 2] produces [[1, 2], [3, 4], [5, 6]]. Transposing the same input would instead produce [[1, 4], [2, 5], [3, 6]]. Both results have shape (3, 2), but their values are arranged differently.

A common use is flattening several feature dimensions into one while retaining the batch dimension. The total element count must stay the same: a (2, 3) tensor has six elements, so it cannot be reshaped to (2, 4).

Use x.reshape(shape) in either framework. In PyTorch, reshape can copy data when needed; this task does not require the stricter storage rules of view.

Explore how the same sequence fits different shapes below.

Loading visualization…