Learn practical skills, build real-world projects, and advance your career

Tensor Dimensions Manipulation

In this notebook, I will discuss ways to change the dimensions of pytorch tensors in order to run proper operations.

  • view
  • reshape
  • unsqueez
  • narrow
  • split
# Import torch and other required modules
import torch

1 - tensor.view()

Used to reshape the tensors guranteeing that the new view is contiguous to the original tensor

# initialize a random tensor:
t = torch.randn((3,6), dtype=torch.float64)
t
tensor([[-0.5408, -0.0113,  1.1259,  0.7425,  0.0775,  2.0028],
        [-0.1798,  1.0431, -0.0445,  0.0123,  2.1436, -0.1350],
        [ 0.4841, -0.2770, -1.7911, -0.3967,  1.4297, -0.8990]],
       dtype=torch.float64)
# create the new view:
a = t.view((9,2))
# show the view a:
print('a =', a)
# check if t and a share the same underlying data:
print('share same data? ', t.storage().data_ptr() == a.storage().data_ptr())
# change the original tensor t:
t[0][0] = 5
# check what happens to its view
print('a =', a)
a = tensor([[ 5.0000, -0.1029], [-1.0466, 0.9614], [ 0.5982, 0.8046], [ 0.3936, 1.6704], [-0.7215, 1.0620], [-0.1761, -1.3021], [-0.2531, -0.3212], [ 1.1066, 0.9818], [-0.7969, -2.0186]], dtype=torch.float64) share same data? True a = tensor([[ 5.0000, -0.1029], [-1.0466, 0.9614], [ 0.5982, 0.8046], [ 0.3936, 1.6704], [-0.7215, 1.0620], [-0.1761, -1.3021], [-0.2531, -0.3212], [ 1.1066, 0.9818], [-0.7969, -2.0186]], dtype=torch.float64)