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

PyTorch

These are the few tensor functions I've choosen.

For more functions visit:
https://pytorch.org/docs/stable/torch.html

  • torch.cat
  • torch.unsqueeze
  • torch.view
  • torch.zeros_like
  • torch.arange
# Import torch and other required modules
import torch

Function 1 - torch.cat

torch.cat is a built-in function which can concatenate sequences of given tensor in the given dimension

# here are two 2 x 2 tensors (x and y)
# manual tensors.
tensor_x = torch.tensor([[5, 6], 
                         [8, 7]])

tensor_y = torch.tensor([[10, 11], 
                         [12, 13]])

# concatenate tensor in the given dim (0 - rows, 1 - column)
# concat on dim = 0 (rows)
vec_row = torch.cat((tensor_x, tensor_y), dim=0)
# concat on dim = 1 (columns)
vec_col = torch.cat((tensor_x, tensor_y), dim=1)

print(vec_row, vec_col, vec_row.shape, vec_col.shape, sep='\n\n',)
tensor([[ 5, 6], [ 8, 7], [10, 11], [12, 13]]) tensor([[ 5, 6, 10, 11], [ 8, 7, 12, 13]]) torch.Size([4, 2]) torch.Size([2, 4])
  • Not only two tensors, torch.cat can concatenate n-number of tensor in the given dimension.