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

5 Pytorch functions that you might require

An short introduction about PyTorch and about the chosen functions.

  • cat
  • split
  • stack
  • index_select
  • unbind

Before we begin, let's install and import PyTorch

# Uncomment and run the appropriate command for your operating system, if required

# Linux / Binder
# !pip install numpy torch==1.7.0+cpu torchvision==0.8.1+cpu torchaudio==0.7.0 -f https://download.pytorch.org/whl/torch_stable.html

# Windows
# !pip install numpy torch==1.7.0+cpu torchvision==0.8.1+cpu torchaudio==0.7.0 -f https://download.pytorch.org/whl/torch_stable.html

# MacOS
# !pip install numpy torch torchvision torchaudio
# Import torch and other required modules
import torch

Function 1 - torch.cat()

  • This function oncatenates the given sequence of seq tensors in the given dimension.
  • All tensors must either have the same shape (except in the concatenating dimension) or be empty.
# Example 1 - working (change this)

t1 = torch.randn(4,4)
print('tensor 1: ', t1)

t2 = torch.randn(4,4)
print('tensor 2: ', t2)

t3 = torch.cat((t1,t2), 0)
print('Concatonated: ', t3)
tensor 1: tensor([[ 0.8081, 0.9813, 0.9306, 0.6073], [ 0.5855, 1.4094, -0.2485, 0.5390], [ 1.3324, 0.9293, -0.4027, -0.7264], [ 0.6216, -0.4011, -0.4822, -1.4297]]) tensor 2: tensor([[ 2.9888e+00, 2.2986e-03, 2.1507e+00, 1.0552e+00], [-4.2311e-01, 5.3012e-01, 1.6477e+00, -7.8110e-01], [-5.7012e-01, 5.1006e-01, 9.4285e-01, -1.1186e+00], [-2.0443e+00, -2.0551e+00, 2.9908e-02, 2.1409e+00]]) Concatonated: tensor([[ 8.0815e-01, 9.8135e-01, 9.3059e-01, 6.0727e-01], [ 5.8546e-01, 1.4094e+00, -2.4846e-01, 5.3897e-01], [ 1.3324e+00, 9.2934e-01, -4.0272e-01, -7.2643e-01], [ 6.2160e-01, -4.0108e-01, -4.8222e-01, -1.4297e+00], [ 2.9888e+00, 2.2986e-03, 2.1507e+00, 1.0552e+00], [-4.2311e-01, 5.3012e-01, 1.6477e+00, -7.8110e-01], [-5.7012e-01, 5.1006e-01, 9.4285e-01, -1.1186e+00], [-2.0443e+00, -2.0551e+00, 2.9908e-02, 2.1409e+00]])