Learn / PyTorch
Beginner

Shape Ops & Indexing

reshape, squeeze/unsqueeze, permute, and indexing: same spirit as NumPy.

CallEffectExample

x.squeeze()

remove all size-1 dimensions

shape (1, 3, 1)(3,)

x.unsqueeze(dim)

insert a new size-1 dimension at dim

shape (3,), unsqueeze(0)(1, 3)

x.permute(2, 0, 1)

reorder dimensions arbitrarily

shape (H, W, C)(C, H, W)

torch.cat([a, b], dim=0)

join along an EXISTING dimension

two (2, 3) tensors → (4, 3)

torch.stack([a, b], dim=0)

join along a NEW dimension

two (2, 3) tensors → (2, 2, 3)

⚠️ Watch out: x.view() requires contiguous memory and fails after operations like .transpose()/.permute(): use .reshape() (or call .contiguous() first) to be safe.

Now practice it

Exercises that use what this lesson just covered.

Tensors BasicsAutograd