Beginner Shape Ops & Indexing reshape, squeeze/unsqueeze, permute, and indexing: same spirit as NumPy.
import torch
x = torch .arange(6 ).reshape(2 , 3 )
print (x)
print (x.t()) # transpose
print (x.flatten()) # collapse to 1-D
print (x[0 , 1 ]) # element access
print (x[:, 0 ]) # every row, column 0
▶ Run
Call Effect Example 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)
import torch
img = torch .arange(24 ).reshape(2 , 3 , 4 ).float () # (H, W, C)
print (img.permute(2 , 0 , 1 ).shape) # -> (C, H, W), PyTorch's usual layout
a = torch .tensor([1 , 2 ])
b = torch .tensor([3 , 4 ])
print (torch .cat([a, b])) # [1 2 3 4] -- same dimension, longer
print (torch .stack([a, b])) # [[1 2] [3 4]] -- new dimension added
▶ Run
⚠️ 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.