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

Let's do a 'touch' on Tensors with Pytorch

Pytorch is an open-source neural network frameworks developed by Facebook. It has many powerful applications. At its core, it is a library for processing and operating on Tensors. A tensor is a number (e.g 15), vector (e.g [2, 4, 6,8], matrix (e.g [[2, 4, 6], [3, 5, 7]]) or multi-dimentional arrays of elements (e.g [[[2, 4, 6], [3, 5, 7]], [[1, 2, 3], [11, 12, 13]]]. Pytorch include a broad functions for various operations on tensors. Pytorch has an extensive functions for performing various mathematical operations and other vital operations such as checking, creating, indexing, slicing, joining, concatenating, serialization, sampling, disabling gradient, comparing and the very vital math operations on tensors. In this tutorial, I will be discussing five of these pytorch tensor functions that are essential for deep learning tasks.

  • as_tensor
  • randn
  • arange
  • div
  • enable_grad

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
import numpy as np

Function 1 - torch.as_tensor

This function is used to convert data into torch.Tensor object. It takes one required parameter of the data to be converted and two optional parameters for dtype and device as illusrated below:
torch.as_tensor(data, dtype=None, device=None)

# Example 1 - working 
arr = np.array([1, 2, 3, 4, 5, 6])
t = torch.as_tensor(arr)
t
tensor([1, 2, 3, 4, 5, 6])