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

Wonderland of PyTorch

The story of few functions of Tensor in PyTorch.

PyTorch is an open-sourced deep-learning library based on Torch(- built on lua) which is especially designed for Python and primarily developed and maintained by Facebook AI Research (FAIR). PyTorch is the answer for the Google's TensorFlow.

Today let's know about few very important tensor functions. But, wait what exactly is a Tensor?

Tensor is nothing but a multidimensional array (or list with elements having same datatype numbers) just like NumPy arrays but with a beautiful capability of operating on CUDA-capable Nvidia GPU.

We will go through the following functions:

  • view
  • topk
  • from_numpy
  • cat
  • stack

Tensors

# Import torch
import torch

print('1D Tensor')
roll = torch.tensor([1, 2, 3, 4, 5])
print(roll)
print(type(roll))
print(roll.dtype)

print('\n2D Tensor')
marks = torch.tensor([[68, 72, 36, 72, 81],[89, 91, 71, 69, 84]], dtype= float)
print(marks)
print(type(marks))
print(marks.dtype)
1D Tensor tensor([1, 2, 3, 4, 5]) <class 'torch.Tensor'> torch.int64 2D Tensor tensor([[68., 72., 36., 72., 81.], [89., 91., 71., 69., 84.]], dtype=torch.float64) <class 'torch.Tensor'> torch.float64

What if we pass some string values to the tensor, lets check!

names = torch.tensor(['Abdullah', 'Adam', 'Achars', 'Arushi', 'Ayerah'])
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-137-b42f3bab7670> in <module> ----> 1 names = torch.tensor(['Abdullah', 'Adam', 'Achars', 'Arushi', 'Ayerah']) ValueError: too many dimensions 'str'