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

Pytorch 'Indexing, Slicing, Joining, and Mutating' operations samples

PyTorch is an open source deep learning framework built to be flexible and modular for research,
it is used for applications such as computer vision and natural language processing, primarily developed by Facebook's AI
It provides a Python package for high-level features like tensor computation (like NumPy) with strong GPU acceleration
and a Deep neural networks built on a tape-based autograd system.

PyTorch provides multi-dimensional Tensors that can live either on the CPU or the GPU and accelerates the computation by a huge amount. And those are 5 simple Tensor functions about 'Indexing, Slicing, Joining, and Mutating' operations to be viewed and discussed:

  • TORCH.CAT()
  • TORCH.CHUNK()
  • TORCH.UNBIND()
  • TORCH.TRANSPOSE()
  • TORCH.VSTACK()

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

TORCH.CAT()

torch.cat() concatenates a given sequence of tensors in the given dimension.
All tensors must either have the same shape or be empty.

# Example 1 - working (concatination over the zero dimension)
x = torch.randn(2, 4)
y = torch.randn(2,4)
x,y
(tensor([[-0.9227,  0.3367,  0.5790, -0.8610],
         [-1.3214,  0.6527, -0.6058, -0.7337]]),
 tensor([[-0.1378,  0.1176, -0.9133,  0.3877],
         [ 1.2060,  1.2807, -1.3365, -0.4115]]))