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

Handy Tensor operations

Pytorch is library a for creating production ready neural networks

  • torch.reshape(input, shape) → Tensor
  • torch.squeeze(input, dim=None, *, out=None) → Tensor
  • torch.transpose(input, dim0, dim1) → Tensor
  • torch.logical_not(input, *, out=None) → Tensor
  • torch.argmax(input) → LongTensor

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.reshape(input, shape) → Tensor

tensor.reshape takes a tensor as input and changes its shape. It keeps the input elements as it is but reshapes the tensor by altering it's dimensions.

# Example 1 - working (change this)
t = torch.tensor([[[1, 2], [3, 4.]],[[5, 6], [7, 8.]]])
print(t.shape)
print(t)
t = torch.reshape(t, (2,4))
print(t)
print(t.shape)
torch.Size([2, 2, 2]) tensor([[[1., 2.], [3., 4.]], [[5., 6.], [7., 8.]]]) tensor([[1., 2., 3., 4.], [5., 6., 7., 8.]]) torch.Size([2, 4])