Reshape, Flatten & Transpose PyTorch Tensors

Basics
BasicsPyTorchTensor ShapesGoogleMetaAmazon

Problem

Given a 1D PyTorch tensor x containing rows * cols elements, implement reshape_ops(x, rows, cols) and return (reshaped, transposed, flat) where reshaped has shape (rows, cols), transposed swaps axes 0 and 1 to shape (cols, rows), and flat is a 1D flattened copy/view of x.

Why It Matters: Tensor shape manipulation—reshaping flat feature vectors into matrices, transposing weight matrices for dot products, and flattening convolutional feature maps before nn.Linear—is used in almost every neural network.

Function Signature

import torch

def reshape_ops(x: torch.Tensor, rows: int, cols: int):
    """Return (reshaped[rows,cols], transposed[cols,rows], flat[rows*cols])."""

Sample Input & Output

Example 1: Standard 2×3 Reshape

Input:

x = torch.tensor([1., 2., 3., 4., 5., 6.]), rows = 2, cols = 3

Expected Output:

reshaped = tensor([[1., 2., 3.], [4., 5., 6.]])
transposed = tensor([[1., 4.], [2., 5.], [3., 6.]])
flat = tensor([1., 2., 3., 4., 5., 6.])

Explanation: x fills row-by-row into (2, 3), transposing flips rows into columns (3, 2), and flat restores (6,).

Example 2: Column Vector Reshape (3×1)

Input:

x = torch.tensor([10., 20., 30.]), rows = 3, cols = 1

Expected Output:

reshaped = tensor([[10.], [20.], [30.]])  # shape (3, 1)
transposed = tensor([[10., 20., 30.]])      # shape (1, 3)
flat = tensor([10., 20., 30.])              # shape (3,)

Explanation: Reshaping into a column matrix (3, 1) and transposing produces a row matrix (1, 3).

Constraints & Edge Cases

  • Return (reshaped, transposed, flat).
  • Prefer x.reshape(rows, cols) over .view(...) when tensors may be non-contiguous.
  • rows * cols always equals x.numel().

Constraints & Evaluation Criteria

  • Return `(reshaped, transposed, flat)`.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
arange(6), rows=2, cols=3
Expected Output / Criteria
(2,3), (3,2), (6,)